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       break;
1578     default:
1579       if (Size > 32)
1580         return false;
1581 
1582       break;
1583     }
1584 
1585     if (IsFast) {
1586       // FIXME: Lie it is fast if +unaligned-access-mode is passed so that
1587       // DS accesses get vectorized.
1588       *IsFast = Alignment >= RequiredAlignment ||
1589                 Subtarget->hasUnalignedDSAccessEnabled();
1590     }
1591 
1592     return Alignment >= RequiredAlignment ||
1593            Subtarget->hasUnalignedDSAccessEnabled();
1594   }
1595 
1596   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1597     bool AlignedBy4 = Alignment >= Align(4);
1598     if (IsFast)
1599       *IsFast = AlignedBy4;
1600 
1601     return AlignedBy4 ||
1602            Subtarget->enableFlatScratch() ||
1603            Subtarget->hasUnalignedScratchAccess();
1604   }
1605 
1606   // FIXME: We have to be conservative here and assume that flat operations
1607   // will access scratch.  If we had access to the IR function, then we
1608   // could determine if any private memory was used in the function.
1609   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1610       !Subtarget->hasUnalignedScratchAccess()) {
1611     bool AlignedBy4 = Alignment >= Align(4);
1612     if (IsFast)
1613       *IsFast = AlignedBy4;
1614 
1615     return AlignedBy4;
1616   }
1617 
1618   if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1619     // If we have a uniform constant load, it still requires using a slow
1620     // buffer instruction if unaligned.
1621     if (IsFast) {
1622       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1623       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1624       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1625                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1626         Alignment >= Align(4) : Alignment != Align(2);
1627     }
1628 
1629     return true;
1630   }
1631 
1632   // Smaller than dword value must be aligned.
1633   if (Size < 32)
1634     return false;
1635 
1636   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1637   // byte-address are ignored, thus forcing Dword alignment.
1638   // This applies to private, global, and constant memory.
1639   if (IsFast)
1640     *IsFast = true;
1641 
1642   return Size >= 32 && Alignment >= Align(4);
1643 }
1644 
1645 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1646     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1647     bool *IsFast) const {
1648   if (IsFast)
1649     *IsFast = false;
1650 
1651   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1652   // which isn't a simple VT.
1653   // Until MVT is extended to handle this, simply check for the size and
1654   // rely on the condition below: allow accesses if the size is a multiple of 4.
1655   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1656                            VT.getStoreSize() > 16)) {
1657     return false;
1658   }
1659 
1660   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1661                                             Alignment, Flags, IsFast);
1662 }
1663 
1664 EVT SITargetLowering::getOptimalMemOpType(
1665     const MemOp &Op, const AttributeList &FuncAttributes) const {
1666   // FIXME: Should account for address space here.
1667 
1668   // The default fallback uses the private pointer size as a guess for a type to
1669   // use. Make sure we switch these to 64-bit accesses.
1670 
1671   if (Op.size() >= 16 &&
1672       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1673     return MVT::v4i32;
1674 
1675   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1676     return MVT::v2i32;
1677 
1678   // Use the default.
1679   return MVT::Other;
1680 }
1681 
1682 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1683   const MemSDNode *MemNode = cast<MemSDNode>(N);
1684   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1685 }
1686 
1687 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1688   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1689          AS == AMDGPUAS::PRIVATE_ADDRESS;
1690 }
1691 
1692 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1693                                            unsigned DestAS) const {
1694   // Flat -> private/local is a simple truncate.
1695   // Flat -> global is no-op
1696   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1697     return true;
1698 
1699   const GCNTargetMachine &TM =
1700       static_cast<const GCNTargetMachine &>(getTargetMachine());
1701   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1702 }
1703 
1704 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1705   const MemSDNode *MemNode = cast<MemSDNode>(N);
1706 
1707   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1708 }
1709 
1710 TargetLoweringBase::LegalizeTypeAction
1711 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1712   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1713       VT.getScalarType().bitsLE(MVT::i16))
1714     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1715   return TargetLoweringBase::getPreferredVectorAction(VT);
1716 }
1717 
1718 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1719                                                          Type *Ty) const {
1720   // FIXME: Could be smarter if called for vector constants.
1721   return true;
1722 }
1723 
1724 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1725   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1726     switch (Op) {
1727     case ISD::LOAD:
1728     case ISD::STORE:
1729 
1730     // These operations are done with 32-bit instructions anyway.
1731     case ISD::AND:
1732     case ISD::OR:
1733     case ISD::XOR:
1734     case ISD::SELECT:
1735       // TODO: Extensions?
1736       return true;
1737     default:
1738       return false;
1739     }
1740   }
1741 
1742   // SimplifySetCC uses this function to determine whether or not it should
1743   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1744   if (VT == MVT::i1 && Op == ISD::SETCC)
1745     return false;
1746 
1747   return TargetLowering::isTypeDesirableForOp(Op, VT);
1748 }
1749 
1750 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1751                                                    const SDLoc &SL,
1752                                                    SDValue Chain,
1753                                                    uint64_t Offset) const {
1754   const DataLayout &DL = DAG.getDataLayout();
1755   MachineFunction &MF = DAG.getMachineFunction();
1756   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1757 
1758   const ArgDescriptor *InputPtrReg;
1759   const TargetRegisterClass *RC;
1760   LLT ArgTy;
1761   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1762 
1763   std::tie(InputPtrReg, RC, ArgTy) =
1764       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1765 
1766   // We may not have the kernarg segment argument if we have no kernel
1767   // arguments.
1768   if (!InputPtrReg)
1769     return DAG.getConstant(0, SL, PtrVT);
1770 
1771   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1772   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1773     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1774 
1775   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1776 }
1777 
1778 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1779                                             const SDLoc &SL) const {
1780   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1781                                                FIRST_IMPLICIT);
1782   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1783 }
1784 
1785 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1786                                          const SDLoc &SL, SDValue Val,
1787                                          bool Signed,
1788                                          const ISD::InputArg *Arg) const {
1789   // First, if it is a widened vector, narrow it.
1790   if (VT.isVector() &&
1791       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1792     EVT NarrowedVT =
1793         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1794                          VT.getVectorNumElements());
1795     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1796                       DAG.getConstant(0, SL, MVT::i32));
1797   }
1798 
1799   // Then convert the vector elements or scalar value.
1800   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1801       VT.bitsLT(MemVT)) {
1802     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1803     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1804   }
1805 
1806   if (MemVT.isFloatingPoint())
1807     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1808   else if (Signed)
1809     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1810   else
1811     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1812 
1813   return Val;
1814 }
1815 
1816 SDValue SITargetLowering::lowerKernargMemParameter(
1817     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1818     uint64_t Offset, Align Alignment, bool Signed,
1819     const ISD::InputArg *Arg) const {
1820   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1821 
1822   // Try to avoid using an extload by loading earlier than the argument address,
1823   // and extracting the relevant bits. The load should hopefully be merged with
1824   // the previous argument.
1825   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1826     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1827     int64_t AlignDownOffset = alignDown(Offset, 4);
1828     int64_t OffsetDiff = Offset - AlignDownOffset;
1829 
1830     EVT IntVT = MemVT.changeTypeToInteger();
1831 
1832     // TODO: If we passed in the base kernel offset we could have a better
1833     // alignment than 4, but we don't really need it.
1834     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1835     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1836                                MachineMemOperand::MODereferenceable |
1837                                    MachineMemOperand::MOInvariant);
1838 
1839     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1840     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1841 
1842     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1843     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1844     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1845 
1846 
1847     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1848   }
1849 
1850   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1851   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1852                              MachineMemOperand::MODereferenceable |
1853                                  MachineMemOperand::MOInvariant);
1854 
1855   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1856   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1857 }
1858 
1859 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1860                                               const SDLoc &SL, SDValue Chain,
1861                                               const ISD::InputArg &Arg) const {
1862   MachineFunction &MF = DAG.getMachineFunction();
1863   MachineFrameInfo &MFI = MF.getFrameInfo();
1864 
1865   if (Arg.Flags.isByVal()) {
1866     unsigned Size = Arg.Flags.getByValSize();
1867     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1868     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1869   }
1870 
1871   unsigned ArgOffset = VA.getLocMemOffset();
1872   unsigned ArgSize = VA.getValVT().getStoreSize();
1873 
1874   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1875 
1876   // Create load nodes to retrieve arguments from the stack.
1877   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1878   SDValue ArgValue;
1879 
1880   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1881   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1882   MVT MemVT = VA.getValVT();
1883 
1884   switch (VA.getLocInfo()) {
1885   default:
1886     break;
1887   case CCValAssign::BCvt:
1888     MemVT = VA.getLocVT();
1889     break;
1890   case CCValAssign::SExt:
1891     ExtType = ISD::SEXTLOAD;
1892     break;
1893   case CCValAssign::ZExt:
1894     ExtType = ISD::ZEXTLOAD;
1895     break;
1896   case CCValAssign::AExt:
1897     ExtType = ISD::EXTLOAD;
1898     break;
1899   }
1900 
1901   ArgValue = DAG.getExtLoad(
1902     ExtType, SL, VA.getLocVT(), Chain, FIN,
1903     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1904     MemVT);
1905   return ArgValue;
1906 }
1907 
1908 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1909   const SIMachineFunctionInfo &MFI,
1910   EVT VT,
1911   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1912   const ArgDescriptor *Reg;
1913   const TargetRegisterClass *RC;
1914   LLT Ty;
1915 
1916   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1917   if (!Reg) {
1918     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1919       // It's possible for a kernarg intrinsic call to appear in a kernel with
1920       // no allocated segment, in which case we do not add the user sgpr
1921       // argument, so just return null.
1922       return DAG.getConstant(0, SDLoc(), VT);
1923     }
1924 
1925     // It's undefined behavior if a function marked with the amdgpu-no-*
1926     // attributes uses the corresponding intrinsic.
1927     return DAG.getUNDEF(VT);
1928   }
1929 
1930   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1931 }
1932 
1933 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1934                                CallingConv::ID CallConv,
1935                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1936                                FunctionType *FType,
1937                                SIMachineFunctionInfo *Info) {
1938   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1939     const ISD::InputArg *Arg = &Ins[I];
1940 
1941     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1942            "vector type argument should have been split");
1943 
1944     // First check if it's a PS input addr.
1945     if (CallConv == CallingConv::AMDGPU_PS &&
1946         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1947       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1948 
1949       // Inconveniently only the first part of the split is marked as isSplit,
1950       // so skip to the end. We only want to increment PSInputNum once for the
1951       // entire split argument.
1952       if (Arg->Flags.isSplit()) {
1953         while (!Arg->Flags.isSplitEnd()) {
1954           assert((!Arg->VT.isVector() ||
1955                   Arg->VT.getScalarSizeInBits() == 16) &&
1956                  "unexpected vector split in ps argument type");
1957           if (!SkipArg)
1958             Splits.push_back(*Arg);
1959           Arg = &Ins[++I];
1960         }
1961       }
1962 
1963       if (SkipArg) {
1964         // We can safely skip PS inputs.
1965         Skipped.set(Arg->getOrigArgIndex());
1966         ++PSInputNum;
1967         continue;
1968       }
1969 
1970       Info->markPSInputAllocated(PSInputNum);
1971       if (Arg->Used)
1972         Info->markPSInputEnabled(PSInputNum);
1973 
1974       ++PSInputNum;
1975     }
1976 
1977     Splits.push_back(*Arg);
1978   }
1979 }
1980 
1981 // Allocate special inputs passed in VGPRs.
1982 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1983                                                       MachineFunction &MF,
1984                                                       const SIRegisterInfo &TRI,
1985                                                       SIMachineFunctionInfo &Info) const {
1986   const LLT S32 = LLT::scalar(32);
1987   MachineRegisterInfo &MRI = MF.getRegInfo();
1988 
1989   if (Info.hasWorkItemIDX()) {
1990     Register Reg = AMDGPU::VGPR0;
1991     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1992 
1993     CCInfo.AllocateReg(Reg);
1994     unsigned Mask = (Subtarget->hasPackedTID() &&
1995                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1996     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1997   }
1998 
1999   if (Info.hasWorkItemIDY()) {
2000     assert(Info.hasWorkItemIDX());
2001     if (Subtarget->hasPackedTID()) {
2002       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2003                                                         0x3ff << 10));
2004     } else {
2005       unsigned Reg = AMDGPU::VGPR1;
2006       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2007 
2008       CCInfo.AllocateReg(Reg);
2009       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
2010     }
2011   }
2012 
2013   if (Info.hasWorkItemIDZ()) {
2014     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
2015     if (Subtarget->hasPackedTID()) {
2016       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2017                                                         0x3ff << 20));
2018     } else {
2019       unsigned Reg = AMDGPU::VGPR2;
2020       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2021 
2022       CCInfo.AllocateReg(Reg);
2023       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
2024     }
2025   }
2026 }
2027 
2028 // Try to allocate a VGPR at the end of the argument list, or if no argument
2029 // VGPRs are left allocating a stack slot.
2030 // If \p Mask is is given it indicates bitfield position in the register.
2031 // If \p Arg is given use it with new ]p Mask instead of allocating new.
2032 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2033                                          ArgDescriptor Arg = ArgDescriptor()) {
2034   if (Arg.isSet())
2035     return ArgDescriptor::createArg(Arg, Mask);
2036 
2037   ArrayRef<MCPhysReg> ArgVGPRs
2038     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2039   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2040   if (RegIdx == ArgVGPRs.size()) {
2041     // Spill to stack required.
2042     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2043 
2044     return ArgDescriptor::createStack(Offset, Mask);
2045   }
2046 
2047   unsigned Reg = ArgVGPRs[RegIdx];
2048   Reg = CCInfo.AllocateReg(Reg);
2049   assert(Reg != AMDGPU::NoRegister);
2050 
2051   MachineFunction &MF = CCInfo.getMachineFunction();
2052   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2053   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2054   return ArgDescriptor::createRegister(Reg, Mask);
2055 }
2056 
2057 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2058                                              const TargetRegisterClass *RC,
2059                                              unsigned NumArgRegs) {
2060   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2061   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2062   if (RegIdx == ArgSGPRs.size())
2063     report_fatal_error("ran out of SGPRs for arguments");
2064 
2065   unsigned Reg = ArgSGPRs[RegIdx];
2066   Reg = CCInfo.AllocateReg(Reg);
2067   assert(Reg != AMDGPU::NoRegister);
2068 
2069   MachineFunction &MF = CCInfo.getMachineFunction();
2070   MF.addLiveIn(Reg, RC);
2071   return ArgDescriptor::createRegister(Reg);
2072 }
2073 
2074 // If this has a fixed position, we still should allocate the register in the
2075 // CCInfo state. Technically we could get away with this for values passed
2076 // outside of the normal argument range.
2077 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2078                                        const TargetRegisterClass *RC,
2079                                        MCRegister Reg) {
2080   Reg = CCInfo.AllocateReg(Reg);
2081   assert(Reg != AMDGPU::NoRegister);
2082   MachineFunction &MF = CCInfo.getMachineFunction();
2083   MF.addLiveIn(Reg, RC);
2084 }
2085 
2086 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2087   if (Arg) {
2088     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2089                                Arg.getRegister());
2090   } else
2091     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2092 }
2093 
2094 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2095   if (Arg) {
2096     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2097                                Arg.getRegister());
2098   } else
2099     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2100 }
2101 
2102 /// Allocate implicit function VGPR arguments at the end of allocated user
2103 /// arguments.
2104 void SITargetLowering::allocateSpecialInputVGPRs(
2105   CCState &CCInfo, MachineFunction &MF,
2106   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2107   const unsigned Mask = 0x3ff;
2108   ArgDescriptor Arg;
2109 
2110   if (Info.hasWorkItemIDX()) {
2111     Arg = allocateVGPR32Input(CCInfo, Mask);
2112     Info.setWorkItemIDX(Arg);
2113   }
2114 
2115   if (Info.hasWorkItemIDY()) {
2116     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2117     Info.setWorkItemIDY(Arg);
2118   }
2119 
2120   if (Info.hasWorkItemIDZ())
2121     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2122 }
2123 
2124 /// Allocate implicit function VGPR arguments in fixed registers.
2125 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2126   CCState &CCInfo, MachineFunction &MF,
2127   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2128   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2129   if (!Reg)
2130     report_fatal_error("failed to allocated VGPR for implicit arguments");
2131 
2132   const unsigned Mask = 0x3ff;
2133   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2134   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2135   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2136 }
2137 
2138 void SITargetLowering::allocateSpecialInputSGPRs(
2139   CCState &CCInfo,
2140   MachineFunction &MF,
2141   const SIRegisterInfo &TRI,
2142   SIMachineFunctionInfo &Info) const {
2143   auto &ArgInfo = Info.getArgInfo();
2144 
2145   // TODO: Unify handling with private memory pointers.
2146   if (Info.hasDispatchPtr())
2147     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2148 
2149   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2150     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2151 
2152   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2153   // constant offset from the kernarg segment.
2154   if (Info.hasImplicitArgPtr())
2155     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2156 
2157   if (Info.hasDispatchID())
2158     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2159 
2160   // flat_scratch_init is not applicable for non-kernel functions.
2161 
2162   if (Info.hasWorkGroupIDX())
2163     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2164 
2165   if (Info.hasWorkGroupIDY())
2166     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2167 
2168   if (Info.hasWorkGroupIDZ())
2169     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2170 }
2171 
2172 // Allocate special inputs passed in user SGPRs.
2173 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2174                                             MachineFunction &MF,
2175                                             const SIRegisterInfo &TRI,
2176                                             SIMachineFunctionInfo &Info) const {
2177   if (Info.hasImplicitBufferPtr()) {
2178     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2179     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2180     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2181   }
2182 
2183   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2184   if (Info.hasPrivateSegmentBuffer()) {
2185     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2186     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2187     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2188   }
2189 
2190   if (Info.hasDispatchPtr()) {
2191     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2192     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2193     CCInfo.AllocateReg(DispatchPtrReg);
2194   }
2195 
2196   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2197     Register QueuePtrReg = Info.addQueuePtr(TRI);
2198     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2199     CCInfo.AllocateReg(QueuePtrReg);
2200   }
2201 
2202   if (Info.hasKernargSegmentPtr()) {
2203     MachineRegisterInfo &MRI = MF.getRegInfo();
2204     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2205     CCInfo.AllocateReg(InputPtrReg);
2206 
2207     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2208     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2209   }
2210 
2211   if (Info.hasDispatchID()) {
2212     Register DispatchIDReg = Info.addDispatchID(TRI);
2213     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2214     CCInfo.AllocateReg(DispatchIDReg);
2215   }
2216 
2217   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2218     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2219     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2220     CCInfo.AllocateReg(FlatScratchInitReg);
2221   }
2222 
2223   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2224   // these from the dispatch pointer.
2225 }
2226 
2227 // Allocate special input registers that are initialized per-wave.
2228 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2229                                            MachineFunction &MF,
2230                                            SIMachineFunctionInfo &Info,
2231                                            CallingConv::ID CallConv,
2232                                            bool IsShader) const {
2233   if (Info.hasWorkGroupIDX()) {
2234     Register Reg = Info.addWorkGroupIDX();
2235     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2236     CCInfo.AllocateReg(Reg);
2237   }
2238 
2239   if (Info.hasWorkGroupIDY()) {
2240     Register Reg = Info.addWorkGroupIDY();
2241     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2242     CCInfo.AllocateReg(Reg);
2243   }
2244 
2245   if (Info.hasWorkGroupIDZ()) {
2246     Register Reg = Info.addWorkGroupIDZ();
2247     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2248     CCInfo.AllocateReg(Reg);
2249   }
2250 
2251   if (Info.hasWorkGroupInfo()) {
2252     Register Reg = Info.addWorkGroupInfo();
2253     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2254     CCInfo.AllocateReg(Reg);
2255   }
2256 
2257   if (Info.hasPrivateSegmentWaveByteOffset()) {
2258     // Scratch wave offset passed in system SGPR.
2259     unsigned PrivateSegmentWaveByteOffsetReg;
2260 
2261     if (IsShader) {
2262       PrivateSegmentWaveByteOffsetReg =
2263         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2264 
2265       // This is true if the scratch wave byte offset doesn't have a fixed
2266       // location.
2267       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2268         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2269         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2270       }
2271     } else
2272       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2273 
2274     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2275     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2276   }
2277 }
2278 
2279 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2280                                      MachineFunction &MF,
2281                                      const SIRegisterInfo &TRI,
2282                                      SIMachineFunctionInfo &Info) {
2283   // Now that we've figured out where the scratch register inputs are, see if
2284   // should reserve the arguments and use them directly.
2285   MachineFrameInfo &MFI = MF.getFrameInfo();
2286   bool HasStackObjects = MFI.hasStackObjects();
2287   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2288 
2289   // Record that we know we have non-spill stack objects so we don't need to
2290   // check all stack objects later.
2291   if (HasStackObjects)
2292     Info.setHasNonSpillStackObjects(true);
2293 
2294   // Everything live out of a block is spilled with fast regalloc, so it's
2295   // almost certain that spilling will be required.
2296   if (TM.getOptLevel() == CodeGenOpt::None)
2297     HasStackObjects = true;
2298 
2299   // For now assume stack access is needed in any callee functions, so we need
2300   // the scratch registers to pass in.
2301   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2302 
2303   if (!ST.enableFlatScratch()) {
2304     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2305       // If we have stack objects, we unquestionably need the private buffer
2306       // resource. For the Code Object V2 ABI, this will be the first 4 user
2307       // SGPR inputs. We can reserve those and use them directly.
2308 
2309       Register PrivateSegmentBufferReg =
2310           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2311       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2312     } else {
2313       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2314       // We tentatively reserve the last registers (skipping the last registers
2315       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2316       // we'll replace these with the ones immediately after those which were
2317       // really allocated. In the prologue copies will be inserted from the
2318       // argument to these reserved registers.
2319 
2320       // Without HSA, relocations are used for the scratch pointer and the
2321       // buffer resource setup is always inserted in the prologue. Scratch wave
2322       // offset is still in an input SGPR.
2323       Info.setScratchRSrcReg(ReservedBufferReg);
2324     }
2325   }
2326 
2327   MachineRegisterInfo &MRI = MF.getRegInfo();
2328 
2329   // For entry functions we have to set up the stack pointer if we use it,
2330   // whereas non-entry functions get this "for free". This means there is no
2331   // intrinsic advantage to using S32 over S34 in cases where we do not have
2332   // calls but do need a frame pointer (i.e. if we are requested to have one
2333   // because frame pointer elimination is disabled). To keep things simple we
2334   // only ever use S32 as the call ABI stack pointer, and so using it does not
2335   // imply we need a separate frame pointer.
2336   //
2337   // Try to use s32 as the SP, but move it if it would interfere with input
2338   // arguments. This won't work with calls though.
2339   //
2340   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2341   // registers.
2342   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2343     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2344   } else {
2345     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2346 
2347     if (MFI.hasCalls())
2348       report_fatal_error("call in graphics shader with too many input SGPRs");
2349 
2350     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2351       if (!MRI.isLiveIn(Reg)) {
2352         Info.setStackPtrOffsetReg(Reg);
2353         break;
2354       }
2355     }
2356 
2357     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2358       report_fatal_error("failed to find register for SP");
2359   }
2360 
2361   // hasFP should be accurate for entry functions even before the frame is
2362   // finalized, because it does not rely on the known stack size, only
2363   // properties like whether variable sized objects are present.
2364   if (ST.getFrameLowering()->hasFP(MF)) {
2365     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2366   }
2367 }
2368 
2369 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2370   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2371   return !Info->isEntryFunction();
2372 }
2373 
2374 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2375 
2376 }
2377 
2378 void SITargetLowering::insertCopiesSplitCSR(
2379   MachineBasicBlock *Entry,
2380   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2381   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2382 
2383   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2384   if (!IStart)
2385     return;
2386 
2387   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2388   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2389   MachineBasicBlock::iterator MBBI = Entry->begin();
2390   for (const MCPhysReg *I = IStart; *I; ++I) {
2391     const TargetRegisterClass *RC = nullptr;
2392     if (AMDGPU::SReg_64RegClass.contains(*I))
2393       RC = &AMDGPU::SGPR_64RegClass;
2394     else if (AMDGPU::SReg_32RegClass.contains(*I))
2395       RC = &AMDGPU::SGPR_32RegClass;
2396     else
2397       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2398 
2399     Register NewVR = MRI->createVirtualRegister(RC);
2400     // Create copy from CSR to a virtual register.
2401     Entry->addLiveIn(*I);
2402     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2403       .addReg(*I);
2404 
2405     // Insert the copy-back instructions right before the terminator.
2406     for (auto *Exit : Exits)
2407       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2408               TII->get(TargetOpcode::COPY), *I)
2409         .addReg(NewVR);
2410   }
2411 }
2412 
2413 SDValue SITargetLowering::LowerFormalArguments(
2414     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2415     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2416     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2417   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2418 
2419   MachineFunction &MF = DAG.getMachineFunction();
2420   const Function &Fn = MF.getFunction();
2421   FunctionType *FType = MF.getFunction().getFunctionType();
2422   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2423 
2424   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2425     DiagnosticInfoUnsupported NoGraphicsHSA(
2426         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2427     DAG.getContext()->diagnose(NoGraphicsHSA);
2428     return DAG.getEntryNode();
2429   }
2430 
2431   Info->allocateModuleLDSGlobal(Fn.getParent());
2432 
2433   SmallVector<ISD::InputArg, 16> Splits;
2434   SmallVector<CCValAssign, 16> ArgLocs;
2435   BitVector Skipped(Ins.size());
2436   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2437                  *DAG.getContext());
2438 
2439   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2440   bool IsKernel = AMDGPU::isKernel(CallConv);
2441   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2442 
2443   if (IsGraphics) {
2444     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2445            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2446            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2447            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2448            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2449            !Info->hasWorkItemIDZ());
2450   }
2451 
2452   if (CallConv == CallingConv::AMDGPU_PS) {
2453     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2454 
2455     // At least one interpolation mode must be enabled or else the GPU will
2456     // hang.
2457     //
2458     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2459     // set PSInputAddr, the user wants to enable some bits after the compilation
2460     // based on run-time states. Since we can't know what the final PSInputEna
2461     // will look like, so we shouldn't do anything here and the user should take
2462     // responsibility for the correct programming.
2463     //
2464     // Otherwise, the following restrictions apply:
2465     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2466     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2467     //   enabled too.
2468     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2469         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2470       CCInfo.AllocateReg(AMDGPU::VGPR0);
2471       CCInfo.AllocateReg(AMDGPU::VGPR1);
2472       Info->markPSInputAllocated(0);
2473       Info->markPSInputEnabled(0);
2474     }
2475     if (Subtarget->isAmdPalOS()) {
2476       // For isAmdPalOS, the user does not enable some bits after compilation
2477       // based on run-time states; the register values being generated here are
2478       // the final ones set in hardware. Therefore we need to apply the
2479       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2480       // a bit is set in PSInputAddr but not PSInputEnable is where the
2481       // frontend set up an input arg for a particular interpolation mode, but
2482       // nothing uses that input arg. Really we should have an earlier pass
2483       // that removes such an arg.)
2484       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2485       if ((PsInputBits & 0x7F) == 0 ||
2486           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2487         Info->markPSInputEnabled(
2488             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2489     }
2490   } else if (IsKernel) {
2491     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2492   } else {
2493     Splits.append(Ins.begin(), Ins.end());
2494   }
2495 
2496   if (IsEntryFunc) {
2497     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2498     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2499   } else if (!IsGraphics) {
2500     // For the fixed ABI, pass workitem IDs in the last argument register.
2501     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2502   }
2503 
2504   if (IsKernel) {
2505     analyzeFormalArgumentsCompute(CCInfo, Ins);
2506   } else {
2507     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2508     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2509   }
2510 
2511   SmallVector<SDValue, 16> Chains;
2512 
2513   // FIXME: This is the minimum kernel argument alignment. We should improve
2514   // this to the maximum alignment of the arguments.
2515   //
2516   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2517   // kern arg offset.
2518   const Align KernelArgBaseAlign = Align(16);
2519 
2520   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2521     const ISD::InputArg &Arg = Ins[i];
2522     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2523       InVals.push_back(DAG.getUNDEF(Arg.VT));
2524       continue;
2525     }
2526 
2527     CCValAssign &VA = ArgLocs[ArgIdx++];
2528     MVT VT = VA.getLocVT();
2529 
2530     if (IsEntryFunc && VA.isMemLoc()) {
2531       VT = Ins[i].VT;
2532       EVT MemVT = VA.getLocVT();
2533 
2534       const uint64_t Offset = VA.getLocMemOffset();
2535       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2536 
2537       if (Arg.Flags.isByRef()) {
2538         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2539 
2540         const GCNTargetMachine &TM =
2541             static_cast<const GCNTargetMachine &>(getTargetMachine());
2542         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2543                                     Arg.Flags.getPointerAddrSpace())) {
2544           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2545                                      Arg.Flags.getPointerAddrSpace());
2546         }
2547 
2548         InVals.push_back(Ptr);
2549         continue;
2550       }
2551 
2552       SDValue Arg = lowerKernargMemParameter(
2553         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2554       Chains.push_back(Arg.getValue(1));
2555 
2556       auto *ParamTy =
2557         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2558       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2559           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2560                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2561         // On SI local pointers are just offsets into LDS, so they are always
2562         // less than 16-bits.  On CI and newer they could potentially be
2563         // real pointers, so we can't guarantee their size.
2564         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2565                           DAG.getValueType(MVT::i16));
2566       }
2567 
2568       InVals.push_back(Arg);
2569       continue;
2570     } else if (!IsEntryFunc && VA.isMemLoc()) {
2571       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2572       InVals.push_back(Val);
2573       if (!Arg.Flags.isByVal())
2574         Chains.push_back(Val.getValue(1));
2575       continue;
2576     }
2577 
2578     assert(VA.isRegLoc() && "Parameter must be in a register!");
2579 
2580     Register Reg = VA.getLocReg();
2581     const TargetRegisterClass *RC = nullptr;
2582     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2583       RC = &AMDGPU::VGPR_32RegClass;
2584     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2585       RC = &AMDGPU::SGPR_32RegClass;
2586     else
2587       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2588     EVT ValVT = VA.getValVT();
2589 
2590     Reg = MF.addLiveIn(Reg, RC);
2591     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2592 
2593     if (Arg.Flags.isSRet()) {
2594       // The return object should be reasonably addressable.
2595 
2596       // FIXME: This helps when the return is a real sret. If it is a
2597       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2598       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2599       unsigned NumBits
2600         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2601       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2602         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2603     }
2604 
2605     // If this is an 8 or 16-bit value, it is really passed promoted
2606     // to 32 bits. Insert an assert[sz]ext to capture this, then
2607     // truncate to the right size.
2608     switch (VA.getLocInfo()) {
2609     case CCValAssign::Full:
2610       break;
2611     case CCValAssign::BCvt:
2612       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2613       break;
2614     case CCValAssign::SExt:
2615       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2616                         DAG.getValueType(ValVT));
2617       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2618       break;
2619     case CCValAssign::ZExt:
2620       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2621                         DAG.getValueType(ValVT));
2622       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2623       break;
2624     case CCValAssign::AExt:
2625       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2626       break;
2627     default:
2628       llvm_unreachable("Unknown loc info!");
2629     }
2630 
2631     InVals.push_back(Val);
2632   }
2633 
2634   // Start adding system SGPRs.
2635   if (IsEntryFunc) {
2636     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2637   } else {
2638     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2639     if (!IsGraphics)
2640       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2641   }
2642 
2643   auto &ArgUsageInfo =
2644     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2645   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2646 
2647   unsigned StackArgSize = CCInfo.getNextStackOffset();
2648   Info->setBytesInStackArgArea(StackArgSize);
2649 
2650   return Chains.empty() ? Chain :
2651     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2652 }
2653 
2654 // TODO: If return values can't fit in registers, we should return as many as
2655 // possible in registers before passing on stack.
2656 bool SITargetLowering::CanLowerReturn(
2657   CallingConv::ID CallConv,
2658   MachineFunction &MF, bool IsVarArg,
2659   const SmallVectorImpl<ISD::OutputArg> &Outs,
2660   LLVMContext &Context) const {
2661   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2662   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2663   // for shaders. Vector types should be explicitly handled by CC.
2664   if (AMDGPU::isEntryFunctionCC(CallConv))
2665     return true;
2666 
2667   SmallVector<CCValAssign, 16> RVLocs;
2668   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2669   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2670 }
2671 
2672 SDValue
2673 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2674                               bool isVarArg,
2675                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2676                               const SmallVectorImpl<SDValue> &OutVals,
2677                               const SDLoc &DL, SelectionDAG &DAG) const {
2678   MachineFunction &MF = DAG.getMachineFunction();
2679   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2680 
2681   if (AMDGPU::isKernel(CallConv)) {
2682     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2683                                              OutVals, DL, DAG);
2684   }
2685 
2686   bool IsShader = AMDGPU::isShader(CallConv);
2687 
2688   Info->setIfReturnsVoid(Outs.empty());
2689   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2690 
2691   // CCValAssign - represent the assignment of the return value to a location.
2692   SmallVector<CCValAssign, 48> RVLocs;
2693   SmallVector<ISD::OutputArg, 48> Splits;
2694 
2695   // CCState - Info about the registers and stack slots.
2696   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2697                  *DAG.getContext());
2698 
2699   // Analyze outgoing return values.
2700   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2701 
2702   SDValue Flag;
2703   SmallVector<SDValue, 48> RetOps;
2704   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2705 
2706   // Copy the result values into the output registers.
2707   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2708        ++I, ++RealRVLocIdx) {
2709     CCValAssign &VA = RVLocs[I];
2710     assert(VA.isRegLoc() && "Can only return in registers!");
2711     // TODO: Partially return in registers if return values don't fit.
2712     SDValue Arg = OutVals[RealRVLocIdx];
2713 
2714     // Copied from other backends.
2715     switch (VA.getLocInfo()) {
2716     case CCValAssign::Full:
2717       break;
2718     case CCValAssign::BCvt:
2719       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2720       break;
2721     case CCValAssign::SExt:
2722       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2723       break;
2724     case CCValAssign::ZExt:
2725       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2726       break;
2727     case CCValAssign::AExt:
2728       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2729       break;
2730     default:
2731       llvm_unreachable("Unknown loc info!");
2732     }
2733 
2734     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2735     Flag = Chain.getValue(1);
2736     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2737   }
2738 
2739   // FIXME: Does sret work properly?
2740   if (!Info->isEntryFunction()) {
2741     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2742     const MCPhysReg *I =
2743       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2744     if (I) {
2745       for (; *I; ++I) {
2746         if (AMDGPU::SReg_64RegClass.contains(*I))
2747           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2748         else if (AMDGPU::SReg_32RegClass.contains(*I))
2749           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2750         else
2751           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2752       }
2753     }
2754   }
2755 
2756   // Update chain and glue.
2757   RetOps[0] = Chain;
2758   if (Flag.getNode())
2759     RetOps.push_back(Flag);
2760 
2761   unsigned Opc = AMDGPUISD::ENDPGM;
2762   if (!IsWaveEnd)
2763     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2764   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2765 }
2766 
2767 SDValue SITargetLowering::LowerCallResult(
2768     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2769     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2770     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2771     SDValue ThisVal) const {
2772   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2773 
2774   // Assign locations to each value returned by this call.
2775   SmallVector<CCValAssign, 16> RVLocs;
2776   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2777                  *DAG.getContext());
2778   CCInfo.AnalyzeCallResult(Ins, RetCC);
2779 
2780   // Copy all of the result registers out of their specified physreg.
2781   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2782     CCValAssign VA = RVLocs[i];
2783     SDValue Val;
2784 
2785     if (VA.isRegLoc()) {
2786       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2787       Chain = Val.getValue(1);
2788       InFlag = Val.getValue(2);
2789     } else if (VA.isMemLoc()) {
2790       report_fatal_error("TODO: return values in memory");
2791     } else
2792       llvm_unreachable("unknown argument location type");
2793 
2794     switch (VA.getLocInfo()) {
2795     case CCValAssign::Full:
2796       break;
2797     case CCValAssign::BCvt:
2798       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2799       break;
2800     case CCValAssign::ZExt:
2801       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2802                         DAG.getValueType(VA.getValVT()));
2803       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2804       break;
2805     case CCValAssign::SExt:
2806       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2807                         DAG.getValueType(VA.getValVT()));
2808       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2809       break;
2810     case CCValAssign::AExt:
2811       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2812       break;
2813     default:
2814       llvm_unreachable("Unknown loc info!");
2815     }
2816 
2817     InVals.push_back(Val);
2818   }
2819 
2820   return Chain;
2821 }
2822 
2823 // Add code to pass special inputs required depending on used features separate
2824 // from the explicit user arguments present in the IR.
2825 void SITargetLowering::passSpecialInputs(
2826     CallLoweringInfo &CLI,
2827     CCState &CCInfo,
2828     const SIMachineFunctionInfo &Info,
2829     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2830     SmallVectorImpl<SDValue> &MemOpChains,
2831     SDValue Chain) const {
2832   // If we don't have a call site, this was a call inserted by
2833   // legalization. These can never use special inputs.
2834   if (!CLI.CB)
2835     return;
2836 
2837   SelectionDAG &DAG = CLI.DAG;
2838   const SDLoc &DL = CLI.DL;
2839   const Function &F = DAG.getMachineFunction().getFunction();
2840 
2841   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2842   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2843 
2844   const AMDGPUFunctionArgInfo *CalleeArgInfo
2845     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2846   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2847     auto &ArgUsageInfo =
2848       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2849     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2850   }
2851 
2852   // TODO: Unify with private memory register handling. This is complicated by
2853   // the fact that at least in kernels, the input argument is not necessarily
2854   // in the same location as the input.
2855   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2856                              StringLiteral> ImplicitAttrs[] = {
2857     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2858     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2859     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2860     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2861     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2862     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2863     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2864   };
2865 
2866   for (auto Attr : ImplicitAttrs) {
2867     const ArgDescriptor *OutgoingArg;
2868     const TargetRegisterClass *ArgRC;
2869     LLT ArgTy;
2870 
2871     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2872 
2873     // If the callee does not use the attribute value, skip copying the value.
2874     if (CLI.CB->hasFnAttr(Attr.second))
2875       continue;
2876 
2877     std::tie(OutgoingArg, ArgRC, ArgTy) =
2878         CalleeArgInfo->getPreloadedValue(InputID);
2879     if (!OutgoingArg)
2880       continue;
2881 
2882     const ArgDescriptor *IncomingArg;
2883     const TargetRegisterClass *IncomingArgRC;
2884     LLT Ty;
2885     std::tie(IncomingArg, IncomingArgRC, Ty) =
2886         CallerArgInfo.getPreloadedValue(InputID);
2887     assert(IncomingArgRC == ArgRC);
2888 
2889     // All special arguments are ints for now.
2890     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2891     SDValue InputReg;
2892 
2893     if (IncomingArg) {
2894       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2895     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2896       // The implicit arg ptr is special because it doesn't have a corresponding
2897       // input for kernels, and is computed from the kernarg segment pointer.
2898       InputReg = getImplicitArgPtr(DAG, DL);
2899     } else {
2900       // We may have proven the input wasn't needed, although the ABI is
2901       // requiring it. We just need to allocate the register appropriately.
2902       InputReg = DAG.getUNDEF(ArgVT);
2903     }
2904 
2905     if (OutgoingArg->isRegister()) {
2906       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2907       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2908         report_fatal_error("failed to allocate implicit input argument");
2909     } else {
2910       unsigned SpecialArgOffset =
2911           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2912       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2913                                               SpecialArgOffset);
2914       MemOpChains.push_back(ArgStore);
2915     }
2916   }
2917 
2918   // Pack workitem IDs into a single register or pass it as is if already
2919   // packed.
2920   const ArgDescriptor *OutgoingArg;
2921   const TargetRegisterClass *ArgRC;
2922   LLT Ty;
2923 
2924   std::tie(OutgoingArg, ArgRC, Ty) =
2925       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2926   if (!OutgoingArg)
2927     std::tie(OutgoingArg, ArgRC, Ty) =
2928         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2929   if (!OutgoingArg)
2930     std::tie(OutgoingArg, ArgRC, Ty) =
2931         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2932   if (!OutgoingArg)
2933     return;
2934 
2935   const ArgDescriptor *IncomingArgX = std::get<0>(
2936       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2937   const ArgDescriptor *IncomingArgY = std::get<0>(
2938       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2939   const ArgDescriptor *IncomingArgZ = std::get<0>(
2940       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2941 
2942   SDValue InputReg;
2943   SDLoc SL;
2944 
2945   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2946   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2947   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2948 
2949   // If incoming ids are not packed we need to pack them.
2950   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2951       NeedWorkItemIDX) {
2952     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2953       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2954     } else {
2955       InputReg = DAG.getConstant(0, DL, MVT::i32);
2956     }
2957   }
2958 
2959   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2960       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2961     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2962     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2963                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2964     InputReg = InputReg.getNode() ?
2965                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2966   }
2967 
2968   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2969       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2970     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2971     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2972                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2973     InputReg = InputReg.getNode() ?
2974                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2975   }
2976 
2977   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2978     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2979       // We're in a situation where the outgoing function requires the workitem
2980       // ID, but the calling function does not have it (e.g a graphics function
2981       // calling a C calling convention function). This is illegal, but we need
2982       // to produce something.
2983       InputReg = DAG.getUNDEF(MVT::i32);
2984     } else {
2985       // Workitem ids are already packed, any of present incoming arguments
2986       // will carry all required fields.
2987       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2988         IncomingArgX ? *IncomingArgX :
2989         IncomingArgY ? *IncomingArgY :
2990         *IncomingArgZ, ~0u);
2991       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2992     }
2993   }
2994 
2995   if (OutgoingArg->isRegister()) {
2996     if (InputReg)
2997       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2998 
2999     CCInfo.AllocateReg(OutgoingArg->getRegister());
3000   } else {
3001     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
3002     if (InputReg) {
3003       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3004                                               SpecialArgOffset);
3005       MemOpChains.push_back(ArgStore);
3006     }
3007   }
3008 }
3009 
3010 static bool canGuaranteeTCO(CallingConv::ID CC) {
3011   return CC == CallingConv::Fast;
3012 }
3013 
3014 /// Return true if we might ever do TCO for calls with this calling convention.
3015 static bool mayTailCallThisCC(CallingConv::ID CC) {
3016   switch (CC) {
3017   case CallingConv::C:
3018   case CallingConv::AMDGPU_Gfx:
3019     return true;
3020   default:
3021     return canGuaranteeTCO(CC);
3022   }
3023 }
3024 
3025 bool SITargetLowering::isEligibleForTailCallOptimization(
3026     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3027     const SmallVectorImpl<ISD::OutputArg> &Outs,
3028     const SmallVectorImpl<SDValue> &OutVals,
3029     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3030   if (!mayTailCallThisCC(CalleeCC))
3031     return false;
3032 
3033   // For a divergent call target, we need to do a waterfall loop over the
3034   // possible callees which precludes us from using a simple jump.
3035   if (Callee->isDivergent())
3036     return false;
3037 
3038   MachineFunction &MF = DAG.getMachineFunction();
3039   const Function &CallerF = MF.getFunction();
3040   CallingConv::ID CallerCC = CallerF.getCallingConv();
3041   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3042   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3043 
3044   // Kernels aren't callable, and don't have a live in return address so it
3045   // doesn't make sense to do a tail call with entry functions.
3046   if (!CallerPreserved)
3047     return false;
3048 
3049   bool CCMatch = CallerCC == CalleeCC;
3050 
3051   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3052     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3053       return true;
3054     return false;
3055   }
3056 
3057   // TODO: Can we handle var args?
3058   if (IsVarArg)
3059     return false;
3060 
3061   for (const Argument &Arg : CallerF.args()) {
3062     if (Arg.hasByValAttr())
3063       return false;
3064   }
3065 
3066   LLVMContext &Ctx = *DAG.getContext();
3067 
3068   // Check that the call results are passed in the same way.
3069   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3070                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3071                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3072     return false;
3073 
3074   // The callee has to preserve all registers the caller needs to preserve.
3075   if (!CCMatch) {
3076     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3077     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3078       return false;
3079   }
3080 
3081   // Nothing more to check if the callee is taking no arguments.
3082   if (Outs.empty())
3083     return true;
3084 
3085   SmallVector<CCValAssign, 16> ArgLocs;
3086   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3087 
3088   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3089 
3090   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3091   // If the stack arguments for this call do not fit into our own save area then
3092   // the call cannot be made tail.
3093   // TODO: Is this really necessary?
3094   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3095     return false;
3096 
3097   const MachineRegisterInfo &MRI = MF.getRegInfo();
3098   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3099 }
3100 
3101 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3102   if (!CI->isTailCall())
3103     return false;
3104 
3105   const Function *ParentFn = CI->getParent()->getParent();
3106   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3107     return false;
3108   return true;
3109 }
3110 
3111 // The wave scratch offset register is used as the global base pointer.
3112 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3113                                     SmallVectorImpl<SDValue> &InVals) const {
3114   SelectionDAG &DAG = CLI.DAG;
3115   const SDLoc &DL = CLI.DL;
3116   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3117   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3118   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3119   SDValue Chain = CLI.Chain;
3120   SDValue Callee = CLI.Callee;
3121   bool &IsTailCall = CLI.IsTailCall;
3122   CallingConv::ID CallConv = CLI.CallConv;
3123   bool IsVarArg = CLI.IsVarArg;
3124   bool IsSibCall = false;
3125   bool IsThisReturn = false;
3126   MachineFunction &MF = DAG.getMachineFunction();
3127 
3128   if (Callee.isUndef() || isNullConstant(Callee)) {
3129     if (!CLI.IsTailCall) {
3130       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3131         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3132     }
3133 
3134     return Chain;
3135   }
3136 
3137   if (IsVarArg) {
3138     return lowerUnhandledCall(CLI, InVals,
3139                               "unsupported call to variadic function ");
3140   }
3141 
3142   if (!CLI.CB)
3143     report_fatal_error("unsupported libcall legalization");
3144 
3145   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3146     return lowerUnhandledCall(CLI, InVals,
3147                               "unsupported required tail call to function ");
3148   }
3149 
3150   if (AMDGPU::isShader(CallConv)) {
3151     // Note the issue is with the CC of the called function, not of the call
3152     // itself.
3153     return lowerUnhandledCall(CLI, InVals,
3154                               "unsupported call to a shader function ");
3155   }
3156 
3157   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3158       CallConv != CallingConv::AMDGPU_Gfx) {
3159     // Only allow calls with specific calling conventions.
3160     return lowerUnhandledCall(CLI, InVals,
3161                               "unsupported calling convention for call from "
3162                               "graphics shader of function ");
3163   }
3164 
3165   if (IsTailCall) {
3166     IsTailCall = isEligibleForTailCallOptimization(
3167       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3168     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3169       report_fatal_error("failed to perform tail call elimination on a call "
3170                          "site marked musttail");
3171     }
3172 
3173     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3174 
3175     // A sibling call is one where we're under the usual C ABI and not planning
3176     // to change that but can still do a tail call:
3177     if (!TailCallOpt && IsTailCall)
3178       IsSibCall = true;
3179 
3180     if (IsTailCall)
3181       ++NumTailCalls;
3182   }
3183 
3184   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3185   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3186   SmallVector<SDValue, 8> MemOpChains;
3187 
3188   // Analyze operands of the call, assigning locations to each operand.
3189   SmallVector<CCValAssign, 16> ArgLocs;
3190   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3191   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3192 
3193   if (CallConv != CallingConv::AMDGPU_Gfx) {
3194     // With a fixed ABI, allocate fixed registers before user arguments.
3195     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3196   }
3197 
3198   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3199 
3200   // Get a count of how many bytes are to be pushed on the stack.
3201   unsigned NumBytes = CCInfo.getNextStackOffset();
3202 
3203   if (IsSibCall) {
3204     // Since we're not changing the ABI to make this a tail call, the memory
3205     // operands are already available in the caller's incoming argument space.
3206     NumBytes = 0;
3207   }
3208 
3209   // FPDiff is the byte offset of the call's argument area from the callee's.
3210   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3211   // by this amount for a tail call. In a sibling call it must be 0 because the
3212   // caller will deallocate the entire stack and the callee still expects its
3213   // arguments to begin at SP+0. Completely unused for non-tail calls.
3214   int32_t FPDiff = 0;
3215   MachineFrameInfo &MFI = MF.getFrameInfo();
3216 
3217   // Adjust the stack pointer for the new arguments...
3218   // These operations are automatically eliminated by the prolog/epilog pass
3219   if (!IsSibCall) {
3220     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3221 
3222     if (!Subtarget->enableFlatScratch()) {
3223       SmallVector<SDValue, 4> CopyFromChains;
3224 
3225       // In the HSA case, this should be an identity copy.
3226       SDValue ScratchRSrcReg
3227         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3228       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3229       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3230       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3231     }
3232   }
3233 
3234   MVT PtrVT = MVT::i32;
3235 
3236   // Walk the register/memloc assignments, inserting copies/loads.
3237   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3238     CCValAssign &VA = ArgLocs[i];
3239     SDValue Arg = OutVals[i];
3240 
3241     // Promote the value if needed.
3242     switch (VA.getLocInfo()) {
3243     case CCValAssign::Full:
3244       break;
3245     case CCValAssign::BCvt:
3246       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3247       break;
3248     case CCValAssign::ZExt:
3249       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3250       break;
3251     case CCValAssign::SExt:
3252       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3253       break;
3254     case CCValAssign::AExt:
3255       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3256       break;
3257     case CCValAssign::FPExt:
3258       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3259       break;
3260     default:
3261       llvm_unreachable("Unknown loc info!");
3262     }
3263 
3264     if (VA.isRegLoc()) {
3265       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3266     } else {
3267       assert(VA.isMemLoc());
3268 
3269       SDValue DstAddr;
3270       MachinePointerInfo DstInfo;
3271 
3272       unsigned LocMemOffset = VA.getLocMemOffset();
3273       int32_t Offset = LocMemOffset;
3274 
3275       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3276       MaybeAlign Alignment;
3277 
3278       if (IsTailCall) {
3279         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3280         unsigned OpSize = Flags.isByVal() ?
3281           Flags.getByValSize() : VA.getValVT().getStoreSize();
3282 
3283         // FIXME: We can have better than the minimum byval required alignment.
3284         Alignment =
3285             Flags.isByVal()
3286                 ? Flags.getNonZeroByValAlign()
3287                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3288 
3289         Offset = Offset + FPDiff;
3290         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3291 
3292         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3293         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3294 
3295         // Make sure any stack arguments overlapping with where we're storing
3296         // are loaded before this eventual operation. Otherwise they'll be
3297         // clobbered.
3298 
3299         // FIXME: Why is this really necessary? This seems to just result in a
3300         // lot of code to copy the stack and write them back to the same
3301         // locations, which are supposed to be immutable?
3302         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3303       } else {
3304         // Stores to the argument stack area are relative to the stack pointer.
3305         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3306                                         MVT::i32);
3307         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3308         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3309         Alignment =
3310             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3311       }
3312 
3313       if (Outs[i].Flags.isByVal()) {
3314         SDValue SizeNode =
3315             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3316         SDValue Cpy =
3317             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3318                           Outs[i].Flags.getNonZeroByValAlign(),
3319                           /*isVol = */ false, /*AlwaysInline = */ true,
3320                           /*isTailCall = */ false, DstInfo,
3321                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3322 
3323         MemOpChains.push_back(Cpy);
3324       } else {
3325         SDValue Store =
3326             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3327         MemOpChains.push_back(Store);
3328       }
3329     }
3330   }
3331 
3332   if (!MemOpChains.empty())
3333     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3334 
3335   // Build a sequence of copy-to-reg nodes chained together with token chain
3336   // and flag operands which copy the outgoing args into the appropriate regs.
3337   SDValue InFlag;
3338   for (auto &RegToPass : RegsToPass) {
3339     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3340                              RegToPass.second, InFlag);
3341     InFlag = Chain.getValue(1);
3342   }
3343 
3344 
3345   // We don't usually want to end the call-sequence here because we would tidy
3346   // the frame up *after* the call, however in the ABI-changing tail-call case
3347   // we've carefully laid out the parameters so that when sp is reset they'll be
3348   // in the correct location.
3349   if (IsTailCall && !IsSibCall) {
3350     Chain = DAG.getCALLSEQ_END(Chain,
3351                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3352                                DAG.getTargetConstant(0, DL, MVT::i32),
3353                                InFlag, DL);
3354     InFlag = Chain.getValue(1);
3355   }
3356 
3357   std::vector<SDValue> Ops;
3358   Ops.push_back(Chain);
3359   Ops.push_back(Callee);
3360   // Add a redundant copy of the callee global which will not be legalized, as
3361   // we need direct access to the callee later.
3362   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3363     const GlobalValue *GV = GSD->getGlobal();
3364     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3365   } else {
3366     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3367   }
3368 
3369   if (IsTailCall) {
3370     // Each tail call may have to adjust the stack by a different amount, so
3371     // this information must travel along with the operation for eventual
3372     // consumption by emitEpilogue.
3373     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3374   }
3375 
3376   // Add argument registers to the end of the list so that they are known live
3377   // into the call.
3378   for (auto &RegToPass : RegsToPass) {
3379     Ops.push_back(DAG.getRegister(RegToPass.first,
3380                                   RegToPass.second.getValueType()));
3381   }
3382 
3383   // Add a register mask operand representing the call-preserved registers.
3384 
3385   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3386   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3387   assert(Mask && "Missing call preserved mask for calling convention");
3388   Ops.push_back(DAG.getRegisterMask(Mask));
3389 
3390   if (InFlag.getNode())
3391     Ops.push_back(InFlag);
3392 
3393   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3394 
3395   // If we're doing a tall call, use a TC_RETURN here rather than an
3396   // actual call instruction.
3397   if (IsTailCall) {
3398     MFI.setHasTailCall();
3399     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3400   }
3401 
3402   // Returns a chain and a flag for retval copy to use.
3403   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3404   Chain = Call.getValue(0);
3405   InFlag = Call.getValue(1);
3406 
3407   uint64_t CalleePopBytes = NumBytes;
3408   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3409                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3410                              InFlag, DL);
3411   if (!Ins.empty())
3412     InFlag = Chain.getValue(1);
3413 
3414   // Handle result values, copying them out of physregs into vregs that we
3415   // return.
3416   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3417                          InVals, IsThisReturn,
3418                          IsThisReturn ? OutVals[0] : SDValue());
3419 }
3420 
3421 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3422 // except for applying the wave size scale to the increment amount.
3423 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3424     SDValue Op, SelectionDAG &DAG) const {
3425   const MachineFunction &MF = DAG.getMachineFunction();
3426   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3427 
3428   SDLoc dl(Op);
3429   EVT VT = Op.getValueType();
3430   SDValue Tmp1 = Op;
3431   SDValue Tmp2 = Op.getValue(1);
3432   SDValue Tmp3 = Op.getOperand(2);
3433   SDValue Chain = Tmp1.getOperand(0);
3434 
3435   Register SPReg = Info->getStackPtrOffsetReg();
3436 
3437   // Chain the dynamic stack allocation so that it doesn't modify the stack
3438   // pointer when other instructions are using the stack.
3439   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3440 
3441   SDValue Size  = Tmp2.getOperand(1);
3442   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3443   Chain = SP.getValue(1);
3444   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3445   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3446   const TargetFrameLowering *TFL = ST.getFrameLowering();
3447   unsigned Opc =
3448     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3449     ISD::ADD : ISD::SUB;
3450 
3451   SDValue ScaledSize = DAG.getNode(
3452       ISD::SHL, dl, VT, Size,
3453       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3454 
3455   Align StackAlign = TFL->getStackAlign();
3456   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3457   if (Alignment && *Alignment > StackAlign) {
3458     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3459                        DAG.getConstant(-(uint64_t)Alignment->value()
3460                                            << ST.getWavefrontSizeLog2(),
3461                                        dl, VT));
3462   }
3463 
3464   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3465   Tmp2 = DAG.getCALLSEQ_END(
3466       Chain, DAG.getIntPtrConstant(0, dl, true),
3467       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3468 
3469   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3470 }
3471 
3472 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3473                                                   SelectionDAG &DAG) const {
3474   // We only handle constant sizes here to allow non-entry block, static sized
3475   // allocas. A truly dynamic value is more difficult to support because we
3476   // don't know if the size value is uniform or not. If the size isn't uniform,
3477   // we would need to do a wave reduction to get the maximum size to know how
3478   // much to increment the uniform stack pointer.
3479   SDValue Size = Op.getOperand(1);
3480   if (isa<ConstantSDNode>(Size))
3481       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3482 
3483   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3484 }
3485 
3486 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3487                                              const MachineFunction &MF) const {
3488   Register Reg = StringSwitch<Register>(RegName)
3489     .Case("m0", AMDGPU::M0)
3490     .Case("exec", AMDGPU::EXEC)
3491     .Case("exec_lo", AMDGPU::EXEC_LO)
3492     .Case("exec_hi", AMDGPU::EXEC_HI)
3493     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3494     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3495     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3496     .Default(Register());
3497 
3498   if (Reg == AMDGPU::NoRegister) {
3499     report_fatal_error(Twine("invalid register name \""
3500                              + StringRef(RegName)  + "\"."));
3501 
3502   }
3503 
3504   if (!Subtarget->hasFlatScrRegister() &&
3505        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3506     report_fatal_error(Twine("invalid register \""
3507                              + StringRef(RegName)  + "\" for subtarget."));
3508   }
3509 
3510   switch (Reg) {
3511   case AMDGPU::M0:
3512   case AMDGPU::EXEC_LO:
3513   case AMDGPU::EXEC_HI:
3514   case AMDGPU::FLAT_SCR_LO:
3515   case AMDGPU::FLAT_SCR_HI:
3516     if (VT.getSizeInBits() == 32)
3517       return Reg;
3518     break;
3519   case AMDGPU::EXEC:
3520   case AMDGPU::FLAT_SCR:
3521     if (VT.getSizeInBits() == 64)
3522       return Reg;
3523     break;
3524   default:
3525     llvm_unreachable("missing register type checking");
3526   }
3527 
3528   report_fatal_error(Twine("invalid type for register \""
3529                            + StringRef(RegName) + "\"."));
3530 }
3531 
3532 // If kill is not the last instruction, split the block so kill is always a
3533 // proper terminator.
3534 MachineBasicBlock *
3535 SITargetLowering::splitKillBlock(MachineInstr &MI,
3536                                  MachineBasicBlock *BB) const {
3537   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3538   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3539   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3540   return SplitBB;
3541 }
3542 
3543 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3544 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3545 // be the first instruction in the remainder block.
3546 //
3547 /// \returns { LoopBody, Remainder }
3548 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3549 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3550   MachineFunction *MF = MBB.getParent();
3551   MachineBasicBlock::iterator I(&MI);
3552 
3553   // To insert the loop we need to split the block. Move everything after this
3554   // point to a new block, and insert a new empty block between the two.
3555   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3556   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3557   MachineFunction::iterator MBBI(MBB);
3558   ++MBBI;
3559 
3560   MF->insert(MBBI, LoopBB);
3561   MF->insert(MBBI, RemainderBB);
3562 
3563   LoopBB->addSuccessor(LoopBB);
3564   LoopBB->addSuccessor(RemainderBB);
3565 
3566   // Move the rest of the block into a new block.
3567   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3568 
3569   if (InstInLoop) {
3570     auto Next = std::next(I);
3571 
3572     // Move instruction to loop body.
3573     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3574 
3575     // Move the rest of the block.
3576     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3577   } else {
3578     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3579   }
3580 
3581   MBB.addSuccessor(LoopBB);
3582 
3583   return std::make_pair(LoopBB, RemainderBB);
3584 }
3585 
3586 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3587 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3588   MachineBasicBlock *MBB = MI.getParent();
3589   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3590   auto I = MI.getIterator();
3591   auto E = std::next(I);
3592 
3593   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3594     .addImm(0);
3595 
3596   MIBundleBuilder Bundler(*MBB, I, E);
3597   finalizeBundle(*MBB, Bundler.begin());
3598 }
3599 
3600 MachineBasicBlock *
3601 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3602                                          MachineBasicBlock *BB) const {
3603   const DebugLoc &DL = MI.getDebugLoc();
3604 
3605   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3606 
3607   MachineBasicBlock *LoopBB;
3608   MachineBasicBlock *RemainderBB;
3609   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3610 
3611   // Apparently kill flags are only valid if the def is in the same block?
3612   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3613     Src->setIsKill(false);
3614 
3615   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3616 
3617   MachineBasicBlock::iterator I = LoopBB->end();
3618 
3619   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3620     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3621 
3622   // Clear TRAP_STS.MEM_VIOL
3623   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3624     .addImm(0)
3625     .addImm(EncodedReg);
3626 
3627   bundleInstWithWaitcnt(MI);
3628 
3629   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3630 
3631   // Load and check TRAP_STS.MEM_VIOL
3632   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3633     .addImm(EncodedReg);
3634 
3635   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3636   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3637     .addReg(Reg, RegState::Kill)
3638     .addImm(0);
3639   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3640     .addMBB(LoopBB);
3641 
3642   return RemainderBB;
3643 }
3644 
3645 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3646 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3647 // will only do one iteration. In the worst case, this will loop 64 times.
3648 //
3649 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3650 static MachineBasicBlock::iterator
3651 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3652                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3653                        const DebugLoc &DL, const MachineOperand &Idx,
3654                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3655                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3656                        Register &SGPRIdxReg) {
3657 
3658   MachineFunction *MF = OrigBB.getParent();
3659   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3660   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3661   MachineBasicBlock::iterator I = LoopBB.begin();
3662 
3663   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3664   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3665   Register NewExec = MRI.createVirtualRegister(BoolRC);
3666   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3667   Register CondReg = MRI.createVirtualRegister(BoolRC);
3668 
3669   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3670     .addReg(InitReg)
3671     .addMBB(&OrigBB)
3672     .addReg(ResultReg)
3673     .addMBB(&LoopBB);
3674 
3675   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3676     .addReg(InitSaveExecReg)
3677     .addMBB(&OrigBB)
3678     .addReg(NewExec)
3679     .addMBB(&LoopBB);
3680 
3681   // Read the next variant <- also loop target.
3682   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3683       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3684 
3685   // Compare the just read M0 value to all possible Idx values.
3686   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3687       .addReg(CurrentIdxReg)
3688       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3689 
3690   // Update EXEC, save the original EXEC value to VCC.
3691   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3692                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3693           NewExec)
3694     .addReg(CondReg, RegState::Kill);
3695 
3696   MRI.setSimpleHint(NewExec, CondReg);
3697 
3698   if (UseGPRIdxMode) {
3699     if (Offset == 0) {
3700       SGPRIdxReg = CurrentIdxReg;
3701     } else {
3702       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3703       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3704           .addReg(CurrentIdxReg, RegState::Kill)
3705           .addImm(Offset);
3706     }
3707   } else {
3708     // Move index from VCC into M0
3709     if (Offset == 0) {
3710       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3711         .addReg(CurrentIdxReg, RegState::Kill);
3712     } else {
3713       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3714         .addReg(CurrentIdxReg, RegState::Kill)
3715         .addImm(Offset);
3716     }
3717   }
3718 
3719   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3720   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3721   MachineInstr *InsertPt =
3722     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3723                                                   : AMDGPU::S_XOR_B64_term), Exec)
3724       .addReg(Exec)
3725       .addReg(NewExec);
3726 
3727   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3728   // s_cbranch_scc0?
3729 
3730   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3731   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3732     .addMBB(&LoopBB);
3733 
3734   return InsertPt->getIterator();
3735 }
3736 
3737 // This has slightly sub-optimal regalloc when the source vector is killed by
3738 // the read. The register allocator does not understand that the kill is
3739 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3740 // subregister from it, using 1 more VGPR than necessary. This was saved when
3741 // this was expanded after register allocation.
3742 static MachineBasicBlock::iterator
3743 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3744                unsigned InitResultReg, unsigned PhiReg, int Offset,
3745                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3746   MachineFunction *MF = MBB.getParent();
3747   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3748   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3749   MachineRegisterInfo &MRI = MF->getRegInfo();
3750   const DebugLoc &DL = MI.getDebugLoc();
3751   MachineBasicBlock::iterator I(&MI);
3752 
3753   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3754   Register DstReg = MI.getOperand(0).getReg();
3755   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3756   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3757   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3758   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3759 
3760   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3761 
3762   // Save the EXEC mask
3763   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3764     .addReg(Exec);
3765 
3766   MachineBasicBlock *LoopBB;
3767   MachineBasicBlock *RemainderBB;
3768   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3769 
3770   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3771 
3772   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3773                                       InitResultReg, DstReg, PhiReg, TmpExec,
3774                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3775 
3776   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3777   MachineFunction::iterator MBBI(LoopBB);
3778   ++MBBI;
3779   MF->insert(MBBI, LandingPad);
3780   LoopBB->removeSuccessor(RemainderBB);
3781   LandingPad->addSuccessor(RemainderBB);
3782   LoopBB->addSuccessor(LandingPad);
3783   MachineBasicBlock::iterator First = LandingPad->begin();
3784   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3785     .addReg(SaveExec);
3786 
3787   return InsPt;
3788 }
3789 
3790 // Returns subreg index, offset
3791 static std::pair<unsigned, int>
3792 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3793                             const TargetRegisterClass *SuperRC,
3794                             unsigned VecReg,
3795                             int Offset) {
3796   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3797 
3798   // Skip out of bounds offsets, or else we would end up using an undefined
3799   // register.
3800   if (Offset >= NumElts || Offset < 0)
3801     return std::make_pair(AMDGPU::sub0, Offset);
3802 
3803   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3804 }
3805 
3806 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3807                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3808                                  int Offset) {
3809   MachineBasicBlock *MBB = MI.getParent();
3810   const DebugLoc &DL = MI.getDebugLoc();
3811   MachineBasicBlock::iterator I(&MI);
3812 
3813   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3814 
3815   assert(Idx->getReg() != AMDGPU::NoRegister);
3816 
3817   if (Offset == 0) {
3818     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3819   } else {
3820     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3821         .add(*Idx)
3822         .addImm(Offset);
3823   }
3824 }
3825 
3826 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3827                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3828                                    int Offset) {
3829   MachineBasicBlock *MBB = MI.getParent();
3830   const DebugLoc &DL = MI.getDebugLoc();
3831   MachineBasicBlock::iterator I(&MI);
3832 
3833   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3834 
3835   if (Offset == 0)
3836     return Idx->getReg();
3837 
3838   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3839   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3840       .add(*Idx)
3841       .addImm(Offset);
3842   return Tmp;
3843 }
3844 
3845 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3846                                           MachineBasicBlock &MBB,
3847                                           const GCNSubtarget &ST) {
3848   const SIInstrInfo *TII = ST.getInstrInfo();
3849   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3850   MachineFunction *MF = MBB.getParent();
3851   MachineRegisterInfo &MRI = MF->getRegInfo();
3852 
3853   Register Dst = MI.getOperand(0).getReg();
3854   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3855   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3856   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3857 
3858   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3859   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3860 
3861   unsigned SubReg;
3862   std::tie(SubReg, Offset)
3863     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3864 
3865   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3866 
3867   // Check for a SGPR index.
3868   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3869     MachineBasicBlock::iterator I(&MI);
3870     const DebugLoc &DL = MI.getDebugLoc();
3871 
3872     if (UseGPRIdxMode) {
3873       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3874       // to avoid interfering with other uses, so probably requires a new
3875       // optimization pass.
3876       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3877 
3878       const MCInstrDesc &GPRIDXDesc =
3879           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3880       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3881           .addReg(SrcReg)
3882           .addReg(Idx)
3883           .addImm(SubReg);
3884     } else {
3885       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3886 
3887       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3888         .addReg(SrcReg, 0, SubReg)
3889         .addReg(SrcReg, RegState::Implicit);
3890     }
3891 
3892     MI.eraseFromParent();
3893 
3894     return &MBB;
3895   }
3896 
3897   // Control flow needs to be inserted if indexing with a VGPR.
3898   const DebugLoc &DL = MI.getDebugLoc();
3899   MachineBasicBlock::iterator I(&MI);
3900 
3901   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3902   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3903 
3904   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3905 
3906   Register SGPRIdxReg;
3907   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3908                               UseGPRIdxMode, SGPRIdxReg);
3909 
3910   MachineBasicBlock *LoopBB = InsPt->getParent();
3911 
3912   if (UseGPRIdxMode) {
3913     const MCInstrDesc &GPRIDXDesc =
3914         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3915 
3916     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3917         .addReg(SrcReg)
3918         .addReg(SGPRIdxReg)
3919         .addImm(SubReg);
3920   } else {
3921     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3922       .addReg(SrcReg, 0, SubReg)
3923       .addReg(SrcReg, RegState::Implicit);
3924   }
3925 
3926   MI.eraseFromParent();
3927 
3928   return LoopBB;
3929 }
3930 
3931 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3932                                           MachineBasicBlock &MBB,
3933                                           const GCNSubtarget &ST) {
3934   const SIInstrInfo *TII = ST.getInstrInfo();
3935   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3936   MachineFunction *MF = MBB.getParent();
3937   MachineRegisterInfo &MRI = MF->getRegInfo();
3938 
3939   Register Dst = MI.getOperand(0).getReg();
3940   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3941   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3942   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3943   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3944   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3945   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3946 
3947   // This can be an immediate, but will be folded later.
3948   assert(Val->getReg());
3949 
3950   unsigned SubReg;
3951   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3952                                                          SrcVec->getReg(),
3953                                                          Offset);
3954   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3955 
3956   if (Idx->getReg() == AMDGPU::NoRegister) {
3957     MachineBasicBlock::iterator I(&MI);
3958     const DebugLoc &DL = MI.getDebugLoc();
3959 
3960     assert(Offset == 0);
3961 
3962     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3963         .add(*SrcVec)
3964         .add(*Val)
3965         .addImm(SubReg);
3966 
3967     MI.eraseFromParent();
3968     return &MBB;
3969   }
3970 
3971   // Check for a SGPR index.
3972   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3973     MachineBasicBlock::iterator I(&MI);
3974     const DebugLoc &DL = MI.getDebugLoc();
3975 
3976     if (UseGPRIdxMode) {
3977       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3978 
3979       const MCInstrDesc &GPRIDXDesc =
3980           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3981       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3982           .addReg(SrcVec->getReg())
3983           .add(*Val)
3984           .addReg(Idx)
3985           .addImm(SubReg);
3986     } else {
3987       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3988 
3989       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3990           TRI.getRegSizeInBits(*VecRC), 32, false);
3991       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3992           .addReg(SrcVec->getReg())
3993           .add(*Val)
3994           .addImm(SubReg);
3995     }
3996     MI.eraseFromParent();
3997     return &MBB;
3998   }
3999 
4000   // Control flow needs to be inserted if indexing with a VGPR.
4001   if (Val->isReg())
4002     MRI.clearKillFlags(Val->getReg());
4003 
4004   const DebugLoc &DL = MI.getDebugLoc();
4005 
4006   Register PhiReg = MRI.createVirtualRegister(VecRC);
4007 
4008   Register SGPRIdxReg;
4009   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4010                               UseGPRIdxMode, SGPRIdxReg);
4011   MachineBasicBlock *LoopBB = InsPt->getParent();
4012 
4013   if (UseGPRIdxMode) {
4014     const MCInstrDesc &GPRIDXDesc =
4015         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4016 
4017     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4018         .addReg(PhiReg)
4019         .add(*Val)
4020         .addReg(SGPRIdxReg)
4021         .addImm(AMDGPU::sub0);
4022   } else {
4023     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4024         TRI.getRegSizeInBits(*VecRC), 32, false);
4025     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4026         .addReg(PhiReg)
4027         .add(*Val)
4028         .addImm(AMDGPU::sub0);
4029   }
4030 
4031   MI.eraseFromParent();
4032   return LoopBB;
4033 }
4034 
4035 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4036   MachineInstr &MI, MachineBasicBlock *BB) const {
4037 
4038   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4039   MachineFunction *MF = BB->getParent();
4040   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4041 
4042   switch (MI.getOpcode()) {
4043   case AMDGPU::S_UADDO_PSEUDO:
4044   case AMDGPU::S_USUBO_PSEUDO: {
4045     const DebugLoc &DL = MI.getDebugLoc();
4046     MachineOperand &Dest0 = MI.getOperand(0);
4047     MachineOperand &Dest1 = MI.getOperand(1);
4048     MachineOperand &Src0 = MI.getOperand(2);
4049     MachineOperand &Src1 = MI.getOperand(3);
4050 
4051     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4052                        ? AMDGPU::S_ADD_I32
4053                        : AMDGPU::S_SUB_I32;
4054     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4055 
4056     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4057         .addImm(1)
4058         .addImm(0);
4059 
4060     MI.eraseFromParent();
4061     return BB;
4062   }
4063   case AMDGPU::S_ADD_U64_PSEUDO:
4064   case AMDGPU::S_SUB_U64_PSEUDO: {
4065     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4066     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4067     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4068     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4069     const DebugLoc &DL = MI.getDebugLoc();
4070 
4071     MachineOperand &Dest = MI.getOperand(0);
4072     MachineOperand &Src0 = MI.getOperand(1);
4073     MachineOperand &Src1 = MI.getOperand(2);
4074 
4075     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4076     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4077 
4078     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4079         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4080     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4081         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4082 
4083     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4084         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4085     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4086         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4087 
4088     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4089 
4090     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4091     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4092     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4093     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4094     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4095         .addReg(DestSub0)
4096         .addImm(AMDGPU::sub0)
4097         .addReg(DestSub1)
4098         .addImm(AMDGPU::sub1);
4099     MI.eraseFromParent();
4100     return BB;
4101   }
4102   case AMDGPU::V_ADD_U64_PSEUDO:
4103   case AMDGPU::V_SUB_U64_PSEUDO: {
4104     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4105     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4106     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4107     const DebugLoc &DL = MI.getDebugLoc();
4108 
4109     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4110 
4111     MachineOperand &Dest = MI.getOperand(0);
4112     MachineOperand &Src0 = MI.getOperand(1);
4113     MachineOperand &Src1 = MI.getOperand(2);
4114 
4115     if (IsAdd && ST.hasLshlAddB64()) {
4116       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4117                          Dest.getReg())
4118                      .add(Src0)
4119                      .addImm(0)
4120                      .add(Src1);
4121       TII->legalizeOperands(*Add);
4122       MI.eraseFromParent();
4123       return BB;
4124     }
4125 
4126     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4127 
4128     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4129     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4130 
4131     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4132     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4133 
4134     const TargetRegisterClass *Src0RC = Src0.isReg()
4135                                             ? MRI.getRegClass(Src0.getReg())
4136                                             : &AMDGPU::VReg_64RegClass;
4137     const TargetRegisterClass *Src1RC = Src1.isReg()
4138                                             ? MRI.getRegClass(Src1.getReg())
4139                                             : &AMDGPU::VReg_64RegClass;
4140 
4141     const TargetRegisterClass *Src0SubRC =
4142         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4143     const TargetRegisterClass *Src1SubRC =
4144         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4145 
4146     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4147         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4148     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4149         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4150 
4151     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4152         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4153     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4154         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4155 
4156     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4157     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4158                                .addReg(CarryReg, RegState::Define)
4159                                .add(SrcReg0Sub0)
4160                                .add(SrcReg1Sub0)
4161                                .addImm(0); // clamp bit
4162 
4163     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4164     MachineInstr *HiHalf =
4165         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4166             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4167             .add(SrcReg0Sub1)
4168             .add(SrcReg1Sub1)
4169             .addReg(CarryReg, RegState::Kill)
4170             .addImm(0); // clamp bit
4171 
4172     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4173         .addReg(DestSub0)
4174         .addImm(AMDGPU::sub0)
4175         .addReg(DestSub1)
4176         .addImm(AMDGPU::sub1);
4177     TII->legalizeOperands(*LoHalf);
4178     TII->legalizeOperands(*HiHalf);
4179     MI.eraseFromParent();
4180     return BB;
4181   }
4182   case AMDGPU::S_ADD_CO_PSEUDO:
4183   case AMDGPU::S_SUB_CO_PSEUDO: {
4184     // This pseudo has a chance to be selected
4185     // only from uniform add/subcarry node. All the VGPR operands
4186     // therefore assumed to be splat vectors.
4187     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4188     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4189     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4190     MachineBasicBlock::iterator MII = MI;
4191     const DebugLoc &DL = MI.getDebugLoc();
4192     MachineOperand &Dest = MI.getOperand(0);
4193     MachineOperand &CarryDest = MI.getOperand(1);
4194     MachineOperand &Src0 = MI.getOperand(2);
4195     MachineOperand &Src1 = MI.getOperand(3);
4196     MachineOperand &Src2 = MI.getOperand(4);
4197     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4198                        ? AMDGPU::S_ADDC_U32
4199                        : AMDGPU::S_SUBB_U32;
4200     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4201       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4202       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4203           .addReg(Src0.getReg());
4204       Src0.setReg(RegOp0);
4205     }
4206     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4207       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4208       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4209           .addReg(Src1.getReg());
4210       Src1.setReg(RegOp1);
4211     }
4212     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4213     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4214       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4215           .addReg(Src2.getReg());
4216       Src2.setReg(RegOp2);
4217     }
4218 
4219     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4220     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4221     assert(WaveSize == 64 || WaveSize == 32);
4222 
4223     if (WaveSize == 64) {
4224       if (ST.hasScalarCompareEq64()) {
4225         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4226             .addReg(Src2.getReg())
4227             .addImm(0);
4228       } else {
4229         const TargetRegisterClass *SubRC =
4230             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4231         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4232             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4233         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4234             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4235         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4236 
4237         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4238             .add(Src2Sub0)
4239             .add(Src2Sub1);
4240 
4241         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4242             .addReg(Src2_32, RegState::Kill)
4243             .addImm(0);
4244       }
4245     } else {
4246       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4247           .addReg(Src2.getReg())
4248           .addImm(0);
4249     }
4250 
4251     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4252 
4253     unsigned SelOpc =
4254         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4255 
4256     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4257         .addImm(-1)
4258         .addImm(0);
4259 
4260     MI.eraseFromParent();
4261     return BB;
4262   }
4263   case AMDGPU::SI_INIT_M0: {
4264     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4265             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4266         .add(MI.getOperand(0));
4267     MI.eraseFromParent();
4268     return BB;
4269   }
4270   case AMDGPU::GET_GROUPSTATICSIZE: {
4271     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4272            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4273     DebugLoc DL = MI.getDebugLoc();
4274     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4275         .add(MI.getOperand(0))
4276         .addImm(MFI->getLDSSize());
4277     MI.eraseFromParent();
4278     return BB;
4279   }
4280   case AMDGPU::SI_INDIRECT_SRC_V1:
4281   case AMDGPU::SI_INDIRECT_SRC_V2:
4282   case AMDGPU::SI_INDIRECT_SRC_V4:
4283   case AMDGPU::SI_INDIRECT_SRC_V8:
4284   case AMDGPU::SI_INDIRECT_SRC_V16:
4285   case AMDGPU::SI_INDIRECT_SRC_V32:
4286     return emitIndirectSrc(MI, *BB, *getSubtarget());
4287   case AMDGPU::SI_INDIRECT_DST_V1:
4288   case AMDGPU::SI_INDIRECT_DST_V2:
4289   case AMDGPU::SI_INDIRECT_DST_V4:
4290   case AMDGPU::SI_INDIRECT_DST_V8:
4291   case AMDGPU::SI_INDIRECT_DST_V16:
4292   case AMDGPU::SI_INDIRECT_DST_V32:
4293     return emitIndirectDst(MI, *BB, *getSubtarget());
4294   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4295   case AMDGPU::SI_KILL_I1_PSEUDO:
4296     return splitKillBlock(MI, BB);
4297   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4298     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4299     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4300     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4301 
4302     Register Dst = MI.getOperand(0).getReg();
4303     Register Src0 = MI.getOperand(1).getReg();
4304     Register Src1 = MI.getOperand(2).getReg();
4305     const DebugLoc &DL = MI.getDebugLoc();
4306     Register SrcCond = MI.getOperand(3).getReg();
4307 
4308     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4309     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4310     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4311     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4312 
4313     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4314       .addReg(SrcCond);
4315     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4316       .addImm(0)
4317       .addReg(Src0, 0, AMDGPU::sub0)
4318       .addImm(0)
4319       .addReg(Src1, 0, AMDGPU::sub0)
4320       .addReg(SrcCondCopy);
4321     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4322       .addImm(0)
4323       .addReg(Src0, 0, AMDGPU::sub1)
4324       .addImm(0)
4325       .addReg(Src1, 0, AMDGPU::sub1)
4326       .addReg(SrcCondCopy);
4327 
4328     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4329       .addReg(DstLo)
4330       .addImm(AMDGPU::sub0)
4331       .addReg(DstHi)
4332       .addImm(AMDGPU::sub1);
4333     MI.eraseFromParent();
4334     return BB;
4335   }
4336   case AMDGPU::SI_BR_UNDEF: {
4337     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4338     const DebugLoc &DL = MI.getDebugLoc();
4339     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4340                            .add(MI.getOperand(0));
4341     Br->getOperand(1).setIsUndef(true); // read undef SCC
4342     MI.eraseFromParent();
4343     return BB;
4344   }
4345   case AMDGPU::ADJCALLSTACKUP:
4346   case AMDGPU::ADJCALLSTACKDOWN: {
4347     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4348     MachineInstrBuilder MIB(*MF, &MI);
4349     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4350        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4351     return BB;
4352   }
4353   case AMDGPU::SI_CALL_ISEL: {
4354     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4355     const DebugLoc &DL = MI.getDebugLoc();
4356 
4357     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4358 
4359     MachineInstrBuilder MIB;
4360     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4361 
4362     for (const MachineOperand &MO : MI.operands())
4363       MIB.add(MO);
4364 
4365     MIB.cloneMemRefs(MI);
4366     MI.eraseFromParent();
4367     return BB;
4368   }
4369   case AMDGPU::V_ADD_CO_U32_e32:
4370   case AMDGPU::V_SUB_CO_U32_e32:
4371   case AMDGPU::V_SUBREV_CO_U32_e32: {
4372     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4373     const DebugLoc &DL = MI.getDebugLoc();
4374     unsigned Opc = MI.getOpcode();
4375 
4376     bool NeedClampOperand = false;
4377     if (TII->pseudoToMCOpcode(Opc) == -1) {
4378       Opc = AMDGPU::getVOPe64(Opc);
4379       NeedClampOperand = true;
4380     }
4381 
4382     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4383     if (TII->isVOP3(*I)) {
4384       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4385       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4386       I.addReg(TRI->getVCC(), RegState::Define);
4387     }
4388     I.add(MI.getOperand(1))
4389      .add(MI.getOperand(2));
4390     if (NeedClampOperand)
4391       I.addImm(0); // clamp bit for e64 encoding
4392 
4393     TII->legalizeOperands(*I);
4394 
4395     MI.eraseFromParent();
4396     return BB;
4397   }
4398   case AMDGPU::V_ADDC_U32_e32:
4399   case AMDGPU::V_SUBB_U32_e32:
4400   case AMDGPU::V_SUBBREV_U32_e32:
4401     // These instructions have an implicit use of vcc which counts towards the
4402     // constant bus limit.
4403     TII->legalizeOperands(MI);
4404     return BB;
4405   case AMDGPU::DS_GWS_INIT:
4406   case AMDGPU::DS_GWS_SEMA_BR:
4407   case AMDGPU::DS_GWS_BARRIER:
4408     if (Subtarget->needsAlignedVGPRs()) {
4409       // Add implicit aligned super-reg to force alignment on the data operand.
4410       const DebugLoc &DL = MI.getDebugLoc();
4411       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4412       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4413       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4414       Register DataReg = Op->getReg();
4415       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4416       Register Undef = MRI.createVirtualRegister(
4417           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4418       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4419       Register NewVR =
4420           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4421                                            : &AMDGPU::VReg_64_Align2RegClass);
4422       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4423           .addReg(DataReg, 0, Op->getSubReg())
4424           .addImm(AMDGPU::sub0)
4425           .addReg(Undef)
4426           .addImm(AMDGPU::sub1);
4427       Op->setReg(NewVR);
4428       Op->setSubReg(AMDGPU::sub0);
4429       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4430     }
4431     LLVM_FALLTHROUGH;
4432   case AMDGPU::DS_GWS_SEMA_V:
4433   case AMDGPU::DS_GWS_SEMA_P:
4434   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4435     // A s_waitcnt 0 is required to be the instruction immediately following.
4436     if (getSubtarget()->hasGWSAutoReplay()) {
4437       bundleInstWithWaitcnt(MI);
4438       return BB;
4439     }
4440 
4441     return emitGWSMemViolTestLoop(MI, BB);
4442   case AMDGPU::S_SETREG_B32: {
4443     // Try to optimize cases that only set the denormal mode or rounding mode.
4444     //
4445     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4446     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4447     // instead.
4448     //
4449     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4450     // allow you to have a no side effect instruction in the output of a
4451     // sideeffecting pattern.
4452     unsigned ID, Offset, Width;
4453     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4454     if (ID != AMDGPU::Hwreg::ID_MODE)
4455       return BB;
4456 
4457     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4458     const unsigned SetMask = WidthMask << Offset;
4459 
4460     if (getSubtarget()->hasDenormModeInst()) {
4461       unsigned SetDenormOp = 0;
4462       unsigned SetRoundOp = 0;
4463 
4464       // The dedicated instructions can only set the whole denorm or round mode
4465       // at once, not a subset of bits in either.
4466       if (SetMask ==
4467           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4468         // If this fully sets both the round and denorm mode, emit the two
4469         // dedicated instructions for these.
4470         SetRoundOp = AMDGPU::S_ROUND_MODE;
4471         SetDenormOp = AMDGPU::S_DENORM_MODE;
4472       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4473         SetRoundOp = AMDGPU::S_ROUND_MODE;
4474       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4475         SetDenormOp = AMDGPU::S_DENORM_MODE;
4476       }
4477 
4478       if (SetRoundOp || SetDenormOp) {
4479         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4480         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4481         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4482           unsigned ImmVal = Def->getOperand(1).getImm();
4483           if (SetRoundOp) {
4484             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4485                 .addImm(ImmVal & 0xf);
4486 
4487             // If we also have the denorm mode, get just the denorm mode bits.
4488             ImmVal >>= 4;
4489           }
4490 
4491           if (SetDenormOp) {
4492             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4493                 .addImm(ImmVal & 0xf);
4494           }
4495 
4496           MI.eraseFromParent();
4497           return BB;
4498         }
4499       }
4500     }
4501 
4502     // If only FP bits are touched, used the no side effects pseudo.
4503     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4504                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4505       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4506 
4507     return BB;
4508   }
4509   default:
4510     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4511   }
4512 }
4513 
4514 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4515   return isTypeLegal(VT.getScalarType());
4516 }
4517 
4518 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4519   // This currently forces unfolding various combinations of fsub into fma with
4520   // free fneg'd operands. As long as we have fast FMA (controlled by
4521   // isFMAFasterThanFMulAndFAdd), we should perform these.
4522 
4523   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4524   // most of these combines appear to be cycle neutral but save on instruction
4525   // count / code size.
4526   return true;
4527 }
4528 
4529 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4530 
4531 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4532                                          EVT VT) const {
4533   if (!VT.isVector()) {
4534     return MVT::i1;
4535   }
4536   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4537 }
4538 
4539 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4540   // TODO: Should i16 be used always if legal? For now it would force VALU
4541   // shifts.
4542   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4543 }
4544 
4545 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4546   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4547              ? Ty.changeElementSize(16)
4548              : Ty.changeElementSize(32);
4549 }
4550 
4551 // Answering this is somewhat tricky and depends on the specific device which
4552 // have different rates for fma or all f64 operations.
4553 //
4554 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4555 // regardless of which device (although the number of cycles differs between
4556 // devices), so it is always profitable for f64.
4557 //
4558 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4559 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4560 // which we can always do even without fused FP ops since it returns the same
4561 // result as the separate operations and since it is always full
4562 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4563 // however does not support denormals, so we do report fma as faster if we have
4564 // a fast fma device and require denormals.
4565 //
4566 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4567                                                   EVT VT) const {
4568   VT = VT.getScalarType();
4569 
4570   switch (VT.getSimpleVT().SimpleTy) {
4571   case MVT::f32: {
4572     // If mad is not available this depends only on if f32 fma is full rate.
4573     if (!Subtarget->hasMadMacF32Insts())
4574       return Subtarget->hasFastFMAF32();
4575 
4576     // Otherwise f32 mad is always full rate and returns the same result as
4577     // the separate operations so should be preferred over fma.
4578     // However does not support denormals.
4579     if (hasFP32Denormals(MF))
4580       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4581 
4582     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4583     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4584   }
4585   case MVT::f64:
4586     return true;
4587   case MVT::f16:
4588     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4589   default:
4590     break;
4591   }
4592 
4593   return false;
4594 }
4595 
4596 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4597                                                   LLT Ty) const {
4598   switch (Ty.getScalarSizeInBits()) {
4599   case 16:
4600     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4601   case 32:
4602     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4603   case 64:
4604     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4605   default:
4606     break;
4607   }
4608 
4609   return false;
4610 }
4611 
4612 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4613   if (!Ty.isScalar())
4614     return false;
4615 
4616   if (Ty.getScalarSizeInBits() == 16)
4617     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4618   if (Ty.getScalarSizeInBits() == 32)
4619     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4620 
4621   return false;
4622 }
4623 
4624 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4625                                    const SDNode *N) const {
4626   // TODO: Check future ftz flag
4627   // v_mad_f32/v_mac_f32 do not support denormals.
4628   EVT VT = N->getValueType(0);
4629   if (VT == MVT::f32)
4630     return Subtarget->hasMadMacF32Insts() &&
4631            !hasFP32Denormals(DAG.getMachineFunction());
4632   if (VT == MVT::f16) {
4633     return Subtarget->hasMadF16() &&
4634            !hasFP64FP16Denormals(DAG.getMachineFunction());
4635   }
4636 
4637   return false;
4638 }
4639 
4640 //===----------------------------------------------------------------------===//
4641 // Custom DAG Lowering Operations
4642 //===----------------------------------------------------------------------===//
4643 
4644 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4645 // wider vector type is legal.
4646 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4647                                              SelectionDAG &DAG) const {
4648   unsigned Opc = Op.getOpcode();
4649   EVT VT = Op.getValueType();
4650   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4651 
4652   SDValue Lo, Hi;
4653   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4654 
4655   SDLoc SL(Op);
4656   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4657                              Op->getFlags());
4658   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4659                              Op->getFlags());
4660 
4661   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4662 }
4663 
4664 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4665 // wider vector type is legal.
4666 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4667                                               SelectionDAG &DAG) const {
4668   unsigned Opc = Op.getOpcode();
4669   EVT VT = Op.getValueType();
4670   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4671          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4672          VT == MVT::v16f32 || VT == MVT::v32f32);
4673 
4674   SDValue Lo0, Hi0;
4675   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4676   SDValue Lo1, Hi1;
4677   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4678 
4679   SDLoc SL(Op);
4680 
4681   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4682                              Op->getFlags());
4683   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4684                              Op->getFlags());
4685 
4686   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4687 }
4688 
4689 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4690                                               SelectionDAG &DAG) const {
4691   unsigned Opc = Op.getOpcode();
4692   EVT VT = Op.getValueType();
4693   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4694          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4695          VT == MVT::v16f32 || VT == MVT::v32f32);
4696 
4697   SDValue Lo0, Hi0;
4698   SDValue Op0 = Op.getOperand(0);
4699   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4700                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4701                          : std::make_pair(Op0, Op0);
4702   SDValue Lo1, Hi1;
4703   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4704   SDValue Lo2, Hi2;
4705   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4706 
4707   SDLoc SL(Op);
4708   auto ResVT = DAG.GetSplitDestVTs(VT);
4709 
4710   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4711                              Op->getFlags());
4712   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4713                              Op->getFlags());
4714 
4715   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4716 }
4717 
4718 
4719 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4720   switch (Op.getOpcode()) {
4721   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4722   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4723   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4724   case ISD::LOAD: {
4725     SDValue Result = LowerLOAD(Op, DAG);
4726     assert((!Result.getNode() ||
4727             Result.getNode()->getNumValues() == 2) &&
4728            "Load should return a value and a chain");
4729     return Result;
4730   }
4731 
4732   case ISD::FSIN:
4733   case ISD::FCOS:
4734     return LowerTrig(Op, DAG);
4735   case ISD::SELECT: return LowerSELECT(Op, DAG);
4736   case ISD::FDIV: return LowerFDIV(Op, DAG);
4737   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4738   case ISD::STORE: return LowerSTORE(Op, DAG);
4739   case ISD::GlobalAddress: {
4740     MachineFunction &MF = DAG.getMachineFunction();
4741     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4742     return LowerGlobalAddress(MFI, Op, DAG);
4743   }
4744   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4745   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4746   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4747   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4748   case ISD::INSERT_SUBVECTOR:
4749     return lowerINSERT_SUBVECTOR(Op, DAG);
4750   case ISD::INSERT_VECTOR_ELT:
4751     return lowerINSERT_VECTOR_ELT(Op, DAG);
4752   case ISD::EXTRACT_VECTOR_ELT:
4753     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4754   case ISD::VECTOR_SHUFFLE:
4755     return lowerVECTOR_SHUFFLE(Op, DAG);
4756   case ISD::BUILD_VECTOR:
4757     return lowerBUILD_VECTOR(Op, DAG);
4758   case ISD::FP_ROUND:
4759     return lowerFP_ROUND(Op, DAG);
4760   case ISD::FPTRUNC_ROUND: {
4761     unsigned Opc;
4762     SDLoc DL(Op);
4763 
4764     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4765       return SDValue();
4766 
4767     // Get the rounding mode from the last operand
4768     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4769     if (RoundMode == (int)RoundingMode::TowardPositive)
4770       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4771     else if (RoundMode == (int)RoundingMode::TowardNegative)
4772       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4773     else
4774       return SDValue();
4775 
4776     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4777   }
4778   case ISD::TRAP:
4779     return lowerTRAP(Op, DAG);
4780   case ISD::DEBUGTRAP:
4781     return lowerDEBUGTRAP(Op, DAG);
4782   case ISD::FABS:
4783   case ISD::FNEG:
4784   case ISD::FCANONICALIZE:
4785   case ISD::BSWAP:
4786     return splitUnaryVectorOp(Op, DAG);
4787   case ISD::FMINNUM:
4788   case ISD::FMAXNUM:
4789     return lowerFMINNUM_FMAXNUM(Op, DAG);
4790   case ISD::FMA:
4791     return splitTernaryVectorOp(Op, DAG);
4792   case ISD::FP_TO_SINT:
4793   case ISD::FP_TO_UINT:
4794     return LowerFP_TO_INT(Op, DAG);
4795   case ISD::SHL:
4796   case ISD::SRA:
4797   case ISD::SRL:
4798   case ISD::ADD:
4799   case ISD::SUB:
4800   case ISD::MUL:
4801   case ISD::SMIN:
4802   case ISD::SMAX:
4803   case ISD::UMIN:
4804   case ISD::UMAX:
4805   case ISD::FADD:
4806   case ISD::FMUL:
4807   case ISD::FMINNUM_IEEE:
4808   case ISD::FMAXNUM_IEEE:
4809   case ISD::UADDSAT:
4810   case ISD::USUBSAT:
4811   case ISD::SADDSAT:
4812   case ISD::SSUBSAT:
4813     return splitBinaryVectorOp(Op, DAG);
4814   case ISD::SMULO:
4815   case ISD::UMULO:
4816     return lowerXMULO(Op, DAG);
4817   case ISD::SMUL_LOHI:
4818   case ISD::UMUL_LOHI:
4819     return lowerXMUL_LOHI(Op, DAG);
4820   case ISD::DYNAMIC_STACKALLOC:
4821     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4822   }
4823   return SDValue();
4824 }
4825 
4826 // Used for D16: Casts the result of an instruction into the right vector,
4827 // packs values if loads return unpacked values.
4828 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4829                                        const SDLoc &DL,
4830                                        SelectionDAG &DAG, bool Unpacked) {
4831   if (!LoadVT.isVector())
4832     return Result;
4833 
4834   // Cast back to the original packed type or to a larger type that is a
4835   // multiple of 32 bit for D16. Widening the return type is a required for
4836   // legalization.
4837   EVT FittingLoadVT = LoadVT;
4838   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4839     FittingLoadVT =
4840         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4841                          LoadVT.getVectorNumElements() + 1);
4842   }
4843 
4844   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4845     // Truncate to v2i16/v4i16.
4846     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4847 
4848     // Workaround legalizer not scalarizing truncate after vector op
4849     // legalization but not creating intermediate vector trunc.
4850     SmallVector<SDValue, 4> Elts;
4851     DAG.ExtractVectorElements(Result, Elts);
4852     for (SDValue &Elt : Elts)
4853       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4854 
4855     // Pad illegal v1i16/v3fi6 to v4i16
4856     if ((LoadVT.getVectorNumElements() % 2) == 1)
4857       Elts.push_back(DAG.getUNDEF(MVT::i16));
4858 
4859     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4860 
4861     // Bitcast to original type (v2f16/v4f16).
4862     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4863   }
4864 
4865   // Cast back to the original packed type.
4866   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4867 }
4868 
4869 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4870                                               MemSDNode *M,
4871                                               SelectionDAG &DAG,
4872                                               ArrayRef<SDValue> Ops,
4873                                               bool IsIntrinsic) const {
4874   SDLoc DL(M);
4875 
4876   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4877   EVT LoadVT = M->getValueType(0);
4878 
4879   EVT EquivLoadVT = LoadVT;
4880   if (LoadVT.isVector()) {
4881     if (Unpacked) {
4882       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4883                                      LoadVT.getVectorNumElements());
4884     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4885       // Widen v3f16 to legal type
4886       EquivLoadVT =
4887           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4888                            LoadVT.getVectorNumElements() + 1);
4889     }
4890   }
4891 
4892   // Change from v4f16/v2f16 to EquivLoadVT.
4893   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4894 
4895   SDValue Load
4896     = DAG.getMemIntrinsicNode(
4897       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4898       VTList, Ops, M->getMemoryVT(),
4899       M->getMemOperand());
4900 
4901   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4902 
4903   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4904 }
4905 
4906 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4907                                              SelectionDAG &DAG,
4908                                              ArrayRef<SDValue> Ops) const {
4909   SDLoc DL(M);
4910   EVT LoadVT = M->getValueType(0);
4911   EVT EltType = LoadVT.getScalarType();
4912   EVT IntVT = LoadVT.changeTypeToInteger();
4913 
4914   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4915 
4916   unsigned Opc =
4917       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4918 
4919   if (IsD16) {
4920     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4921   }
4922 
4923   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4924   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4925     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4926 
4927   if (isTypeLegal(LoadVT)) {
4928     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4929                                M->getMemOperand(), DAG);
4930   }
4931 
4932   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4933   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4934   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4935                                         M->getMemOperand(), DAG);
4936   return DAG.getMergeValues(
4937       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4938       DL);
4939 }
4940 
4941 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4942                                   SDNode *N, SelectionDAG &DAG) {
4943   EVT VT = N->getValueType(0);
4944   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4945   unsigned CondCode = CD->getZExtValue();
4946   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4947     return DAG.getUNDEF(VT);
4948 
4949   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4950 
4951   SDValue LHS = N->getOperand(1);
4952   SDValue RHS = N->getOperand(2);
4953 
4954   SDLoc DL(N);
4955 
4956   EVT CmpVT = LHS.getValueType();
4957   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4958     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4959       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4960     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4961     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4962   }
4963 
4964   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4965 
4966   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4967   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4968 
4969   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4970                               DAG.getCondCode(CCOpcode));
4971   if (VT.bitsEq(CCVT))
4972     return SetCC;
4973   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4974 }
4975 
4976 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4977                                   SDNode *N, SelectionDAG &DAG) {
4978   EVT VT = N->getValueType(0);
4979   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4980 
4981   unsigned CondCode = CD->getZExtValue();
4982   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4983     return DAG.getUNDEF(VT);
4984 
4985   SDValue Src0 = N->getOperand(1);
4986   SDValue Src1 = N->getOperand(2);
4987   EVT CmpVT = Src0.getValueType();
4988   SDLoc SL(N);
4989 
4990   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4991     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4992     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4993   }
4994 
4995   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4996   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4997   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4998   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4999   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
5000                               Src1, DAG.getCondCode(CCOpcode));
5001   if (VT.bitsEq(CCVT))
5002     return SetCC;
5003   return DAG.getZExtOrTrunc(SetCC, SL, VT);
5004 }
5005 
5006 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
5007                                     SelectionDAG &DAG) {
5008   EVT VT = N->getValueType(0);
5009   SDValue Src = N->getOperand(1);
5010   SDLoc SL(N);
5011 
5012   if (Src.getOpcode() == ISD::SETCC) {
5013     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
5014     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
5015                        Src.getOperand(1), Src.getOperand(2));
5016   }
5017   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5018     // (ballot 0) -> 0
5019     if (Arg->isZero())
5020       return DAG.getConstant(0, SL, VT);
5021 
5022     // (ballot 1) -> EXEC/EXEC_LO
5023     if (Arg->isOne()) {
5024       Register Exec;
5025       if (VT.getScalarSizeInBits() == 32)
5026         Exec = AMDGPU::EXEC_LO;
5027       else if (VT.getScalarSizeInBits() == 64)
5028         Exec = AMDGPU::EXEC;
5029       else
5030         return SDValue();
5031 
5032       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5033     }
5034   }
5035 
5036   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5037   // ISD::SETNE)
5038   return DAG.getNode(
5039       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5040       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5041 }
5042 
5043 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5044                                           SmallVectorImpl<SDValue> &Results,
5045                                           SelectionDAG &DAG) const {
5046   switch (N->getOpcode()) {
5047   case ISD::INSERT_VECTOR_ELT: {
5048     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5049       Results.push_back(Res);
5050     return;
5051   }
5052   case ISD::EXTRACT_VECTOR_ELT: {
5053     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5054       Results.push_back(Res);
5055     return;
5056   }
5057   case ISD::INTRINSIC_WO_CHAIN: {
5058     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5059     switch (IID) {
5060     case Intrinsic::amdgcn_cvt_pkrtz: {
5061       SDValue Src0 = N->getOperand(1);
5062       SDValue Src1 = N->getOperand(2);
5063       SDLoc SL(N);
5064       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5065                                 Src0, Src1);
5066       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5067       return;
5068     }
5069     case Intrinsic::amdgcn_cvt_pknorm_i16:
5070     case Intrinsic::amdgcn_cvt_pknorm_u16:
5071     case Intrinsic::amdgcn_cvt_pk_i16:
5072     case Intrinsic::amdgcn_cvt_pk_u16: {
5073       SDValue Src0 = N->getOperand(1);
5074       SDValue Src1 = N->getOperand(2);
5075       SDLoc SL(N);
5076       unsigned Opcode;
5077 
5078       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5079         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5080       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5081         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5082       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5083         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5084       else
5085         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5086 
5087       EVT VT = N->getValueType(0);
5088       if (isTypeLegal(VT))
5089         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5090       else {
5091         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5092         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5093       }
5094       return;
5095     }
5096     }
5097     break;
5098   }
5099   case ISD::INTRINSIC_W_CHAIN: {
5100     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5101       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5102         // FIXME: Hacky
5103         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5104           Results.push_back(Res.getOperand(I));
5105         }
5106       } else {
5107         Results.push_back(Res);
5108         Results.push_back(Res.getValue(1));
5109       }
5110       return;
5111     }
5112 
5113     break;
5114   }
5115   case ISD::SELECT: {
5116     SDLoc SL(N);
5117     EVT VT = N->getValueType(0);
5118     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5119     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5120     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5121 
5122     EVT SelectVT = NewVT;
5123     if (NewVT.bitsLT(MVT::i32)) {
5124       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5125       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5126       SelectVT = MVT::i32;
5127     }
5128 
5129     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5130                                     N->getOperand(0), LHS, RHS);
5131 
5132     if (NewVT != SelectVT)
5133       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5134     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5135     return;
5136   }
5137   case ISD::FNEG: {
5138     if (N->getValueType(0) != MVT::v2f16)
5139       break;
5140 
5141     SDLoc SL(N);
5142     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5143 
5144     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5145                              BC,
5146                              DAG.getConstant(0x80008000, SL, MVT::i32));
5147     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5148     return;
5149   }
5150   case ISD::FABS: {
5151     if (N->getValueType(0) != MVT::v2f16)
5152       break;
5153 
5154     SDLoc SL(N);
5155     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5156 
5157     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5158                              BC,
5159                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5160     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5161     return;
5162   }
5163   default:
5164     break;
5165   }
5166 }
5167 
5168 /// Helper function for LowerBRCOND
5169 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5170 
5171   SDNode *Parent = Value.getNode();
5172   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5173        I != E; ++I) {
5174 
5175     if (I.getUse().get() != Value)
5176       continue;
5177 
5178     if (I->getOpcode() == Opcode)
5179       return *I;
5180   }
5181   return nullptr;
5182 }
5183 
5184 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5185   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5186     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5187     case Intrinsic::amdgcn_if:
5188       return AMDGPUISD::IF;
5189     case Intrinsic::amdgcn_else:
5190       return AMDGPUISD::ELSE;
5191     case Intrinsic::amdgcn_loop:
5192       return AMDGPUISD::LOOP;
5193     case Intrinsic::amdgcn_end_cf:
5194       llvm_unreachable("should not occur");
5195     default:
5196       return 0;
5197     }
5198   }
5199 
5200   // break, if_break, else_break are all only used as inputs to loop, not
5201   // directly as branch conditions.
5202   return 0;
5203 }
5204 
5205 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5206   const Triple &TT = getTargetMachine().getTargetTriple();
5207   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5208           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5209          AMDGPU::shouldEmitConstantsToTextSection(TT);
5210 }
5211 
5212 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5213   // FIXME: Either avoid relying on address space here or change the default
5214   // address space for functions to avoid the explicit check.
5215   return (GV->getValueType()->isFunctionTy() ||
5216           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5217          !shouldEmitFixup(GV) &&
5218          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5219 }
5220 
5221 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5222   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5223 }
5224 
5225 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5226   if (!GV->hasExternalLinkage())
5227     return true;
5228 
5229   const auto OS = getTargetMachine().getTargetTriple().getOS();
5230   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5231 }
5232 
5233 /// This transforms the control flow intrinsics to get the branch destination as
5234 /// last parameter, also switches branch target with BR if the need arise
5235 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5236                                       SelectionDAG &DAG) const {
5237   SDLoc DL(BRCOND);
5238 
5239   SDNode *Intr = BRCOND.getOperand(1).getNode();
5240   SDValue Target = BRCOND.getOperand(2);
5241   SDNode *BR = nullptr;
5242   SDNode *SetCC = nullptr;
5243 
5244   if (Intr->getOpcode() == ISD::SETCC) {
5245     // As long as we negate the condition everything is fine
5246     SetCC = Intr;
5247     Intr = SetCC->getOperand(0).getNode();
5248 
5249   } else {
5250     // Get the target from BR if we don't negate the condition
5251     BR = findUser(BRCOND, ISD::BR);
5252     assert(BR && "brcond missing unconditional branch user");
5253     Target = BR->getOperand(1);
5254   }
5255 
5256   unsigned CFNode = isCFIntrinsic(Intr);
5257   if (CFNode == 0) {
5258     // This is a uniform branch so we don't need to legalize.
5259     return BRCOND;
5260   }
5261 
5262   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5263                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5264 
5265   assert(!SetCC ||
5266         (SetCC->getConstantOperandVal(1) == 1 &&
5267          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5268                                                              ISD::SETNE));
5269 
5270   // operands of the new intrinsic call
5271   SmallVector<SDValue, 4> Ops;
5272   if (HaveChain)
5273     Ops.push_back(BRCOND.getOperand(0));
5274 
5275   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5276   Ops.push_back(Target);
5277 
5278   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5279 
5280   // build the new intrinsic call
5281   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5282 
5283   if (!HaveChain) {
5284     SDValue Ops[] =  {
5285       SDValue(Result, 0),
5286       BRCOND.getOperand(0)
5287     };
5288 
5289     Result = DAG.getMergeValues(Ops, DL).getNode();
5290   }
5291 
5292   if (BR) {
5293     // Give the branch instruction our target
5294     SDValue Ops[] = {
5295       BR->getOperand(0),
5296       BRCOND.getOperand(2)
5297     };
5298     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5299     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5300   }
5301 
5302   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5303 
5304   // Copy the intrinsic results to registers
5305   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5306     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5307     if (!CopyToReg)
5308       continue;
5309 
5310     Chain = DAG.getCopyToReg(
5311       Chain, DL,
5312       CopyToReg->getOperand(1),
5313       SDValue(Result, i - 1),
5314       SDValue());
5315 
5316     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5317   }
5318 
5319   // Remove the old intrinsic from the chain
5320   DAG.ReplaceAllUsesOfValueWith(
5321     SDValue(Intr, Intr->getNumValues() - 1),
5322     Intr->getOperand(0));
5323 
5324   return Chain;
5325 }
5326 
5327 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5328                                           SelectionDAG &DAG) const {
5329   MVT VT = Op.getSimpleValueType();
5330   SDLoc DL(Op);
5331   // Checking the depth
5332   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5333     return DAG.getConstant(0, DL, VT);
5334 
5335   MachineFunction &MF = DAG.getMachineFunction();
5336   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5337   // Check for kernel and shader functions
5338   if (Info->isEntryFunction())
5339     return DAG.getConstant(0, DL, VT);
5340 
5341   MachineFrameInfo &MFI = MF.getFrameInfo();
5342   // There is a call to @llvm.returnaddress in this function
5343   MFI.setReturnAddressIsTaken(true);
5344 
5345   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5346   // Get the return address reg and mark it as an implicit live-in
5347   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5348 
5349   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5350 }
5351 
5352 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5353                                             SDValue Op,
5354                                             const SDLoc &DL,
5355                                             EVT VT) const {
5356   return Op.getValueType().bitsLE(VT) ?
5357       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5358     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5359                 DAG.getTargetConstant(0, DL, MVT::i32));
5360 }
5361 
5362 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5363   assert(Op.getValueType() == MVT::f16 &&
5364          "Do not know how to custom lower FP_ROUND for non-f16 type");
5365 
5366   SDValue Src = Op.getOperand(0);
5367   EVT SrcVT = Src.getValueType();
5368   if (SrcVT != MVT::f64)
5369     return Op;
5370 
5371   SDLoc DL(Op);
5372 
5373   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5374   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5375   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5376 }
5377 
5378 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5379                                                SelectionDAG &DAG) const {
5380   EVT VT = Op.getValueType();
5381   const MachineFunction &MF = DAG.getMachineFunction();
5382   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5383   bool IsIEEEMode = Info->getMode().IEEE;
5384 
5385   // FIXME: Assert during selection that this is only selected for
5386   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5387   // mode functions, but this happens to be OK since it's only done in cases
5388   // where there is known no sNaN.
5389   if (IsIEEEMode)
5390     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5391 
5392   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5393     return splitBinaryVectorOp(Op, DAG);
5394   return Op;
5395 }
5396 
5397 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5398   EVT VT = Op.getValueType();
5399   SDLoc SL(Op);
5400   SDValue LHS = Op.getOperand(0);
5401   SDValue RHS = Op.getOperand(1);
5402   bool isSigned = Op.getOpcode() == ISD::SMULO;
5403 
5404   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5405     const APInt &C = RHSC->getAPIntValue();
5406     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5407     if (C.isPowerOf2()) {
5408       // smulo(x, signed_min) is same as umulo(x, signed_min).
5409       bool UseArithShift = isSigned && !C.isMinSignedValue();
5410       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5411       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5412       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5413           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5414                       SL, VT, Result, ShiftAmt),
5415           LHS, ISD::SETNE);
5416       return DAG.getMergeValues({ Result, Overflow }, SL);
5417     }
5418   }
5419 
5420   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5421   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5422                             SL, VT, LHS, RHS);
5423 
5424   SDValue Sign = isSigned
5425     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5426                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5427     : DAG.getConstant(0, SL, VT);
5428   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5429 
5430   return DAG.getMergeValues({ Result, Overflow }, SL);
5431 }
5432 
5433 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5434   if (Op->isDivergent()) {
5435     // Select to V_MAD_[IU]64_[IU]32.
5436     return Op;
5437   }
5438   if (Subtarget->hasSMulHi()) {
5439     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5440     return SDValue();
5441   }
5442   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5443   // calculate the high part, so we might as well do the whole thing with
5444   // V_MAD_[IU]64_[IU]32.
5445   return Op;
5446 }
5447 
5448 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5449   if (!Subtarget->isTrapHandlerEnabled() ||
5450       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5451     return lowerTrapEndpgm(Op, DAG);
5452 
5453   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5454     switch (*HsaAbiVer) {
5455     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5456     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5457       return lowerTrapHsaQueuePtr(Op, DAG);
5458     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5459     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5460       return Subtarget->supportsGetDoorbellID() ?
5461           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5462     }
5463   }
5464 
5465   llvm_unreachable("Unknown trap handler");
5466 }
5467 
5468 SDValue SITargetLowering::lowerTrapEndpgm(
5469     SDValue Op, SelectionDAG &DAG) const {
5470   SDLoc SL(Op);
5471   SDValue Chain = Op.getOperand(0);
5472   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5473 }
5474 
5475 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5476     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5477   MachineFunction &MF = DAG.getMachineFunction();
5478   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5479   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5480   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5481   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5482                      MachineMemOperand::MODereferenceable |
5483                          MachineMemOperand::MOInvariant);
5484 }
5485 
5486 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5487     SDValue Op, SelectionDAG &DAG) const {
5488   SDLoc SL(Op);
5489   SDValue Chain = Op.getOperand(0);
5490 
5491   SDValue QueuePtr;
5492   // For code object version 5, QueuePtr is passed through implicit kernarg.
5493   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5494     QueuePtr =
5495         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5496   } else {
5497     MachineFunction &MF = DAG.getMachineFunction();
5498     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5499     Register UserSGPR = Info->getQueuePtrUserSGPR();
5500 
5501     if (UserSGPR == AMDGPU::NoRegister) {
5502       // We probably are in a function incorrectly marked with
5503       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5504       // trap, so just use a null pointer.
5505       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5506     } else {
5507       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5508                                       MVT::i64);
5509     }
5510   }
5511 
5512   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5513   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5514                                    QueuePtr, SDValue());
5515 
5516   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5517   SDValue Ops[] = {
5518     ToReg,
5519     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5520     SGPR01,
5521     ToReg.getValue(1)
5522   };
5523   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5524 }
5525 
5526 SDValue SITargetLowering::lowerTrapHsa(
5527     SDValue Op, SelectionDAG &DAG) const {
5528   SDLoc SL(Op);
5529   SDValue Chain = Op.getOperand(0);
5530 
5531   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5532   SDValue Ops[] = {
5533     Chain,
5534     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5535   };
5536   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5537 }
5538 
5539 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5540   SDLoc SL(Op);
5541   SDValue Chain = Op.getOperand(0);
5542   MachineFunction &MF = DAG.getMachineFunction();
5543 
5544   if (!Subtarget->isTrapHandlerEnabled() ||
5545       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5546     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5547                                      "debugtrap handler not supported",
5548                                      Op.getDebugLoc(),
5549                                      DS_Warning);
5550     LLVMContext &Ctx = MF.getFunction().getContext();
5551     Ctx.diagnose(NoTrap);
5552     return Chain;
5553   }
5554 
5555   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5556   SDValue Ops[] = {
5557     Chain,
5558     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5559   };
5560   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5561 }
5562 
5563 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5564                                              SelectionDAG &DAG) const {
5565   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5566   if (Subtarget->hasApertureRegs()) {
5567     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5568         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5569         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5570     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5571         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5572         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5573     unsigned Encoding =
5574         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5575         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5576         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5577 
5578     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5579     SDValue ApertureReg = SDValue(
5580         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5581     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5582     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5583   }
5584 
5585   // For code object version 5, private_base and shared_base are passed through
5586   // implicit kernargs.
5587   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5588     ImplicitParameter Param =
5589         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5590     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5591   }
5592 
5593   MachineFunction &MF = DAG.getMachineFunction();
5594   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5595   Register UserSGPR = Info->getQueuePtrUserSGPR();
5596   if (UserSGPR == AMDGPU::NoRegister) {
5597     // We probably are in a function incorrectly marked with
5598     // amdgpu-no-queue-ptr. This is undefined.
5599     return DAG.getUNDEF(MVT::i32);
5600   }
5601 
5602   SDValue QueuePtr = CreateLiveInRegister(
5603     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5604 
5605   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5606   // private_segment_aperture_base_hi.
5607   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5608 
5609   SDValue Ptr =
5610       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5611 
5612   // TODO: Use custom target PseudoSourceValue.
5613   // TODO: We should use the value from the IR intrinsic call, but it might not
5614   // be available and how do we get it?
5615   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5616   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5617                      commonAlignment(Align(64), StructOffset),
5618                      MachineMemOperand::MODereferenceable |
5619                          MachineMemOperand::MOInvariant);
5620 }
5621 
5622 /// Return true if the value is a known valid address, such that a null check is
5623 /// not necessary.
5624 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5625                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5626   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5627       isa<BasicBlockSDNode>(Val))
5628     return true;
5629 
5630   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5631     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5632 
5633   // TODO: Search through arithmetic, handle arguments and loads
5634   // marked nonnull.
5635   return false;
5636 }
5637 
5638 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5639                                              SelectionDAG &DAG) const {
5640   SDLoc SL(Op);
5641   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5642 
5643   SDValue Src = ASC->getOperand(0);
5644   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5645   unsigned SrcAS = ASC->getSrcAddressSpace();
5646 
5647   const AMDGPUTargetMachine &TM =
5648     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5649 
5650   // flat -> local/private
5651   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5652     unsigned DestAS = ASC->getDestAddressSpace();
5653 
5654     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5655         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5656       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5657 
5658       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5659         return Ptr;
5660 
5661       unsigned NullVal = TM.getNullPointerValue(DestAS);
5662       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5663       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5664 
5665       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5666                          SegmentNullPtr);
5667     }
5668   }
5669 
5670   // local/private -> flat
5671   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5672     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5673         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5674 
5675       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5676       SDValue CvtPtr =
5677           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5678       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5679 
5680       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5681         return CvtPtr;
5682 
5683       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5684       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5685 
5686       SDValue NonNull
5687         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5688 
5689       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5690                          FlatNullPtr);
5691     }
5692   }
5693 
5694   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5695       Op.getValueType() == MVT::i64) {
5696     const SIMachineFunctionInfo *Info =
5697         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5698     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5699     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5700     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5701   }
5702 
5703   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5704       Src.getValueType() == MVT::i64)
5705     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5706 
5707   // global <-> flat are no-ops and never emitted.
5708 
5709   const MachineFunction &MF = DAG.getMachineFunction();
5710   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5711     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5712   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5713 
5714   return DAG.getUNDEF(ASC->getValueType(0));
5715 }
5716 
5717 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5718 // the small vector and inserting them into the big vector. That is better than
5719 // the default expansion of doing it via a stack slot. Even though the use of
5720 // the stack slot would be optimized away afterwards, the stack slot itself
5721 // remains.
5722 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5723                                                 SelectionDAG &DAG) const {
5724   SDValue Vec = Op.getOperand(0);
5725   SDValue Ins = Op.getOperand(1);
5726   SDValue Idx = Op.getOperand(2);
5727   EVT VecVT = Vec.getValueType();
5728   EVT InsVT = Ins.getValueType();
5729   EVT EltVT = VecVT.getVectorElementType();
5730   unsigned InsNumElts = InsVT.getVectorNumElements();
5731   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5732   SDLoc SL(Op);
5733 
5734   for (unsigned I = 0; I != InsNumElts; ++I) {
5735     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5736                               DAG.getConstant(I, SL, MVT::i32));
5737     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5738                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5739   }
5740   return Vec;
5741 }
5742 
5743 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5744                                                  SelectionDAG &DAG) const {
5745   SDValue Vec = Op.getOperand(0);
5746   SDValue InsVal = Op.getOperand(1);
5747   SDValue Idx = Op.getOperand(2);
5748   EVT VecVT = Vec.getValueType();
5749   EVT EltVT = VecVT.getVectorElementType();
5750   unsigned VecSize = VecVT.getSizeInBits();
5751   unsigned EltSize = EltVT.getSizeInBits();
5752 
5753 
5754   assert(VecSize <= 64);
5755 
5756   unsigned NumElts = VecVT.getVectorNumElements();
5757   SDLoc SL(Op);
5758   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5759 
5760   if (NumElts == 4 && EltSize == 16 && KIdx) {
5761     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5762 
5763     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5764                                  DAG.getConstant(0, SL, MVT::i32));
5765     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5766                                  DAG.getConstant(1, SL, MVT::i32));
5767 
5768     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5769     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5770 
5771     unsigned Idx = KIdx->getZExtValue();
5772     bool InsertLo = Idx < 2;
5773     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5774       InsertLo ? LoVec : HiVec,
5775       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5776       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5777 
5778     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5779 
5780     SDValue Concat = InsertLo ?
5781       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5782       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5783 
5784     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5785   }
5786 
5787   if (isa<ConstantSDNode>(Idx))
5788     return SDValue();
5789 
5790   MVT IntVT = MVT::getIntegerVT(VecSize);
5791 
5792   // Avoid stack access for dynamic indexing.
5793   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5794 
5795   // Create a congruent vector with the target value in each element so that
5796   // the required element can be masked and ORed into the target vector.
5797   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5798                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5799 
5800   assert(isPowerOf2_32(EltSize));
5801   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5802 
5803   // Convert vector index to bit-index.
5804   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5805 
5806   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5807   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5808                             DAG.getConstant(0xffff, SL, IntVT),
5809                             ScaledIdx);
5810 
5811   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5812   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5813                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5814 
5815   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5816   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5817 }
5818 
5819 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5820                                                   SelectionDAG &DAG) const {
5821   SDLoc SL(Op);
5822 
5823   EVT ResultVT = Op.getValueType();
5824   SDValue Vec = Op.getOperand(0);
5825   SDValue Idx = Op.getOperand(1);
5826   EVT VecVT = Vec.getValueType();
5827   unsigned VecSize = VecVT.getSizeInBits();
5828   EVT EltVT = VecVT.getVectorElementType();
5829 
5830   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5831 
5832   // Make sure we do any optimizations that will make it easier to fold
5833   // source modifiers before obscuring it with bit operations.
5834 
5835   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5836   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5837     return Combined;
5838 
5839   if (VecSize == 128) {
5840     SDValue Lo, Hi;
5841     EVT LoVT, HiVT;
5842     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5843     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5844     Lo =
5845         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5846                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5847     Hi =
5848         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5849                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5850     EVT IdxVT = Idx.getValueType();
5851     unsigned NElem = VecVT.getVectorNumElements();
5852     assert(isPowerOf2_32(NElem));
5853     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5854     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5855     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5856     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5857   }
5858 
5859   assert(VecSize <= 64);
5860 
5861   unsigned EltSize = EltVT.getSizeInBits();
5862   assert(isPowerOf2_32(EltSize));
5863 
5864   MVT IntVT = MVT::getIntegerVT(VecSize);
5865   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5866 
5867   // Convert vector index to bit-index (* EltSize)
5868   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5869 
5870   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5871   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5872 
5873   if (ResultVT == MVT::f16) {
5874     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5875     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5876   }
5877 
5878   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5879 }
5880 
5881 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5882   assert(Elt % 2 == 0);
5883   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5884 }
5885 
5886 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5887                                               SelectionDAG &DAG) const {
5888   SDLoc SL(Op);
5889   EVT ResultVT = Op.getValueType();
5890   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5891 
5892   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5893   EVT EltVT = PackVT.getVectorElementType();
5894   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5895 
5896   // vector_shuffle <0,1,6,7> lhs, rhs
5897   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5898   //
5899   // vector_shuffle <6,7,2,3> lhs, rhs
5900   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5901   //
5902   // vector_shuffle <6,7,0,1> lhs, rhs
5903   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5904 
5905   // Avoid scalarizing when both halves are reading from consecutive elements.
5906   SmallVector<SDValue, 4> Pieces;
5907   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5908     if (elementPairIsContiguous(SVN->getMask(), I)) {
5909       const int Idx = SVN->getMaskElt(I);
5910       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5911       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5912       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5913                                     PackVT, SVN->getOperand(VecIdx),
5914                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5915       Pieces.push_back(SubVec);
5916     } else {
5917       const int Idx0 = SVN->getMaskElt(I);
5918       const int Idx1 = SVN->getMaskElt(I + 1);
5919       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5920       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5921       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5922       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5923 
5924       SDValue Vec0 = SVN->getOperand(VecIdx0);
5925       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5926                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5927 
5928       SDValue Vec1 = SVN->getOperand(VecIdx1);
5929       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5930                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5931       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5932     }
5933   }
5934 
5935   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5936 }
5937 
5938 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5939                                             SelectionDAG &DAG) const {
5940   SDLoc SL(Op);
5941   EVT VT = Op.getValueType();
5942 
5943   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5944       VT == MVT::v8i16 || VT == MVT::v8f16) {
5945     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5946                                   VT.getVectorNumElements() / 2);
5947     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5948 
5949     // Turn into pair of packed build_vectors.
5950     // TODO: Special case for constants that can be materialized with s_mov_b64.
5951     SmallVector<SDValue, 4> LoOps, HiOps;
5952     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5953       LoOps.push_back(Op.getOperand(I));
5954       HiOps.push_back(Op.getOperand(I + E));
5955     }
5956     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5957     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5958 
5959     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5960     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5961 
5962     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5963                                        { CastLo, CastHi });
5964     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5965   }
5966 
5967   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5968   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5969 
5970   SDValue Lo = Op.getOperand(0);
5971   SDValue Hi = Op.getOperand(1);
5972 
5973   // Avoid adding defined bits with the zero_extend.
5974   if (Hi.isUndef()) {
5975     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5976     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5977     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5978   }
5979 
5980   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5981   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5982 
5983   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5984                               DAG.getConstant(16, SL, MVT::i32));
5985   if (Lo.isUndef())
5986     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5987 
5988   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5989   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5990 
5991   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5992   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5993 }
5994 
5995 bool
5996 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5997   // We can fold offsets for anything that doesn't require a GOT relocation.
5998   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5999           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
6000           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
6001          !shouldEmitGOTReloc(GA->getGlobal());
6002 }
6003 
6004 static SDValue
6005 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
6006                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
6007                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
6008   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
6009   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
6010   // lowered to the following code sequence:
6011   //
6012   // For constant address space:
6013   //   s_getpc_b64 s[0:1]
6014   //   s_add_u32 s0, s0, $symbol
6015   //   s_addc_u32 s1, s1, 0
6016   //
6017   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6018   //   a fixup or relocation is emitted to replace $symbol with a literal
6019   //   constant, which is a pc-relative offset from the encoding of the $symbol
6020   //   operand to the global variable.
6021   //
6022   // For global address space:
6023   //   s_getpc_b64 s[0:1]
6024   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
6025   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
6026   //
6027   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6028   //   fixups or relocations are emitted to replace $symbol@*@lo and
6029   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6030   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6031   //   operand to the global variable.
6032   //
6033   // What we want here is an offset from the value returned by s_getpc
6034   // (which is the address of the s_add_u32 instruction) to the global
6035   // variable, but since the encoding of $symbol starts 4 bytes after the start
6036   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6037   // small. This requires us to add 4 to the global variable offset in order to
6038   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6039   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6040   // instruction.
6041   SDValue PtrLo =
6042       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6043   SDValue PtrHi;
6044   if (GAFlags == SIInstrInfo::MO_NONE) {
6045     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6046   } else {
6047     PtrHi =
6048         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6049   }
6050   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6051 }
6052 
6053 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6054                                              SDValue Op,
6055                                              SelectionDAG &DAG) const {
6056   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6057   SDLoc DL(GSD);
6058   EVT PtrVT = Op.getValueType();
6059 
6060   const GlobalValue *GV = GSD->getGlobal();
6061   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6062        shouldUseLDSConstAddress(GV)) ||
6063       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6064       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6065     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6066         GV->hasExternalLinkage()) {
6067       Type *Ty = GV->getValueType();
6068       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6069       // zero-sized type in other languages to declare the dynamic shared
6070       // memory which size is not known at the compile time. They will be
6071       // allocated by the runtime and placed directly after the static
6072       // allocated ones. They all share the same offset.
6073       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6074         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6075         // Adjust alignment for that dynamic shared memory array.
6076         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6077         return SDValue(
6078             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6079       }
6080     }
6081     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6082   }
6083 
6084   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6085     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6086                                             SIInstrInfo::MO_ABS32_LO);
6087     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6088   }
6089 
6090   if (shouldEmitFixup(GV))
6091     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6092   else if (shouldEmitPCReloc(GV))
6093     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6094                                    SIInstrInfo::MO_REL32);
6095 
6096   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6097                                             SIInstrInfo::MO_GOTPCREL32);
6098 
6099   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6100   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6101   const DataLayout &DataLayout = DAG.getDataLayout();
6102   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6103   MachinePointerInfo PtrInfo
6104     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6105 
6106   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6107                      MachineMemOperand::MODereferenceable |
6108                          MachineMemOperand::MOInvariant);
6109 }
6110 
6111 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6112                                    const SDLoc &DL, SDValue V) const {
6113   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6114   // the destination register.
6115   //
6116   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6117   // so we will end up with redundant moves to m0.
6118   //
6119   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6120 
6121   // A Null SDValue creates a glue result.
6122   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6123                                   V, Chain);
6124   return SDValue(M0, 0);
6125 }
6126 
6127 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6128                                                  SDValue Op,
6129                                                  MVT VT,
6130                                                  unsigned Offset) const {
6131   SDLoc SL(Op);
6132   SDValue Param = lowerKernargMemParameter(
6133       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6134   // The local size values will have the hi 16-bits as zero.
6135   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6136                      DAG.getValueType(VT));
6137 }
6138 
6139 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6140                                         EVT VT) {
6141   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6142                                       "non-hsa intrinsic with hsa target",
6143                                       DL.getDebugLoc());
6144   DAG.getContext()->diagnose(BadIntrin);
6145   return DAG.getUNDEF(VT);
6146 }
6147 
6148 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6149                                          EVT VT) {
6150   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6151                                       "intrinsic not supported on subtarget",
6152                                       DL.getDebugLoc());
6153   DAG.getContext()->diagnose(BadIntrin);
6154   return DAG.getUNDEF(VT);
6155 }
6156 
6157 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6158                                     ArrayRef<SDValue> Elts) {
6159   assert(!Elts.empty());
6160   MVT Type;
6161   unsigned NumElts = Elts.size();
6162 
6163   if (NumElts <= 8) {
6164     Type = MVT::getVectorVT(MVT::f32, NumElts);
6165   } else {
6166     assert(Elts.size() <= 16);
6167     Type = MVT::v16f32;
6168     NumElts = 16;
6169   }
6170 
6171   SmallVector<SDValue, 16> VecElts(NumElts);
6172   for (unsigned i = 0; i < Elts.size(); ++i) {
6173     SDValue Elt = Elts[i];
6174     if (Elt.getValueType() != MVT::f32)
6175       Elt = DAG.getBitcast(MVT::f32, Elt);
6176     VecElts[i] = Elt;
6177   }
6178   for (unsigned i = Elts.size(); i < NumElts; ++i)
6179     VecElts[i] = DAG.getUNDEF(MVT::f32);
6180 
6181   if (NumElts == 1)
6182     return VecElts[0];
6183   return DAG.getBuildVector(Type, DL, VecElts);
6184 }
6185 
6186 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6187                               SDValue Src, int ExtraElts) {
6188   EVT SrcVT = Src.getValueType();
6189 
6190   SmallVector<SDValue, 8> Elts;
6191 
6192   if (SrcVT.isVector())
6193     DAG.ExtractVectorElements(Src, Elts);
6194   else
6195     Elts.push_back(Src);
6196 
6197   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6198   while (ExtraElts--)
6199     Elts.push_back(Undef);
6200 
6201   return DAG.getBuildVector(CastVT, DL, Elts);
6202 }
6203 
6204 // Re-construct the required return value for a image load intrinsic.
6205 // This is more complicated due to the optional use TexFailCtrl which means the required
6206 // return type is an aggregate
6207 static SDValue constructRetValue(SelectionDAG &DAG,
6208                                  MachineSDNode *Result,
6209                                  ArrayRef<EVT> ResultTypes,
6210                                  bool IsTexFail, bool Unpacked, bool IsD16,
6211                                  int DMaskPop, int NumVDataDwords,
6212                                  const SDLoc &DL) {
6213   // Determine the required return type. This is the same regardless of IsTexFail flag
6214   EVT ReqRetVT = ResultTypes[0];
6215   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6216   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6217     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6218 
6219   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6220     DMaskPop : (DMaskPop + 1) / 2;
6221 
6222   MVT DataDwordVT = NumDataDwords == 1 ?
6223     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6224 
6225   MVT MaskPopVT = MaskPopDwords == 1 ?
6226     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6227 
6228   SDValue Data(Result, 0);
6229   SDValue TexFail;
6230 
6231   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6232     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6233     if (MaskPopVT.isVector()) {
6234       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6235                          SDValue(Result, 0), ZeroIdx);
6236     } else {
6237       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6238                          SDValue(Result, 0), ZeroIdx);
6239     }
6240   }
6241 
6242   if (DataDwordVT.isVector())
6243     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6244                           NumDataDwords - MaskPopDwords);
6245 
6246   if (IsD16)
6247     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6248 
6249   EVT LegalReqRetVT = ReqRetVT;
6250   if (!ReqRetVT.isVector()) {
6251     if (!Data.getValueType().isInteger())
6252       Data = DAG.getNode(ISD::BITCAST, DL,
6253                          Data.getValueType().changeTypeToInteger(), Data);
6254     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6255   } else {
6256     // We need to widen the return vector to a legal type
6257     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6258         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6259       LegalReqRetVT =
6260           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6261                            ReqRetVT.getVectorNumElements() + 1);
6262     }
6263   }
6264   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6265 
6266   if (IsTexFail) {
6267     TexFail =
6268         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6269                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6270 
6271     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6272   }
6273 
6274   if (Result->getNumValues() == 1)
6275     return Data;
6276 
6277   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6278 }
6279 
6280 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6281                          SDValue *LWE, bool &IsTexFail) {
6282   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6283 
6284   uint64_t Value = TexFailCtrlConst->getZExtValue();
6285   if (Value) {
6286     IsTexFail = true;
6287   }
6288 
6289   SDLoc DL(TexFailCtrlConst);
6290   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6291   Value &= ~(uint64_t)0x1;
6292   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6293   Value &= ~(uint64_t)0x2;
6294 
6295   return Value == 0;
6296 }
6297 
6298 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6299                                       MVT PackVectorVT,
6300                                       SmallVectorImpl<SDValue> &PackedAddrs,
6301                                       unsigned DimIdx, unsigned EndIdx,
6302                                       unsigned NumGradients) {
6303   SDLoc DL(Op);
6304   for (unsigned I = DimIdx; I < EndIdx; I++) {
6305     SDValue Addr = Op.getOperand(I);
6306 
6307     // Gradients are packed with undef for each coordinate.
6308     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6309     // 1D: undef,dx/dh; undef,dx/dv
6310     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6311     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6312     if (((I + 1) >= EndIdx) ||
6313         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6314                                          I == DimIdx + NumGradients - 1))) {
6315       if (Addr.getValueType() != MVT::i16)
6316         Addr = DAG.getBitcast(MVT::i16, Addr);
6317       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6318     } else {
6319       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6320       I++;
6321     }
6322     Addr = DAG.getBitcast(MVT::f32, Addr);
6323     PackedAddrs.push_back(Addr);
6324   }
6325 }
6326 
6327 SDValue SITargetLowering::lowerImage(SDValue Op,
6328                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6329                                      SelectionDAG &DAG, bool WithChain) const {
6330   SDLoc DL(Op);
6331   MachineFunction &MF = DAG.getMachineFunction();
6332   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6333   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6334       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6335   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6336   unsigned IntrOpcode = Intr->BaseOpcode;
6337   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6338 
6339   SmallVector<EVT, 3> ResultTypes(Op->values());
6340   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6341   bool IsD16 = false;
6342   bool IsG16 = false;
6343   bool IsA16 = false;
6344   SDValue VData;
6345   int NumVDataDwords;
6346   bool AdjustRetType = false;
6347 
6348   // Offset of intrinsic arguments
6349   const unsigned ArgOffset = WithChain ? 2 : 1;
6350 
6351   unsigned DMask;
6352   unsigned DMaskLanes = 0;
6353 
6354   if (BaseOpcode->Atomic) {
6355     VData = Op.getOperand(2);
6356 
6357     bool Is64Bit = VData.getValueType() == MVT::i64;
6358     if (BaseOpcode->AtomicX2) {
6359       SDValue VData2 = Op.getOperand(3);
6360       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6361                                  {VData, VData2});
6362       if (Is64Bit)
6363         VData = DAG.getBitcast(MVT::v4i32, VData);
6364 
6365       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6366       DMask = Is64Bit ? 0xf : 0x3;
6367       NumVDataDwords = Is64Bit ? 4 : 2;
6368     } else {
6369       DMask = Is64Bit ? 0x3 : 0x1;
6370       NumVDataDwords = Is64Bit ? 2 : 1;
6371     }
6372   } else {
6373     auto *DMaskConst =
6374         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6375     DMask = DMaskConst->getZExtValue();
6376     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6377 
6378     if (BaseOpcode->Store) {
6379       VData = Op.getOperand(2);
6380 
6381       MVT StoreVT = VData.getSimpleValueType();
6382       if (StoreVT.getScalarType() == MVT::f16) {
6383         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6384           return Op; // D16 is unsupported for this instruction
6385 
6386         IsD16 = true;
6387         VData = handleD16VData(VData, DAG, true);
6388       }
6389 
6390       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6391     } else {
6392       // Work out the num dwords based on the dmask popcount and underlying type
6393       // and whether packing is supported.
6394       MVT LoadVT = ResultTypes[0].getSimpleVT();
6395       if (LoadVT.getScalarType() == MVT::f16) {
6396         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6397           return Op; // D16 is unsupported for this instruction
6398 
6399         IsD16 = true;
6400       }
6401 
6402       // Confirm that the return type is large enough for the dmask specified
6403       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6404           (!LoadVT.isVector() && DMaskLanes > 1))
6405           return Op;
6406 
6407       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6408       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6409       // instructions.
6410       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6411           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6412         NumVDataDwords = (DMaskLanes + 1) / 2;
6413       else
6414         NumVDataDwords = DMaskLanes;
6415 
6416       AdjustRetType = true;
6417     }
6418   }
6419 
6420   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6421   SmallVector<SDValue, 4> VAddrs;
6422 
6423   // Check for 16 bit addresses or derivatives and pack if true.
6424   MVT VAddrVT =
6425       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6426   MVT VAddrScalarVT = VAddrVT.getScalarType();
6427   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6428   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6429 
6430   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6431   VAddrScalarVT = VAddrVT.getScalarType();
6432   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6433   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6434 
6435   // Push back extra arguments.
6436   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6437     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6438       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6439       // Special handling of bias when A16 is on. Bias is of type half but
6440       // occupies full 32-bit.
6441       SDValue Bias = DAG.getBuildVector(
6442           MVT::v2f16, DL,
6443           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6444       VAddrs.push_back(Bias);
6445     } else {
6446       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6447              "Bias needs to be converted to 16 bit in A16 mode");
6448       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6449     }
6450   }
6451 
6452   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6453     // 16 bit gradients are supported, but are tied to the A16 control
6454     // so both gradients and addresses must be 16 bit
6455     LLVM_DEBUG(
6456         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6457                   "require 16 bit args for both gradients and addresses");
6458     return Op;
6459   }
6460 
6461   if (IsA16) {
6462     if (!ST->hasA16()) {
6463       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6464                            "support 16 bit addresses\n");
6465       return Op;
6466     }
6467   }
6468 
6469   // We've dealt with incorrect input so we know that if IsA16, IsG16
6470   // are set then we have to compress/pack operands (either address,
6471   // gradient or both)
6472   // In the case where a16 and gradients are tied (no G16 support) then we
6473   // have already verified that both IsA16 and IsG16 are true
6474   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6475     // Activate g16
6476     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6477         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6478     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6479   }
6480 
6481   // Add gradients (packed or unpacked)
6482   if (IsG16) {
6483     // Pack the gradients
6484     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6485     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6486                               ArgOffset + Intr->GradientStart,
6487                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6488   } else {
6489     for (unsigned I = ArgOffset + Intr->GradientStart;
6490          I < ArgOffset + Intr->CoordStart; I++)
6491       VAddrs.push_back(Op.getOperand(I));
6492   }
6493 
6494   // Add addresses (packed or unpacked)
6495   if (IsA16) {
6496     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6497                               ArgOffset + Intr->CoordStart, VAddrEnd,
6498                               0 /* No gradients */);
6499   } else {
6500     // Add uncompressed address
6501     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6502       VAddrs.push_back(Op.getOperand(I));
6503   }
6504 
6505   // If the register allocator cannot place the address registers contiguously
6506   // without introducing moves, then using the non-sequential address encoding
6507   // is always preferable, since it saves VALU instructions and is usually a
6508   // wash in terms of code size or even better.
6509   //
6510   // However, we currently have no way of hinting to the register allocator that
6511   // MIMG addresses should be placed contiguously when it is possible to do so,
6512   // so force non-NSA for the common 2-address case as a heuristic.
6513   //
6514   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6515   // allocation when possible.
6516   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6517                 VAddrs.size() >= 3 &&
6518                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6519   SDValue VAddr;
6520   if (!UseNSA)
6521     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6522 
6523   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6524   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6525   SDValue Unorm;
6526   if (!BaseOpcode->Sampler) {
6527     Unorm = True;
6528   } else {
6529     auto UnormConst =
6530         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6531 
6532     Unorm = UnormConst->getZExtValue() ? True : False;
6533   }
6534 
6535   SDValue TFE;
6536   SDValue LWE;
6537   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6538   bool IsTexFail = false;
6539   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6540     return Op;
6541 
6542   if (IsTexFail) {
6543     if (!DMaskLanes) {
6544       // Expecting to get an error flag since TFC is on - and dmask is 0
6545       // Force dmask to be at least 1 otherwise the instruction will fail
6546       DMask = 0x1;
6547       DMaskLanes = 1;
6548       NumVDataDwords = 1;
6549     }
6550     NumVDataDwords += 1;
6551     AdjustRetType = true;
6552   }
6553 
6554   // Has something earlier tagged that the return type needs adjusting
6555   // This happens if the instruction is a load or has set TexFailCtrl flags
6556   if (AdjustRetType) {
6557     // NumVDataDwords reflects the true number of dwords required in the return type
6558     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6559       // This is a no-op load. This can be eliminated
6560       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6561       if (isa<MemSDNode>(Op))
6562         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6563       return Undef;
6564     }
6565 
6566     EVT NewVT = NumVDataDwords > 1 ?
6567                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6568                 : MVT::i32;
6569 
6570     ResultTypes[0] = NewVT;
6571     if (ResultTypes.size() == 3) {
6572       // Original result was aggregate type used for TexFailCtrl results
6573       // The actual instruction returns as a vector type which has now been
6574       // created. Remove the aggregate result.
6575       ResultTypes.erase(&ResultTypes[1]);
6576     }
6577   }
6578 
6579   unsigned CPol = cast<ConstantSDNode>(
6580       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6581   if (BaseOpcode->Atomic)
6582     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6583   if (CPol & ~AMDGPU::CPol::ALL)
6584     return Op;
6585 
6586   SmallVector<SDValue, 26> Ops;
6587   if (BaseOpcode->Store || BaseOpcode->Atomic)
6588     Ops.push_back(VData); // vdata
6589   if (UseNSA)
6590     append_range(Ops, VAddrs);
6591   else
6592     Ops.push_back(VAddr);
6593   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6594   if (BaseOpcode->Sampler)
6595     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6596   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6597   if (IsGFX10Plus)
6598     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6599   Ops.push_back(Unorm);
6600   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6601   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6602                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6603   if (IsGFX10Plus)
6604     Ops.push_back(IsA16 ? True : False);
6605   if (!Subtarget->hasGFX90AInsts()) {
6606     Ops.push_back(TFE); //tfe
6607   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6608     report_fatal_error("TFE is not supported on this GPU");
6609   }
6610   Ops.push_back(LWE); // lwe
6611   if (!IsGFX10Plus)
6612     Ops.push_back(DimInfo->DA ? True : False);
6613   if (BaseOpcode->HasD16)
6614     Ops.push_back(IsD16 ? True : False);
6615   if (isa<MemSDNode>(Op))
6616     Ops.push_back(Op.getOperand(0)); // chain
6617 
6618   int NumVAddrDwords =
6619       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6620   int Opcode = -1;
6621 
6622   if (IsGFX10Plus) {
6623     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6624                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6625                                           : AMDGPU::MIMGEncGfx10Default,
6626                                    NumVDataDwords, NumVAddrDwords);
6627   } else {
6628     if (Subtarget->hasGFX90AInsts()) {
6629       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6630                                      NumVDataDwords, NumVAddrDwords);
6631       if (Opcode == -1)
6632         report_fatal_error(
6633             "requested image instruction is not supported on this GPU");
6634     }
6635     if (Opcode == -1 &&
6636         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6637       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6638                                      NumVDataDwords, NumVAddrDwords);
6639     if (Opcode == -1)
6640       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6641                                      NumVDataDwords, NumVAddrDwords);
6642   }
6643   assert(Opcode != -1);
6644 
6645   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6646   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6647     MachineMemOperand *MemRef = MemOp->getMemOperand();
6648     DAG.setNodeMemRefs(NewNode, {MemRef});
6649   }
6650 
6651   if (BaseOpcode->AtomicX2) {
6652     SmallVector<SDValue, 1> Elt;
6653     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6654     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6655   }
6656   if (BaseOpcode->Store)
6657     return SDValue(NewNode, 0);
6658   return constructRetValue(DAG, NewNode,
6659                            OrigResultTypes, IsTexFail,
6660                            Subtarget->hasUnpackedD16VMem(), IsD16,
6661                            DMaskLanes, NumVDataDwords, DL);
6662 }
6663 
6664 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6665                                        SDValue Offset, SDValue CachePolicy,
6666                                        SelectionDAG &DAG) const {
6667   MachineFunction &MF = DAG.getMachineFunction();
6668 
6669   const DataLayout &DataLayout = DAG.getDataLayout();
6670   Align Alignment =
6671       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6672 
6673   MachineMemOperand *MMO = MF.getMachineMemOperand(
6674       MachinePointerInfo(),
6675       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6676           MachineMemOperand::MOInvariant,
6677       VT.getStoreSize(), Alignment);
6678 
6679   if (!Offset->isDivergent()) {
6680     SDValue Ops[] = {
6681         Rsrc,
6682         Offset, // Offset
6683         CachePolicy
6684     };
6685 
6686     // Widen vec3 load to vec4.
6687     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6688       EVT WidenedVT =
6689           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6690       auto WidenedOp = DAG.getMemIntrinsicNode(
6691           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6692           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6693       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6694                                    DAG.getVectorIdxConstant(0, DL));
6695       return Subvector;
6696     }
6697 
6698     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6699                                    DAG.getVTList(VT), Ops, VT, MMO);
6700   }
6701 
6702   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6703   // assume that the buffer is unswizzled.
6704   SmallVector<SDValue, 4> Loads;
6705   unsigned NumLoads = 1;
6706   MVT LoadVT = VT.getSimpleVT();
6707   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6708   assert((LoadVT.getScalarType() == MVT::i32 ||
6709           LoadVT.getScalarType() == MVT::f32));
6710 
6711   if (NumElts == 8 || NumElts == 16) {
6712     NumLoads = NumElts / 4;
6713     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6714   }
6715 
6716   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6717   SDValue Ops[] = {
6718       DAG.getEntryNode(),                               // Chain
6719       Rsrc,                                             // rsrc
6720       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6721       {},                                               // voffset
6722       {},                                               // soffset
6723       {},                                               // offset
6724       CachePolicy,                                      // cachepolicy
6725       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6726   };
6727 
6728   // Use the alignment to ensure that the required offsets will fit into the
6729   // immediate offsets.
6730   setBufferOffsets(Offset, DAG, &Ops[3],
6731                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6732 
6733   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6734   for (unsigned i = 0; i < NumLoads; ++i) {
6735     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6736     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6737                                         LoadVT, MMO, DAG));
6738   }
6739 
6740   if (NumElts == 8 || NumElts == 16)
6741     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6742 
6743   return Loads[0];
6744 }
6745 
6746 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6747                                                   SelectionDAG &DAG) const {
6748   MachineFunction &MF = DAG.getMachineFunction();
6749   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6750 
6751   EVT VT = Op.getValueType();
6752   SDLoc DL(Op);
6753   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6754 
6755   // TODO: Should this propagate fast-math-flags?
6756 
6757   switch (IntrinsicID) {
6758   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6759     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6760       return emitNonHSAIntrinsicError(DAG, DL, VT);
6761     return getPreloadedValue(DAG, *MFI, VT,
6762                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6763   }
6764   case Intrinsic::amdgcn_dispatch_ptr:
6765   case Intrinsic::amdgcn_queue_ptr: {
6766     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6767       DiagnosticInfoUnsupported BadIntrin(
6768           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6769           DL.getDebugLoc());
6770       DAG.getContext()->diagnose(BadIntrin);
6771       return DAG.getUNDEF(VT);
6772     }
6773 
6774     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6775       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6776     return getPreloadedValue(DAG, *MFI, VT, RegID);
6777   }
6778   case Intrinsic::amdgcn_implicitarg_ptr: {
6779     if (MFI->isEntryFunction())
6780       return getImplicitArgPtr(DAG, DL);
6781     return getPreloadedValue(DAG, *MFI, VT,
6782                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6783   }
6784   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6785     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6786       // This only makes sense to call in a kernel, so just lower to null.
6787       return DAG.getConstant(0, DL, VT);
6788     }
6789 
6790     return getPreloadedValue(DAG, *MFI, VT,
6791                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6792   }
6793   case Intrinsic::amdgcn_dispatch_id: {
6794     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6795   }
6796   case Intrinsic::amdgcn_rcp:
6797     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6798   case Intrinsic::amdgcn_rsq:
6799     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6800   case Intrinsic::amdgcn_rsq_legacy:
6801     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6802       return emitRemovedIntrinsicError(DAG, DL, VT);
6803     return SDValue();
6804   case Intrinsic::amdgcn_rcp_legacy:
6805     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6806       return emitRemovedIntrinsicError(DAG, DL, VT);
6807     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6808   case Intrinsic::amdgcn_rsq_clamp: {
6809     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6810       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6811 
6812     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6813     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6814     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6815 
6816     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6817     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6818                               DAG.getConstantFP(Max, DL, VT));
6819     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6820                        DAG.getConstantFP(Min, DL, VT));
6821   }
6822   case Intrinsic::r600_read_ngroups_x:
6823     if (Subtarget->isAmdHsaOS())
6824       return emitNonHSAIntrinsicError(DAG, DL, VT);
6825 
6826     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6827                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6828                                     false);
6829   case Intrinsic::r600_read_ngroups_y:
6830     if (Subtarget->isAmdHsaOS())
6831       return emitNonHSAIntrinsicError(DAG, DL, VT);
6832 
6833     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6834                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6835                                     false);
6836   case Intrinsic::r600_read_ngroups_z:
6837     if (Subtarget->isAmdHsaOS())
6838       return emitNonHSAIntrinsicError(DAG, DL, VT);
6839 
6840     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6841                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6842                                     false);
6843   case Intrinsic::r600_read_global_size_x:
6844     if (Subtarget->isAmdHsaOS())
6845       return emitNonHSAIntrinsicError(DAG, DL, VT);
6846 
6847     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6848                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6849                                     Align(4), false);
6850   case Intrinsic::r600_read_global_size_y:
6851     if (Subtarget->isAmdHsaOS())
6852       return emitNonHSAIntrinsicError(DAG, DL, VT);
6853 
6854     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6855                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6856                                     Align(4), false);
6857   case Intrinsic::r600_read_global_size_z:
6858     if (Subtarget->isAmdHsaOS())
6859       return emitNonHSAIntrinsicError(DAG, DL, VT);
6860 
6861     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6862                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6863                                     Align(4), false);
6864   case Intrinsic::r600_read_local_size_x:
6865     if (Subtarget->isAmdHsaOS())
6866       return emitNonHSAIntrinsicError(DAG, DL, VT);
6867 
6868     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6869                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6870   case Intrinsic::r600_read_local_size_y:
6871     if (Subtarget->isAmdHsaOS())
6872       return emitNonHSAIntrinsicError(DAG, DL, VT);
6873 
6874     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6875                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6876   case Intrinsic::r600_read_local_size_z:
6877     if (Subtarget->isAmdHsaOS())
6878       return emitNonHSAIntrinsicError(DAG, DL, VT);
6879 
6880     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6881                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6882   case Intrinsic::amdgcn_workgroup_id_x:
6883     return getPreloadedValue(DAG, *MFI, VT,
6884                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6885   case Intrinsic::amdgcn_workgroup_id_y:
6886     return getPreloadedValue(DAG, *MFI, VT,
6887                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6888   case Intrinsic::amdgcn_workgroup_id_z:
6889     return getPreloadedValue(DAG, *MFI, VT,
6890                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6891   case Intrinsic::amdgcn_workitem_id_x:
6892     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6893       return DAG.getConstant(0, DL, MVT::i32);
6894 
6895     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6896                           SDLoc(DAG.getEntryNode()),
6897                           MFI->getArgInfo().WorkItemIDX);
6898   case Intrinsic::amdgcn_workitem_id_y:
6899     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6900       return DAG.getConstant(0, DL, MVT::i32);
6901 
6902     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6903                           SDLoc(DAG.getEntryNode()),
6904                           MFI->getArgInfo().WorkItemIDY);
6905   case Intrinsic::amdgcn_workitem_id_z:
6906     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6907       return DAG.getConstant(0, DL, MVT::i32);
6908 
6909     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6910                           SDLoc(DAG.getEntryNode()),
6911                           MFI->getArgInfo().WorkItemIDZ);
6912   case Intrinsic::amdgcn_wavefrontsize:
6913     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6914                            SDLoc(Op), MVT::i32);
6915   case Intrinsic::amdgcn_s_buffer_load: {
6916     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6917     if (CPol & ~AMDGPU::CPol::ALL)
6918       return Op;
6919     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6920                         DAG);
6921   }
6922   case Intrinsic::amdgcn_fdiv_fast:
6923     return lowerFDIV_FAST(Op, DAG);
6924   case Intrinsic::amdgcn_sin:
6925     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6926 
6927   case Intrinsic::amdgcn_cos:
6928     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6929 
6930   case Intrinsic::amdgcn_mul_u24:
6931     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6932   case Intrinsic::amdgcn_mul_i24:
6933     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6934 
6935   case Intrinsic::amdgcn_log_clamp: {
6936     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6937       return SDValue();
6938 
6939     return emitRemovedIntrinsicError(DAG, DL, VT);
6940   }
6941   case Intrinsic::amdgcn_ldexp:
6942     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6943                        Op.getOperand(1), Op.getOperand(2));
6944 
6945   case Intrinsic::amdgcn_fract:
6946     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6947 
6948   case Intrinsic::amdgcn_class:
6949     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6950                        Op.getOperand(1), Op.getOperand(2));
6951   case Intrinsic::amdgcn_div_fmas:
6952     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6953                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6954                        Op.getOperand(4));
6955 
6956   case Intrinsic::amdgcn_div_fixup:
6957     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6958                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6959 
6960   case Intrinsic::amdgcn_div_scale: {
6961     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6962 
6963     // Translate to the operands expected by the machine instruction. The
6964     // first parameter must be the same as the first instruction.
6965     SDValue Numerator = Op.getOperand(1);
6966     SDValue Denominator = Op.getOperand(2);
6967 
6968     // Note this order is opposite of the machine instruction's operations,
6969     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6970     // intrinsic has the numerator as the first operand to match a normal
6971     // division operation.
6972 
6973     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6974 
6975     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6976                        Denominator, Numerator);
6977   }
6978   case Intrinsic::amdgcn_icmp: {
6979     // There is a Pat that handles this variant, so return it as-is.
6980     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6981         Op.getConstantOperandVal(2) == 0 &&
6982         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6983       return Op;
6984     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6985   }
6986   case Intrinsic::amdgcn_fcmp: {
6987     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6988   }
6989   case Intrinsic::amdgcn_ballot:
6990     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6991   case Intrinsic::amdgcn_fmed3:
6992     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6993                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6994   case Intrinsic::amdgcn_fdot2:
6995     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6996                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6997                        Op.getOperand(4));
6998   case Intrinsic::amdgcn_fmul_legacy:
6999     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
7000                        Op.getOperand(1), Op.getOperand(2));
7001   case Intrinsic::amdgcn_sffbh:
7002     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
7003   case Intrinsic::amdgcn_sbfe:
7004     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
7005                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7006   case Intrinsic::amdgcn_ubfe:
7007     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
7008                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7009   case Intrinsic::amdgcn_cvt_pkrtz:
7010   case Intrinsic::amdgcn_cvt_pknorm_i16:
7011   case Intrinsic::amdgcn_cvt_pknorm_u16:
7012   case Intrinsic::amdgcn_cvt_pk_i16:
7013   case Intrinsic::amdgcn_cvt_pk_u16: {
7014     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
7015     EVT VT = Op.getValueType();
7016     unsigned Opcode;
7017 
7018     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
7019       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
7020     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
7021       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
7022     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
7023       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
7024     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
7025       Opcode = AMDGPUISD::CVT_PK_I16_I32;
7026     else
7027       Opcode = AMDGPUISD::CVT_PK_U16_U32;
7028 
7029     if (isTypeLegal(VT))
7030       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7031 
7032     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7033                                Op.getOperand(1), Op.getOperand(2));
7034     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7035   }
7036   case Intrinsic::amdgcn_fmad_ftz:
7037     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7038                        Op.getOperand(2), Op.getOperand(3));
7039 
7040   case Intrinsic::amdgcn_if_break:
7041     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7042                                       Op->getOperand(1), Op->getOperand(2)), 0);
7043 
7044   case Intrinsic::amdgcn_groupstaticsize: {
7045     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7046     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7047       return Op;
7048 
7049     const Module *M = MF.getFunction().getParent();
7050     const GlobalValue *GV =
7051         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7052     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7053                                             SIInstrInfo::MO_ABS32_LO);
7054     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7055   }
7056   case Intrinsic::amdgcn_is_shared:
7057   case Intrinsic::amdgcn_is_private: {
7058     SDLoc SL(Op);
7059     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7060       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7061     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7062     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7063                                  Op.getOperand(1));
7064 
7065     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7066                                 DAG.getConstant(1, SL, MVT::i32));
7067     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7068   }
7069   case Intrinsic::amdgcn_perm:
7070     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7071                        Op.getOperand(2), Op.getOperand(3));
7072   case Intrinsic::amdgcn_reloc_constant: {
7073     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7074     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7075     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7076     auto RelocSymbol = cast<GlobalVariable>(
7077         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7078     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7079                                             SIInstrInfo::MO_ABS32_LO);
7080     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7081   }
7082   default:
7083     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7084             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7085       return lowerImage(Op, ImageDimIntr, DAG, false);
7086 
7087     return Op;
7088   }
7089 }
7090 
7091 /// Update \p MMO based on the offset inputs to an intrinsic.
7092 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7093                             SDValue SOffset, SDValue Offset,
7094                             SDValue VIndex = SDValue()) {
7095   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7096       !isa<ConstantSDNode>(Offset)) {
7097     // The combined offset is not known to be constant, so we cannot represent
7098     // it in the MMO. Give up.
7099     MMO->setValue((Value *)nullptr);
7100     return;
7101   }
7102 
7103   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7104                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7105     // The strided index component of the address is not known to be zero, so we
7106     // cannot represent it in the MMO. Give up.
7107     MMO->setValue((Value *)nullptr);
7108     return;
7109   }
7110 
7111   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7112                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7113                  cast<ConstantSDNode>(Offset)->getSExtValue());
7114 }
7115 
7116 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7117                                                      SelectionDAG &DAG,
7118                                                      unsigned NewOpcode) const {
7119   SDLoc DL(Op);
7120 
7121   SDValue VData = Op.getOperand(2);
7122   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7123   SDValue Ops[] = {
7124     Op.getOperand(0), // Chain
7125     VData,            // vdata
7126     Op.getOperand(3), // rsrc
7127     DAG.getConstant(0, DL, MVT::i32), // vindex
7128     Offsets.first,    // voffset
7129     Op.getOperand(5), // soffset
7130     Offsets.second,   // offset
7131     Op.getOperand(6), // cachepolicy
7132     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7133   };
7134 
7135   auto *M = cast<MemSDNode>(Op);
7136   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7137 
7138   EVT MemVT = VData.getValueType();
7139   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7140                                  M->getMemOperand());
7141 }
7142 
7143 // Return a value to use for the idxen operand by examining the vindex operand.
7144 static unsigned getIdxEn(SDValue VIndex) {
7145   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7146     // No need to set idxen if vindex is known to be zero.
7147     return VIndexC->getZExtValue() != 0;
7148   return 1;
7149 }
7150 
7151 SDValue
7152 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7153                                                 unsigned NewOpcode) const {
7154   SDLoc DL(Op);
7155 
7156   SDValue VData = Op.getOperand(2);
7157   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7158   SDValue Ops[] = {
7159     Op.getOperand(0), // Chain
7160     VData,            // vdata
7161     Op.getOperand(3), // rsrc
7162     Op.getOperand(4), // vindex
7163     Offsets.first,    // voffset
7164     Op.getOperand(6), // soffset
7165     Offsets.second,   // offset
7166     Op.getOperand(7), // cachepolicy
7167     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7168   };
7169 
7170   auto *M = cast<MemSDNode>(Op);
7171   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7172 
7173   EVT MemVT = VData.getValueType();
7174   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7175                                  M->getMemOperand());
7176 }
7177 
7178 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7179                                                  SelectionDAG &DAG) const {
7180   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7181   SDLoc DL(Op);
7182 
7183   switch (IntrID) {
7184   case Intrinsic::amdgcn_ds_ordered_add:
7185   case Intrinsic::amdgcn_ds_ordered_swap: {
7186     MemSDNode *M = cast<MemSDNode>(Op);
7187     SDValue Chain = M->getOperand(0);
7188     SDValue M0 = M->getOperand(2);
7189     SDValue Value = M->getOperand(3);
7190     unsigned IndexOperand = M->getConstantOperandVal(7);
7191     unsigned WaveRelease = M->getConstantOperandVal(8);
7192     unsigned WaveDone = M->getConstantOperandVal(9);
7193 
7194     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7195     IndexOperand &= ~0x3f;
7196     unsigned CountDw = 0;
7197 
7198     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7199       CountDw = (IndexOperand >> 24) & 0xf;
7200       IndexOperand &= ~(0xf << 24);
7201 
7202       if (CountDw < 1 || CountDw > 4) {
7203         report_fatal_error(
7204             "ds_ordered_count: dword count must be between 1 and 4");
7205       }
7206     }
7207 
7208     if (IndexOperand)
7209       report_fatal_error("ds_ordered_count: bad index operand");
7210 
7211     if (WaveDone && !WaveRelease)
7212       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7213 
7214     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7215     unsigned ShaderType =
7216         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7217     unsigned Offset0 = OrderedCountIndex << 2;
7218     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7219                        (Instruction << 4);
7220 
7221     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7222       Offset1 |= (CountDw - 1) << 6;
7223 
7224     unsigned Offset = Offset0 | (Offset1 << 8);
7225 
7226     SDValue Ops[] = {
7227       Chain,
7228       Value,
7229       DAG.getTargetConstant(Offset, DL, MVT::i16),
7230       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7231     };
7232     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7233                                    M->getVTList(), Ops, M->getMemoryVT(),
7234                                    M->getMemOperand());
7235   }
7236   case Intrinsic::amdgcn_ds_fadd: {
7237     MemSDNode *M = cast<MemSDNode>(Op);
7238     unsigned Opc;
7239     switch (IntrID) {
7240     case Intrinsic::amdgcn_ds_fadd:
7241       Opc = ISD::ATOMIC_LOAD_FADD;
7242       break;
7243     }
7244 
7245     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7246                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7247                          M->getMemOperand());
7248   }
7249   case Intrinsic::amdgcn_atomic_inc:
7250   case Intrinsic::amdgcn_atomic_dec:
7251   case Intrinsic::amdgcn_ds_fmin:
7252   case Intrinsic::amdgcn_ds_fmax: {
7253     MemSDNode *M = cast<MemSDNode>(Op);
7254     unsigned Opc;
7255     switch (IntrID) {
7256     case Intrinsic::amdgcn_atomic_inc:
7257       Opc = AMDGPUISD::ATOMIC_INC;
7258       break;
7259     case Intrinsic::amdgcn_atomic_dec:
7260       Opc = AMDGPUISD::ATOMIC_DEC;
7261       break;
7262     case Intrinsic::amdgcn_ds_fmin:
7263       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7264       break;
7265     case Intrinsic::amdgcn_ds_fmax:
7266       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7267       break;
7268     default:
7269       llvm_unreachable("Unknown intrinsic!");
7270     }
7271     SDValue Ops[] = {
7272       M->getOperand(0), // Chain
7273       M->getOperand(2), // Ptr
7274       M->getOperand(3)  // Value
7275     };
7276 
7277     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7278                                    M->getMemoryVT(), M->getMemOperand());
7279   }
7280   case Intrinsic::amdgcn_buffer_load:
7281   case Intrinsic::amdgcn_buffer_load_format: {
7282     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7283     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7284     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7285     SDValue Ops[] = {
7286       Op.getOperand(0), // Chain
7287       Op.getOperand(2), // rsrc
7288       Op.getOperand(3), // vindex
7289       SDValue(),        // voffset -- will be set by setBufferOffsets
7290       SDValue(),        // soffset -- will be set by setBufferOffsets
7291       SDValue(),        // offset -- will be set by setBufferOffsets
7292       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7293       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7294     };
7295     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7296 
7297     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7298         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7299 
7300     EVT VT = Op.getValueType();
7301     EVT IntVT = VT.changeTypeToInteger();
7302     auto *M = cast<MemSDNode>(Op);
7303     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7304     EVT LoadVT = Op.getValueType();
7305 
7306     if (LoadVT.getScalarType() == MVT::f16)
7307       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7308                                  M, DAG, Ops);
7309 
7310     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7311     if (LoadVT.getScalarType() == MVT::i8 ||
7312         LoadVT.getScalarType() == MVT::i16)
7313       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7314 
7315     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7316                                M->getMemOperand(), DAG);
7317   }
7318   case Intrinsic::amdgcn_raw_buffer_load:
7319   case Intrinsic::amdgcn_raw_buffer_load_format: {
7320     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7321 
7322     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7323     SDValue Ops[] = {
7324       Op.getOperand(0), // Chain
7325       Op.getOperand(2), // rsrc
7326       DAG.getConstant(0, DL, MVT::i32), // vindex
7327       Offsets.first,    // voffset
7328       Op.getOperand(4), // soffset
7329       Offsets.second,   // offset
7330       Op.getOperand(5), // cachepolicy, swizzled buffer
7331       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7332     };
7333 
7334     auto *M = cast<MemSDNode>(Op);
7335     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7336     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7337   }
7338   case Intrinsic::amdgcn_struct_buffer_load:
7339   case Intrinsic::amdgcn_struct_buffer_load_format: {
7340     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7341 
7342     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7343     SDValue Ops[] = {
7344       Op.getOperand(0), // Chain
7345       Op.getOperand(2), // rsrc
7346       Op.getOperand(3), // vindex
7347       Offsets.first,    // voffset
7348       Op.getOperand(5), // soffset
7349       Offsets.second,   // offset
7350       Op.getOperand(6), // cachepolicy, swizzled buffer
7351       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7352     };
7353 
7354     auto *M = cast<MemSDNode>(Op);
7355     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7356     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7357   }
7358   case Intrinsic::amdgcn_tbuffer_load: {
7359     MemSDNode *M = cast<MemSDNode>(Op);
7360     EVT LoadVT = Op.getValueType();
7361 
7362     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7363     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7364     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7365     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7366     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7367     SDValue Ops[] = {
7368       Op.getOperand(0),  // Chain
7369       Op.getOperand(2),  // rsrc
7370       Op.getOperand(3),  // vindex
7371       Op.getOperand(4),  // voffset
7372       Op.getOperand(5),  // soffset
7373       Op.getOperand(6),  // offset
7374       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7375       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7376       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7377     };
7378 
7379     if (LoadVT.getScalarType() == MVT::f16)
7380       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7381                                  M, DAG, Ops);
7382     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7383                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7384                                DAG);
7385   }
7386   case Intrinsic::amdgcn_raw_tbuffer_load: {
7387     MemSDNode *M = cast<MemSDNode>(Op);
7388     EVT LoadVT = Op.getValueType();
7389     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7390 
7391     SDValue Ops[] = {
7392       Op.getOperand(0),  // Chain
7393       Op.getOperand(2),  // rsrc
7394       DAG.getConstant(0, DL, MVT::i32), // vindex
7395       Offsets.first,     // voffset
7396       Op.getOperand(4),  // soffset
7397       Offsets.second,    // offset
7398       Op.getOperand(5),  // format
7399       Op.getOperand(6),  // cachepolicy, swizzled buffer
7400       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7401     };
7402 
7403     if (LoadVT.getScalarType() == MVT::f16)
7404       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7405                                  M, DAG, Ops);
7406     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7407                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7408                                DAG);
7409   }
7410   case Intrinsic::amdgcn_struct_tbuffer_load: {
7411     MemSDNode *M = cast<MemSDNode>(Op);
7412     EVT LoadVT = Op.getValueType();
7413     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7414 
7415     SDValue Ops[] = {
7416       Op.getOperand(0),  // Chain
7417       Op.getOperand(2),  // rsrc
7418       Op.getOperand(3),  // vindex
7419       Offsets.first,     // voffset
7420       Op.getOperand(5),  // soffset
7421       Offsets.second,    // offset
7422       Op.getOperand(6),  // format
7423       Op.getOperand(7),  // cachepolicy, swizzled buffer
7424       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7425     };
7426 
7427     if (LoadVT.getScalarType() == MVT::f16)
7428       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7429                                  M, DAG, Ops);
7430     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7431                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7432                                DAG);
7433   }
7434   case Intrinsic::amdgcn_buffer_atomic_swap:
7435   case Intrinsic::amdgcn_buffer_atomic_add:
7436   case Intrinsic::amdgcn_buffer_atomic_sub:
7437   case Intrinsic::amdgcn_buffer_atomic_csub:
7438   case Intrinsic::amdgcn_buffer_atomic_smin:
7439   case Intrinsic::amdgcn_buffer_atomic_umin:
7440   case Intrinsic::amdgcn_buffer_atomic_smax:
7441   case Intrinsic::amdgcn_buffer_atomic_umax:
7442   case Intrinsic::amdgcn_buffer_atomic_and:
7443   case Intrinsic::amdgcn_buffer_atomic_or:
7444   case Intrinsic::amdgcn_buffer_atomic_xor:
7445   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7446     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7447     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7448     SDValue Ops[] = {
7449       Op.getOperand(0), // Chain
7450       Op.getOperand(2), // vdata
7451       Op.getOperand(3), // rsrc
7452       Op.getOperand(4), // vindex
7453       SDValue(),        // voffset -- will be set by setBufferOffsets
7454       SDValue(),        // soffset -- will be set by setBufferOffsets
7455       SDValue(),        // offset -- will be set by setBufferOffsets
7456       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7457       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7458     };
7459     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7460 
7461     EVT VT = Op.getValueType();
7462 
7463     auto *M = cast<MemSDNode>(Op);
7464     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7465     unsigned Opcode = 0;
7466 
7467     switch (IntrID) {
7468     case Intrinsic::amdgcn_buffer_atomic_swap:
7469       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7470       break;
7471     case Intrinsic::amdgcn_buffer_atomic_add:
7472       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7473       break;
7474     case Intrinsic::amdgcn_buffer_atomic_sub:
7475       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7476       break;
7477     case Intrinsic::amdgcn_buffer_atomic_csub:
7478       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7479       break;
7480     case Intrinsic::amdgcn_buffer_atomic_smin:
7481       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7482       break;
7483     case Intrinsic::amdgcn_buffer_atomic_umin:
7484       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7485       break;
7486     case Intrinsic::amdgcn_buffer_atomic_smax:
7487       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7488       break;
7489     case Intrinsic::amdgcn_buffer_atomic_umax:
7490       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7491       break;
7492     case Intrinsic::amdgcn_buffer_atomic_and:
7493       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7494       break;
7495     case Intrinsic::amdgcn_buffer_atomic_or:
7496       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7497       break;
7498     case Intrinsic::amdgcn_buffer_atomic_xor:
7499       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7500       break;
7501     case Intrinsic::amdgcn_buffer_atomic_fadd:
7502       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7503         DiagnosticInfoUnsupported
7504           NoFpRet(DAG.getMachineFunction().getFunction(),
7505                   "return versions of fp atomics not supported",
7506                   DL.getDebugLoc(), DS_Error);
7507         DAG.getContext()->diagnose(NoFpRet);
7508         return SDValue();
7509       }
7510       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7511       break;
7512     default:
7513       llvm_unreachable("unhandled atomic opcode");
7514     }
7515 
7516     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7517                                    M->getMemOperand());
7518   }
7519   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7520     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7521   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7522     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7523   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7524     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7525   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7526     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7527   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7528     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7529   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7530     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7531   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7532     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7533   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7534     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7535   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7536     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7537   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7538     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7539   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7540     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7541   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7542     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7543   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7544     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7545   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7546     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7547   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7548     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7549   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7550     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7551   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7552     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7553   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7554     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7555   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7556     return lowerStructBufferAtomicIntrin(Op, DAG,
7557                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7558   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7559     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7560   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7561     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7562   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7563     return lowerStructBufferAtomicIntrin(Op, DAG,
7564                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7565   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7566     return lowerStructBufferAtomicIntrin(Op, DAG,
7567                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7568   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7569     return lowerStructBufferAtomicIntrin(Op, DAG,
7570                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7571   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7572     return lowerStructBufferAtomicIntrin(Op, DAG,
7573                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7574   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7575     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7576   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7577     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7578   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7579     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7580   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7581     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7582   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7583     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7584 
7585   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7586     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7587     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7588     SDValue Ops[] = {
7589       Op.getOperand(0), // Chain
7590       Op.getOperand(2), // src
7591       Op.getOperand(3), // cmp
7592       Op.getOperand(4), // rsrc
7593       Op.getOperand(5), // vindex
7594       SDValue(),        // voffset -- will be set by setBufferOffsets
7595       SDValue(),        // soffset -- will be set by setBufferOffsets
7596       SDValue(),        // offset -- will be set by setBufferOffsets
7597       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7598       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7599     };
7600     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7601 
7602     EVT VT = Op.getValueType();
7603     auto *M = cast<MemSDNode>(Op);
7604     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7605 
7606     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7607                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7608   }
7609   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7610     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7611     SDValue Ops[] = {
7612       Op.getOperand(0), // Chain
7613       Op.getOperand(2), // src
7614       Op.getOperand(3), // cmp
7615       Op.getOperand(4), // rsrc
7616       DAG.getConstant(0, DL, MVT::i32), // vindex
7617       Offsets.first,    // voffset
7618       Op.getOperand(6), // soffset
7619       Offsets.second,   // offset
7620       Op.getOperand(7), // cachepolicy
7621       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7622     };
7623     EVT VT = Op.getValueType();
7624     auto *M = cast<MemSDNode>(Op);
7625     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7626 
7627     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7628                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7629   }
7630   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7631     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7632     SDValue Ops[] = {
7633       Op.getOperand(0), // Chain
7634       Op.getOperand(2), // src
7635       Op.getOperand(3), // cmp
7636       Op.getOperand(4), // rsrc
7637       Op.getOperand(5), // vindex
7638       Offsets.first,    // voffset
7639       Op.getOperand(7), // soffset
7640       Offsets.second,   // offset
7641       Op.getOperand(8), // cachepolicy
7642       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7643     };
7644     EVT VT = Op.getValueType();
7645     auto *M = cast<MemSDNode>(Op);
7646     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7647 
7648     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7649                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7650   }
7651   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7652     MemSDNode *M = cast<MemSDNode>(Op);
7653     SDValue NodePtr = M->getOperand(2);
7654     SDValue RayExtent = M->getOperand(3);
7655     SDValue RayOrigin = M->getOperand(4);
7656     SDValue RayDir = M->getOperand(5);
7657     SDValue RayInvDir = M->getOperand(6);
7658     SDValue TDescr = M->getOperand(7);
7659 
7660     assert(NodePtr.getValueType() == MVT::i32 ||
7661            NodePtr.getValueType() == MVT::i64);
7662     assert(RayDir.getValueType() == MVT::v3f16 ||
7663            RayDir.getValueType() == MVT::v3f32);
7664 
7665     if (!Subtarget->hasGFX10_AEncoding()) {
7666       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7667       return SDValue();
7668     }
7669 
7670     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7671     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7672     const unsigned NumVDataDwords = 4;
7673     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7674     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7675                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7676     const unsigned BaseOpcodes[2][2] = {
7677         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7678         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7679          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7680     int Opcode;
7681     if (UseNSA) {
7682       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7683                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7684                                      NumVAddrDwords);
7685     } else {
7686       Opcode = AMDGPU::getMIMGOpcode(
7687           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7688           PowerOf2Ceil(NumVAddrDwords));
7689     }
7690     assert(Opcode != -1);
7691 
7692     SmallVector<SDValue, 16> Ops;
7693 
7694     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7695       SmallVector<SDValue, 3> Lanes;
7696       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7697       if (Lanes[0].getValueSizeInBits() == 32) {
7698         for (unsigned I = 0; I < 3; ++I)
7699           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7700       } else {
7701         if (IsAligned) {
7702           Ops.push_back(
7703             DAG.getBitcast(MVT::i32,
7704                            DAG.getBuildVector(MVT::v2f16, DL,
7705                                               { Lanes[0], Lanes[1] })));
7706           Ops.push_back(Lanes[2]);
7707         } else {
7708           SDValue Elt0 = Ops.pop_back_val();
7709           Ops.push_back(
7710             DAG.getBitcast(MVT::i32,
7711                            DAG.getBuildVector(MVT::v2f16, DL,
7712                                               { Elt0, Lanes[0] })));
7713           Ops.push_back(
7714             DAG.getBitcast(MVT::i32,
7715                            DAG.getBuildVector(MVT::v2f16, DL,
7716                                               { Lanes[1], Lanes[2] })));
7717         }
7718       }
7719     };
7720 
7721     if (Is64)
7722       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7723     else
7724       Ops.push_back(NodePtr);
7725 
7726     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7727     packLanes(RayOrigin, true);
7728     packLanes(RayDir, true);
7729     packLanes(RayInvDir, false);
7730 
7731     if (!UseNSA) {
7732       // Build a single vector containing all the operands so far prepared.
7733       if (NumVAddrDwords > 8) {
7734         SDValue Undef = DAG.getUNDEF(MVT::i32);
7735         Ops.append(16 - Ops.size(), Undef);
7736       }
7737       assert(Ops.size() == 8 || Ops.size() == 16);
7738       SDValue MergedOps = DAG.getBuildVector(
7739           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7740       Ops.clear();
7741       Ops.push_back(MergedOps);
7742     }
7743 
7744     Ops.push_back(TDescr);
7745     if (IsA16)
7746       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7747     Ops.push_back(M->getChain());
7748 
7749     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7750     MachineMemOperand *MemRef = M->getMemOperand();
7751     DAG.setNodeMemRefs(NewNode, {MemRef});
7752     return SDValue(NewNode, 0);
7753   }
7754   case Intrinsic::amdgcn_global_atomic_fadd:
7755     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7756       DiagnosticInfoUnsupported
7757         NoFpRet(DAG.getMachineFunction().getFunction(),
7758                 "return versions of fp atomics not supported",
7759                 DL.getDebugLoc(), DS_Error);
7760       DAG.getContext()->diagnose(NoFpRet);
7761       return SDValue();
7762     }
7763     LLVM_FALLTHROUGH;
7764   case Intrinsic::amdgcn_global_atomic_fmin:
7765   case Intrinsic::amdgcn_global_atomic_fmax:
7766   case Intrinsic::amdgcn_flat_atomic_fadd:
7767   case Intrinsic::amdgcn_flat_atomic_fmin:
7768   case Intrinsic::amdgcn_flat_atomic_fmax: {
7769     MemSDNode *M = cast<MemSDNode>(Op);
7770     SDValue Ops[] = {
7771       M->getOperand(0), // Chain
7772       M->getOperand(2), // Ptr
7773       M->getOperand(3)  // Value
7774     };
7775     unsigned Opcode = 0;
7776     switch (IntrID) {
7777     case Intrinsic::amdgcn_global_atomic_fadd:
7778     case Intrinsic::amdgcn_flat_atomic_fadd: {
7779       EVT VT = Op.getOperand(3).getValueType();
7780       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7781                            DAG.getVTList(VT, MVT::Other), Ops,
7782                            M->getMemOperand());
7783     }
7784     case Intrinsic::amdgcn_global_atomic_fmin:
7785     case Intrinsic::amdgcn_flat_atomic_fmin: {
7786       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7787       break;
7788     }
7789     case Intrinsic::amdgcn_global_atomic_fmax:
7790     case Intrinsic::amdgcn_flat_atomic_fmax: {
7791       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7792       break;
7793     }
7794     default:
7795       llvm_unreachable("unhandled atomic opcode");
7796     }
7797     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7798                                    M->getVTList(), Ops, M->getMemoryVT(),
7799                                    M->getMemOperand());
7800   }
7801   default:
7802 
7803     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7804             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7805       return lowerImage(Op, ImageDimIntr, DAG, true);
7806 
7807     return SDValue();
7808   }
7809 }
7810 
7811 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7812 // dwordx4 if on SI.
7813 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7814                                               SDVTList VTList,
7815                                               ArrayRef<SDValue> Ops, EVT MemVT,
7816                                               MachineMemOperand *MMO,
7817                                               SelectionDAG &DAG) const {
7818   EVT VT = VTList.VTs[0];
7819   EVT WidenedVT = VT;
7820   EVT WidenedMemVT = MemVT;
7821   if (!Subtarget->hasDwordx3LoadStores() &&
7822       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7823     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7824                                  WidenedVT.getVectorElementType(), 4);
7825     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7826                                     WidenedMemVT.getVectorElementType(), 4);
7827     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7828   }
7829 
7830   assert(VTList.NumVTs == 2);
7831   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7832 
7833   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7834                                        WidenedMemVT, MMO);
7835   if (WidenedVT != VT) {
7836     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7837                                DAG.getVectorIdxConstant(0, DL));
7838     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7839   }
7840   return NewOp;
7841 }
7842 
7843 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7844                                          bool ImageStore) const {
7845   EVT StoreVT = VData.getValueType();
7846 
7847   // No change for f16 and legal vector D16 types.
7848   if (!StoreVT.isVector())
7849     return VData;
7850 
7851   SDLoc DL(VData);
7852   unsigned NumElements = StoreVT.getVectorNumElements();
7853 
7854   if (Subtarget->hasUnpackedD16VMem()) {
7855     // We need to unpack the packed data to store.
7856     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7857     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7858 
7859     EVT EquivStoreVT =
7860         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7861     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7862     return DAG.UnrollVectorOp(ZExt.getNode());
7863   }
7864 
7865   // The sq block of gfx8.1 does not estimate register use correctly for d16
7866   // image store instructions. The data operand is computed as if it were not a
7867   // d16 image instruction.
7868   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7869     // Bitcast to i16
7870     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7871     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7872 
7873     // Decompose into scalars
7874     SmallVector<SDValue, 4> Elts;
7875     DAG.ExtractVectorElements(IntVData, Elts);
7876 
7877     // Group pairs of i16 into v2i16 and bitcast to i32
7878     SmallVector<SDValue, 4> PackedElts;
7879     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7880       SDValue Pair =
7881           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7882       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7883       PackedElts.push_back(IntPair);
7884     }
7885     if ((NumElements % 2) == 1) {
7886       // Handle v3i16
7887       unsigned I = Elts.size() / 2;
7888       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7889                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7890       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7891       PackedElts.push_back(IntPair);
7892     }
7893 
7894     // Pad using UNDEF
7895     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7896 
7897     // Build final vector
7898     EVT VecVT =
7899         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7900     return DAG.getBuildVector(VecVT, DL, PackedElts);
7901   }
7902 
7903   if (NumElements == 3) {
7904     EVT IntStoreVT =
7905         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7906     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7907 
7908     EVT WidenedStoreVT = EVT::getVectorVT(
7909         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7910     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7911                                          WidenedStoreVT.getStoreSizeInBits());
7912     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7913     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7914   }
7915 
7916   assert(isTypeLegal(StoreVT));
7917   return VData;
7918 }
7919 
7920 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7921                                               SelectionDAG &DAG) const {
7922   SDLoc DL(Op);
7923   SDValue Chain = Op.getOperand(0);
7924   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7925   MachineFunction &MF = DAG.getMachineFunction();
7926 
7927   switch (IntrinsicID) {
7928   case Intrinsic::amdgcn_exp_compr: {
7929     SDValue Src0 = Op.getOperand(4);
7930     SDValue Src1 = Op.getOperand(5);
7931     // Hack around illegal type on SI by directly selecting it.
7932     if (isTypeLegal(Src0.getValueType()))
7933       return SDValue();
7934 
7935     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7936     SDValue Undef = DAG.getUNDEF(MVT::f32);
7937     const SDValue Ops[] = {
7938       Op.getOperand(2), // tgt
7939       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7940       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7941       Undef, // src2
7942       Undef, // src3
7943       Op.getOperand(7), // vm
7944       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7945       Op.getOperand(3), // en
7946       Op.getOperand(0) // Chain
7947     };
7948 
7949     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7950     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7951   }
7952   case Intrinsic::amdgcn_s_barrier: {
7953     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7954       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7955       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7956       if (WGSize <= ST.getWavefrontSize())
7957         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7958                                           Op.getOperand(0)), 0);
7959     }
7960     return SDValue();
7961   };
7962   case Intrinsic::amdgcn_tbuffer_store: {
7963     SDValue VData = Op.getOperand(2);
7964     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7965     if (IsD16)
7966       VData = handleD16VData(VData, DAG);
7967     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7968     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7969     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7970     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7971     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7972     SDValue Ops[] = {
7973       Chain,
7974       VData,             // vdata
7975       Op.getOperand(3),  // rsrc
7976       Op.getOperand(4),  // vindex
7977       Op.getOperand(5),  // voffset
7978       Op.getOperand(6),  // soffset
7979       Op.getOperand(7),  // offset
7980       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7981       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7982       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7983     };
7984     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7985                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7986     MemSDNode *M = cast<MemSDNode>(Op);
7987     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7988                                    M->getMemoryVT(), M->getMemOperand());
7989   }
7990 
7991   case Intrinsic::amdgcn_struct_tbuffer_store: {
7992     SDValue VData = Op.getOperand(2);
7993     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7994     if (IsD16)
7995       VData = handleD16VData(VData, DAG);
7996     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7997     SDValue Ops[] = {
7998       Chain,
7999       VData,             // vdata
8000       Op.getOperand(3),  // rsrc
8001       Op.getOperand(4),  // vindex
8002       Offsets.first,     // voffset
8003       Op.getOperand(6),  // soffset
8004       Offsets.second,    // offset
8005       Op.getOperand(7),  // format
8006       Op.getOperand(8),  // cachepolicy, swizzled buffer
8007       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8008     };
8009     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8010                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8011     MemSDNode *M = cast<MemSDNode>(Op);
8012     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8013                                    M->getMemoryVT(), M->getMemOperand());
8014   }
8015 
8016   case Intrinsic::amdgcn_raw_tbuffer_store: {
8017     SDValue VData = Op.getOperand(2);
8018     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8019     if (IsD16)
8020       VData = handleD16VData(VData, DAG);
8021     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8022     SDValue Ops[] = {
8023       Chain,
8024       VData,             // vdata
8025       Op.getOperand(3),  // rsrc
8026       DAG.getConstant(0, DL, MVT::i32), // vindex
8027       Offsets.first,     // voffset
8028       Op.getOperand(5),  // soffset
8029       Offsets.second,    // offset
8030       Op.getOperand(6),  // format
8031       Op.getOperand(7),  // cachepolicy, swizzled buffer
8032       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8033     };
8034     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8035                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8036     MemSDNode *M = cast<MemSDNode>(Op);
8037     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8038                                    M->getMemoryVT(), M->getMemOperand());
8039   }
8040 
8041   case Intrinsic::amdgcn_buffer_store:
8042   case Intrinsic::amdgcn_buffer_store_format: {
8043     SDValue VData = Op.getOperand(2);
8044     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8045     if (IsD16)
8046       VData = handleD16VData(VData, DAG);
8047     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8048     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8049     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8050     SDValue Ops[] = {
8051       Chain,
8052       VData,
8053       Op.getOperand(3), // rsrc
8054       Op.getOperand(4), // vindex
8055       SDValue(), // voffset -- will be set by setBufferOffsets
8056       SDValue(), // soffset -- will be set by setBufferOffsets
8057       SDValue(), // offset -- will be set by setBufferOffsets
8058       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8059       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8060     };
8061     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8062 
8063     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8064                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8065     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8066     MemSDNode *M = cast<MemSDNode>(Op);
8067     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8068 
8069     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8070     EVT VDataType = VData.getValueType().getScalarType();
8071     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8072       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8073 
8074     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8075                                    M->getMemoryVT(), M->getMemOperand());
8076   }
8077 
8078   case Intrinsic::amdgcn_raw_buffer_store:
8079   case Intrinsic::amdgcn_raw_buffer_store_format: {
8080     const bool IsFormat =
8081         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8082 
8083     SDValue VData = Op.getOperand(2);
8084     EVT VDataVT = VData.getValueType();
8085     EVT EltType = VDataVT.getScalarType();
8086     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8087     if (IsD16) {
8088       VData = handleD16VData(VData, DAG);
8089       VDataVT = VData.getValueType();
8090     }
8091 
8092     if (!isTypeLegal(VDataVT)) {
8093       VData =
8094           DAG.getNode(ISD::BITCAST, DL,
8095                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8096     }
8097 
8098     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8099     SDValue Ops[] = {
8100       Chain,
8101       VData,
8102       Op.getOperand(3), // rsrc
8103       DAG.getConstant(0, DL, MVT::i32), // vindex
8104       Offsets.first,    // voffset
8105       Op.getOperand(5), // soffset
8106       Offsets.second,   // offset
8107       Op.getOperand(6), // cachepolicy, swizzled buffer
8108       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8109     };
8110     unsigned Opc =
8111         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8112     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8113     MemSDNode *M = cast<MemSDNode>(Op);
8114     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8115 
8116     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8117     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8118       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8119 
8120     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8121                                    M->getMemoryVT(), M->getMemOperand());
8122   }
8123 
8124   case Intrinsic::amdgcn_struct_buffer_store:
8125   case Intrinsic::amdgcn_struct_buffer_store_format: {
8126     const bool IsFormat =
8127         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8128 
8129     SDValue VData = Op.getOperand(2);
8130     EVT VDataVT = VData.getValueType();
8131     EVT EltType = VDataVT.getScalarType();
8132     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8133 
8134     if (IsD16) {
8135       VData = handleD16VData(VData, DAG);
8136       VDataVT = VData.getValueType();
8137     }
8138 
8139     if (!isTypeLegal(VDataVT)) {
8140       VData =
8141           DAG.getNode(ISD::BITCAST, DL,
8142                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8143     }
8144 
8145     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8146     SDValue Ops[] = {
8147       Chain,
8148       VData,
8149       Op.getOperand(3), // rsrc
8150       Op.getOperand(4), // vindex
8151       Offsets.first,    // voffset
8152       Op.getOperand(6), // soffset
8153       Offsets.second,   // offset
8154       Op.getOperand(7), // cachepolicy, swizzled buffer
8155       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8156     };
8157     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8158                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8159     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8160     MemSDNode *M = cast<MemSDNode>(Op);
8161     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8162 
8163     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8164     EVT VDataType = VData.getValueType().getScalarType();
8165     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8166       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8167 
8168     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8169                                    M->getMemoryVT(), M->getMemOperand());
8170   }
8171   case Intrinsic::amdgcn_end_cf:
8172     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8173                                       Op->getOperand(2), Chain), 0);
8174 
8175   default: {
8176     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8177             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8178       return lowerImage(Op, ImageDimIntr, DAG, true);
8179 
8180     return Op;
8181   }
8182   }
8183 }
8184 
8185 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8186 // offset (the offset that is included in bounds checking and swizzling, to be
8187 // split between the instruction's voffset and immoffset fields) and soffset
8188 // (the offset that is excluded from bounds checking and swizzling, to go in
8189 // the instruction's soffset field).  This function takes the first kind of
8190 // offset and figures out how to split it between voffset and immoffset.
8191 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8192     SDValue Offset, SelectionDAG &DAG) const {
8193   SDLoc DL(Offset);
8194   const unsigned MaxImm = 4095;
8195   SDValue N0 = Offset;
8196   ConstantSDNode *C1 = nullptr;
8197 
8198   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8199     N0 = SDValue();
8200   else if (DAG.isBaseWithConstantOffset(N0)) {
8201     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8202     N0 = N0.getOperand(0);
8203   }
8204 
8205   if (C1) {
8206     unsigned ImmOffset = C1->getZExtValue();
8207     // If the immediate value is too big for the immoffset field, put the value
8208     // and -4096 into the immoffset field so that the value that is copied/added
8209     // for the voffset field is a multiple of 4096, and it stands more chance
8210     // of being CSEd with the copy/add for another similar load/store.
8211     // However, do not do that rounding down to a multiple of 4096 if that is a
8212     // negative number, as it appears to be illegal to have a negative offset
8213     // in the vgpr, even if adding the immediate offset makes it positive.
8214     unsigned Overflow = ImmOffset & ~MaxImm;
8215     ImmOffset -= Overflow;
8216     if ((int32_t)Overflow < 0) {
8217       Overflow += ImmOffset;
8218       ImmOffset = 0;
8219     }
8220     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8221     if (Overflow) {
8222       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8223       if (!N0)
8224         N0 = OverflowVal;
8225       else {
8226         SDValue Ops[] = { N0, OverflowVal };
8227         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8228       }
8229     }
8230   }
8231   if (!N0)
8232     N0 = DAG.getConstant(0, DL, MVT::i32);
8233   if (!C1)
8234     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8235   return {N0, SDValue(C1, 0)};
8236 }
8237 
8238 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8239 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8240 // pointed to by Offsets.
8241 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8242                                         SelectionDAG &DAG, SDValue *Offsets,
8243                                         Align Alignment) const {
8244   SDLoc DL(CombinedOffset);
8245   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8246     uint32_t Imm = C->getZExtValue();
8247     uint32_t SOffset, ImmOffset;
8248     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8249                                  Alignment)) {
8250       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8251       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8252       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8253       return;
8254     }
8255   }
8256   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8257     SDValue N0 = CombinedOffset.getOperand(0);
8258     SDValue N1 = CombinedOffset.getOperand(1);
8259     uint32_t SOffset, ImmOffset;
8260     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8261     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8262                                                 Subtarget, Alignment)) {
8263       Offsets[0] = N0;
8264       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8265       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8266       return;
8267     }
8268   }
8269   Offsets[0] = CombinedOffset;
8270   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8271   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8272 }
8273 
8274 // Handle 8 bit and 16 bit buffer loads
8275 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8276                                                      EVT LoadVT, SDLoc DL,
8277                                                      ArrayRef<SDValue> Ops,
8278                                                      MemSDNode *M) const {
8279   EVT IntVT = LoadVT.changeTypeToInteger();
8280   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8281          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8282 
8283   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8284   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8285                                                Ops, IntVT,
8286                                                M->getMemOperand());
8287   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8288   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8289 
8290   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8291 }
8292 
8293 // Handle 8 bit and 16 bit buffer stores
8294 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8295                                                       EVT VDataType, SDLoc DL,
8296                                                       SDValue Ops[],
8297                                                       MemSDNode *M) const {
8298   if (VDataType == MVT::f16)
8299     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8300 
8301   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8302   Ops[1] = BufferStoreExt;
8303   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8304                                  AMDGPUISD::BUFFER_STORE_SHORT;
8305   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8306   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8307                                      M->getMemOperand());
8308 }
8309 
8310 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8311                                  ISD::LoadExtType ExtType, SDValue Op,
8312                                  const SDLoc &SL, EVT VT) {
8313   if (VT.bitsLT(Op.getValueType()))
8314     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8315 
8316   switch (ExtType) {
8317   case ISD::SEXTLOAD:
8318     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8319   case ISD::ZEXTLOAD:
8320     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8321   case ISD::EXTLOAD:
8322     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8323   case ISD::NON_EXTLOAD:
8324     return Op;
8325   }
8326 
8327   llvm_unreachable("invalid ext type");
8328 }
8329 
8330 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8331   SelectionDAG &DAG = DCI.DAG;
8332   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8333     return SDValue();
8334 
8335   // FIXME: Constant loads should all be marked invariant.
8336   unsigned AS = Ld->getAddressSpace();
8337   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8338       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8339       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8340     return SDValue();
8341 
8342   // Don't do this early, since it may interfere with adjacent load merging for
8343   // illegal types. We can avoid losing alignment information for exotic types
8344   // pre-legalize.
8345   EVT MemVT = Ld->getMemoryVT();
8346   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8347       MemVT.getSizeInBits() >= 32)
8348     return SDValue();
8349 
8350   SDLoc SL(Ld);
8351 
8352   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8353          "unexpected vector extload");
8354 
8355   // TODO: Drop only high part of range.
8356   SDValue Ptr = Ld->getBasePtr();
8357   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8358                                 MVT::i32, SL, Ld->getChain(), Ptr,
8359                                 Ld->getOffset(),
8360                                 Ld->getPointerInfo(), MVT::i32,
8361                                 Ld->getAlignment(),
8362                                 Ld->getMemOperand()->getFlags(),
8363                                 Ld->getAAInfo(),
8364                                 nullptr); // Drop ranges
8365 
8366   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8367   if (MemVT.isFloatingPoint()) {
8368     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8369            "unexpected fp extload");
8370     TruncVT = MemVT.changeTypeToInteger();
8371   }
8372 
8373   SDValue Cvt = NewLoad;
8374   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8375     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8376                       DAG.getValueType(TruncVT));
8377   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8378              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8379     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8380   } else {
8381     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8382   }
8383 
8384   EVT VT = Ld->getValueType(0);
8385   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8386 
8387   DCI.AddToWorklist(Cvt.getNode());
8388 
8389   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8390   // the appropriate extension from the 32-bit load.
8391   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8392   DCI.AddToWorklist(Cvt.getNode());
8393 
8394   // Handle conversion back to floating point if necessary.
8395   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8396 
8397   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8398 }
8399 
8400 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8401   SDLoc DL(Op);
8402   LoadSDNode *Load = cast<LoadSDNode>(Op);
8403   ISD::LoadExtType ExtType = Load->getExtensionType();
8404   EVT MemVT = Load->getMemoryVT();
8405 
8406   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8407     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8408       return SDValue();
8409 
8410     // FIXME: Copied from PPC
8411     // First, load into 32 bits, then truncate to 1 bit.
8412 
8413     SDValue Chain = Load->getChain();
8414     SDValue BasePtr = Load->getBasePtr();
8415     MachineMemOperand *MMO = Load->getMemOperand();
8416 
8417     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8418 
8419     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8420                                    BasePtr, RealMemVT, MMO);
8421 
8422     if (!MemVT.isVector()) {
8423       SDValue Ops[] = {
8424         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8425         NewLD.getValue(1)
8426       };
8427 
8428       return DAG.getMergeValues(Ops, DL);
8429     }
8430 
8431     SmallVector<SDValue, 3> Elts;
8432     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8433       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8434                                 DAG.getConstant(I, DL, MVT::i32));
8435 
8436       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8437     }
8438 
8439     SDValue Ops[] = {
8440       DAG.getBuildVector(MemVT, DL, Elts),
8441       NewLD.getValue(1)
8442     };
8443 
8444     return DAG.getMergeValues(Ops, DL);
8445   }
8446 
8447   if (!MemVT.isVector())
8448     return SDValue();
8449 
8450   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8451          "Custom lowering for non-i32 vectors hasn't been implemented.");
8452 
8453   unsigned Alignment = Load->getAlignment();
8454   unsigned AS = Load->getAddressSpace();
8455   if (Subtarget->hasLDSMisalignedBug() &&
8456       AS == AMDGPUAS::FLAT_ADDRESS &&
8457       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8458     return SplitVectorLoad(Op, DAG);
8459   }
8460 
8461   MachineFunction &MF = DAG.getMachineFunction();
8462   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8463   // If there is a possibility that flat instruction access scratch memory
8464   // then we need to use the same legalization rules we use for private.
8465   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8466       !Subtarget->hasMultiDwordFlatScratchAddressing())
8467     AS = MFI->hasFlatScratchInit() ?
8468          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8469 
8470   unsigned NumElements = MemVT.getVectorNumElements();
8471 
8472   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8473       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8474     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8475       if (MemVT.isPow2VectorType())
8476         return SDValue();
8477       return WidenOrSplitVectorLoad(Op, DAG);
8478     }
8479     // Non-uniform loads will be selected to MUBUF instructions, so they
8480     // have the same legalization requirements as global and private
8481     // loads.
8482     //
8483   }
8484 
8485   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8486       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8487       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8488     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8489         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8490         Alignment >= 4 && NumElements < 32) {
8491       if (MemVT.isPow2VectorType())
8492         return SDValue();
8493       return WidenOrSplitVectorLoad(Op, DAG);
8494     }
8495     // Non-uniform loads will be selected to MUBUF instructions, so they
8496     // have the same legalization requirements as global and private
8497     // loads.
8498     //
8499   }
8500   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8501       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8502       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8503       AS == AMDGPUAS::FLAT_ADDRESS) {
8504     if (NumElements > 4)
8505       return SplitVectorLoad(Op, DAG);
8506     // v3 loads not supported on SI.
8507     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8508       return WidenOrSplitVectorLoad(Op, DAG);
8509 
8510     // v3 and v4 loads are supported for private and global memory.
8511     return SDValue();
8512   }
8513   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8514     // Depending on the setting of the private_element_size field in the
8515     // resource descriptor, we can only make private accesses up to a certain
8516     // size.
8517     switch (Subtarget->getMaxPrivateElementSize()) {
8518     case 4: {
8519       SDValue Ops[2];
8520       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8521       return DAG.getMergeValues(Ops, DL);
8522     }
8523     case 8:
8524       if (NumElements > 2)
8525         return SplitVectorLoad(Op, DAG);
8526       return SDValue();
8527     case 16:
8528       // Same as global/flat
8529       if (NumElements > 4)
8530         return SplitVectorLoad(Op, DAG);
8531       // v3 loads not supported on SI.
8532       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8533         return WidenOrSplitVectorLoad(Op, DAG);
8534 
8535       return SDValue();
8536     default:
8537       llvm_unreachable("unsupported private_element_size");
8538     }
8539   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8540     bool Fast = false;
8541     auto Flags = Load->getMemOperand()->getFlags();
8542     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8543                                            Load->getAlign(), Flags, &Fast) &&
8544         Fast)
8545       return SDValue();
8546 
8547     if (MemVT.isVector())
8548       return SplitVectorLoad(Op, DAG);
8549   }
8550 
8551   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8552                                       MemVT, *Load->getMemOperand())) {
8553     SDValue Ops[2];
8554     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8555     return DAG.getMergeValues(Ops, DL);
8556   }
8557 
8558   return SDValue();
8559 }
8560 
8561 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8562   EVT VT = Op.getValueType();
8563   if (VT.getSizeInBits() == 128)
8564     return splitTernaryVectorOp(Op, DAG);
8565 
8566   assert(VT.getSizeInBits() == 64);
8567 
8568   SDLoc DL(Op);
8569   SDValue Cond = Op.getOperand(0);
8570 
8571   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8572   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8573 
8574   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8575   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8576 
8577   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8578   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8579 
8580   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8581 
8582   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8583   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8584 
8585   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8586 
8587   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8588   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8589 }
8590 
8591 // Catch division cases where we can use shortcuts with rcp and rsq
8592 // instructions.
8593 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8594                                               SelectionDAG &DAG) const {
8595   SDLoc SL(Op);
8596   SDValue LHS = Op.getOperand(0);
8597   SDValue RHS = Op.getOperand(1);
8598   EVT VT = Op.getValueType();
8599   const SDNodeFlags Flags = Op->getFlags();
8600 
8601   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8602 
8603   // Without !fpmath accuracy information, we can't do more because we don't
8604   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8605   if (!AllowInaccurateRcp)
8606     return SDValue();
8607 
8608   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8609     if (CLHS->isExactlyValue(1.0)) {
8610       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8611       // the CI documentation has a worst case error of 1 ulp.
8612       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8613       // use it as long as we aren't trying to use denormals.
8614       //
8615       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8616 
8617       // 1.0 / sqrt(x) -> rsq(x)
8618 
8619       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8620       // error seems really high at 2^29 ULP.
8621       if (RHS.getOpcode() == ISD::FSQRT)
8622         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8623 
8624       // 1.0 / x -> rcp(x)
8625       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8626     }
8627 
8628     // Same as for 1.0, but expand the sign out of the constant.
8629     if (CLHS->isExactlyValue(-1.0)) {
8630       // -1.0 / x -> rcp (fneg x)
8631       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8632       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8633     }
8634   }
8635 
8636   // Turn into multiply by the reciprocal.
8637   // x / y -> x * (1.0 / y)
8638   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8639   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8640 }
8641 
8642 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8643                                                 SelectionDAG &DAG) const {
8644   SDLoc SL(Op);
8645   SDValue X = Op.getOperand(0);
8646   SDValue Y = Op.getOperand(1);
8647   EVT VT = Op.getValueType();
8648   const SDNodeFlags Flags = Op->getFlags();
8649 
8650   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8651                             DAG.getTarget().Options.UnsafeFPMath;
8652   if (!AllowInaccurateDiv)
8653     return SDValue();
8654 
8655   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8656   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8657 
8658   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8659   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8660 
8661   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8662   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8663   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8664   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8665   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8666   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8667 }
8668 
8669 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8670                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8671                           SDNodeFlags Flags) {
8672   if (GlueChain->getNumValues() <= 1) {
8673     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8674   }
8675 
8676   assert(GlueChain->getNumValues() == 3);
8677 
8678   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8679   switch (Opcode) {
8680   default: llvm_unreachable("no chain equivalent for opcode");
8681   case ISD::FMUL:
8682     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8683     break;
8684   }
8685 
8686   return DAG.getNode(Opcode, SL, VTList,
8687                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8688                      Flags);
8689 }
8690 
8691 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8692                            EVT VT, SDValue A, SDValue B, SDValue C,
8693                            SDValue GlueChain, SDNodeFlags Flags) {
8694   if (GlueChain->getNumValues() <= 1) {
8695     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8696   }
8697 
8698   assert(GlueChain->getNumValues() == 3);
8699 
8700   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8701   switch (Opcode) {
8702   default: llvm_unreachable("no chain equivalent for opcode");
8703   case ISD::FMA:
8704     Opcode = AMDGPUISD::FMA_W_CHAIN;
8705     break;
8706   }
8707 
8708   return DAG.getNode(Opcode, SL, VTList,
8709                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8710                      Flags);
8711 }
8712 
8713 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8714   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8715     return FastLowered;
8716 
8717   SDLoc SL(Op);
8718   SDValue Src0 = Op.getOperand(0);
8719   SDValue Src1 = Op.getOperand(1);
8720 
8721   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8722   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8723 
8724   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8725   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8726 
8727   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8728   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8729 
8730   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8731 }
8732 
8733 // Faster 2.5 ULP division that does not support denormals.
8734 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8735   SDLoc SL(Op);
8736   SDValue LHS = Op.getOperand(1);
8737   SDValue RHS = Op.getOperand(2);
8738 
8739   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8740 
8741   const APFloat K0Val(BitsToFloat(0x6f800000));
8742   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8743 
8744   const APFloat K1Val(BitsToFloat(0x2f800000));
8745   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8746 
8747   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8748 
8749   EVT SetCCVT =
8750     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8751 
8752   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8753 
8754   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8755 
8756   // TODO: Should this propagate fast-math-flags?
8757   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8758 
8759   // rcp does not support denormals.
8760   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8761 
8762   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8763 
8764   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8765 }
8766 
8767 // Returns immediate value for setting the F32 denorm mode when using the
8768 // S_DENORM_MODE instruction.
8769 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8770                                     const SDLoc &SL, const GCNSubtarget *ST) {
8771   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8772   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8773                                 ? FP_DENORM_FLUSH_NONE
8774                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8775 
8776   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8777   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8778 }
8779 
8780 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8781   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8782     return FastLowered;
8783 
8784   // The selection matcher assumes anything with a chain selecting to a
8785   // mayRaiseFPException machine instruction. Since we're introducing a chain
8786   // here, we need to explicitly report nofpexcept for the regular fdiv
8787   // lowering.
8788   SDNodeFlags Flags = Op->getFlags();
8789   Flags.setNoFPExcept(true);
8790 
8791   SDLoc SL(Op);
8792   SDValue LHS = Op.getOperand(0);
8793   SDValue RHS = Op.getOperand(1);
8794 
8795   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8796 
8797   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8798 
8799   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8800                                           {RHS, RHS, LHS}, Flags);
8801   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8802                                         {LHS, RHS, LHS}, Flags);
8803 
8804   // Denominator is scaled to not be denormal, so using rcp is ok.
8805   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8806                                   DenominatorScaled, Flags);
8807   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8808                                      DenominatorScaled, Flags);
8809 
8810   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8811                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8812                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8813   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8814 
8815   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8816 
8817   if (!HasFP32Denormals) {
8818     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8819     // lowering. The chain dependence is insufficient, and we need glue. We do
8820     // not need the glue variants in a strictfp function.
8821 
8822     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8823 
8824     SDNode *EnableDenorm;
8825     if (Subtarget->hasDenormModeInst()) {
8826       const SDValue EnableDenormValue =
8827           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8828 
8829       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8830                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8831     } else {
8832       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8833                                                         SL, MVT::i32);
8834       EnableDenorm =
8835           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8836                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8837     }
8838 
8839     SDValue Ops[3] = {
8840       NegDivScale0,
8841       SDValue(EnableDenorm, 0),
8842       SDValue(EnableDenorm, 1)
8843     };
8844 
8845     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8846   }
8847 
8848   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8849                              ApproxRcp, One, NegDivScale0, Flags);
8850 
8851   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8852                              ApproxRcp, Fma0, Flags);
8853 
8854   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8855                            Fma1, Fma1, Flags);
8856 
8857   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8858                              NumeratorScaled, Mul, Flags);
8859 
8860   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8861                              Fma2, Fma1, Mul, Fma2, Flags);
8862 
8863   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8864                              NumeratorScaled, Fma3, Flags);
8865 
8866   if (!HasFP32Denormals) {
8867     SDNode *DisableDenorm;
8868     if (Subtarget->hasDenormModeInst()) {
8869       const SDValue DisableDenormValue =
8870           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8871 
8872       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8873                                   Fma4.getValue(1), DisableDenormValue,
8874                                   Fma4.getValue(2)).getNode();
8875     } else {
8876       const SDValue DisableDenormValue =
8877           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8878 
8879       DisableDenorm = DAG.getMachineNode(
8880           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8881           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8882     }
8883 
8884     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8885                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8886     DAG.setRoot(OutputChain);
8887   }
8888 
8889   SDValue Scale = NumeratorScaled.getValue(1);
8890   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8891                              {Fma4, Fma1, Fma3, Scale}, Flags);
8892 
8893   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8894 }
8895 
8896 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8897   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8898     return FastLowered;
8899 
8900   SDLoc SL(Op);
8901   SDValue X = Op.getOperand(0);
8902   SDValue Y = Op.getOperand(1);
8903 
8904   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8905 
8906   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8907 
8908   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8909 
8910   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8911 
8912   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8913 
8914   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8915 
8916   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8917 
8918   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8919 
8920   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8921 
8922   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8923   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8924 
8925   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8926                              NegDivScale0, Mul, DivScale1);
8927 
8928   SDValue Scale;
8929 
8930   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8931     // Workaround a hardware bug on SI where the condition output from div_scale
8932     // is not usable.
8933 
8934     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8935 
8936     // Figure out if the scale to use for div_fmas.
8937     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8938     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8939     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8940     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8941 
8942     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8943     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8944 
8945     SDValue Scale0Hi
8946       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8947     SDValue Scale1Hi
8948       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8949 
8950     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8951     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8952     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8953   } else {
8954     Scale = DivScale1.getValue(1);
8955   }
8956 
8957   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8958                              Fma4, Fma3, Mul, Scale);
8959 
8960   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8961 }
8962 
8963 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8964   EVT VT = Op.getValueType();
8965 
8966   if (VT == MVT::f32)
8967     return LowerFDIV32(Op, DAG);
8968 
8969   if (VT == MVT::f64)
8970     return LowerFDIV64(Op, DAG);
8971 
8972   if (VT == MVT::f16)
8973     return LowerFDIV16(Op, DAG);
8974 
8975   llvm_unreachable("Unexpected type for fdiv");
8976 }
8977 
8978 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8979   SDLoc DL(Op);
8980   StoreSDNode *Store = cast<StoreSDNode>(Op);
8981   EVT VT = Store->getMemoryVT();
8982 
8983   if (VT == MVT::i1) {
8984     return DAG.getTruncStore(Store->getChain(), DL,
8985        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8986        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8987   }
8988 
8989   assert(VT.isVector() &&
8990          Store->getValue().getValueType().getScalarType() == MVT::i32);
8991 
8992   unsigned AS = Store->getAddressSpace();
8993   if (Subtarget->hasLDSMisalignedBug() &&
8994       AS == AMDGPUAS::FLAT_ADDRESS &&
8995       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8996     return SplitVectorStore(Op, DAG);
8997   }
8998 
8999   MachineFunction &MF = DAG.getMachineFunction();
9000   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9001   // If there is a possibility that flat instruction access scratch memory
9002   // then we need to use the same legalization rules we use for private.
9003   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9004       !Subtarget->hasMultiDwordFlatScratchAddressing())
9005     AS = MFI->hasFlatScratchInit() ?
9006          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9007 
9008   unsigned NumElements = VT.getVectorNumElements();
9009   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9010       AS == AMDGPUAS::FLAT_ADDRESS) {
9011     if (NumElements > 4)
9012       return SplitVectorStore(Op, DAG);
9013     // v3 stores not supported on SI.
9014     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9015       return SplitVectorStore(Op, DAG);
9016 
9017     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9018                                         VT, *Store->getMemOperand()))
9019       return expandUnalignedStore(Store, DAG);
9020 
9021     return SDValue();
9022   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9023     switch (Subtarget->getMaxPrivateElementSize()) {
9024     case 4:
9025       return scalarizeVectorStore(Store, DAG);
9026     case 8:
9027       if (NumElements > 2)
9028         return SplitVectorStore(Op, DAG);
9029       return SDValue();
9030     case 16:
9031       if (NumElements > 4 ||
9032           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9033         return SplitVectorStore(Op, DAG);
9034       return SDValue();
9035     default:
9036       llvm_unreachable("unsupported private_element_size");
9037     }
9038   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9039     bool Fast = false;
9040     auto Flags = Store->getMemOperand()->getFlags();
9041     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9042                                            Store->getAlign(), Flags, &Fast) &&
9043         Fast)
9044       return SDValue();
9045 
9046     if (VT.isVector())
9047       return SplitVectorStore(Op, DAG);
9048 
9049     return expandUnalignedStore(Store, DAG);
9050   } else {
9051     llvm_unreachable("unhandled address space");
9052   }
9053 }
9054 
9055 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9056   SDLoc DL(Op);
9057   EVT VT = Op.getValueType();
9058   SDValue Arg = Op.getOperand(0);
9059   SDValue TrigVal;
9060 
9061   // Propagate fast-math flags so that the multiply we introduce can be folded
9062   // if Arg is already the result of a multiply by constant.
9063   auto Flags = Op->getFlags();
9064 
9065   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9066 
9067   if (Subtarget->hasTrigReducedRange()) {
9068     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9069     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9070   } else {
9071     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9072   }
9073 
9074   switch (Op.getOpcode()) {
9075   case ISD::FCOS:
9076     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9077   case ISD::FSIN:
9078     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9079   default:
9080     llvm_unreachable("Wrong trig opcode");
9081   }
9082 }
9083 
9084 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9085   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9086   assert(AtomicNode->isCompareAndSwap());
9087   unsigned AS = AtomicNode->getAddressSpace();
9088 
9089   // No custom lowering required for local address space
9090   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9091     return Op;
9092 
9093   // Non-local address space requires custom lowering for atomic compare
9094   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9095   SDLoc DL(Op);
9096   SDValue ChainIn = Op.getOperand(0);
9097   SDValue Addr = Op.getOperand(1);
9098   SDValue Old = Op.getOperand(2);
9099   SDValue New = Op.getOperand(3);
9100   EVT VT = Op.getValueType();
9101   MVT SimpleVT = VT.getSimpleVT();
9102   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9103 
9104   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9105   SDValue Ops[] = { ChainIn, Addr, NewOld };
9106 
9107   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9108                                  Ops, VT, AtomicNode->getMemOperand());
9109 }
9110 
9111 //===----------------------------------------------------------------------===//
9112 // Custom DAG optimizations
9113 //===----------------------------------------------------------------------===//
9114 
9115 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9116                                                      DAGCombinerInfo &DCI) const {
9117   EVT VT = N->getValueType(0);
9118   EVT ScalarVT = VT.getScalarType();
9119   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9120     return SDValue();
9121 
9122   SelectionDAG &DAG = DCI.DAG;
9123   SDLoc DL(N);
9124 
9125   SDValue Src = N->getOperand(0);
9126   EVT SrcVT = Src.getValueType();
9127 
9128   // TODO: We could try to match extracting the higher bytes, which would be
9129   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9130   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9131   // about in practice.
9132   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9133     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9134       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9135       DCI.AddToWorklist(Cvt.getNode());
9136 
9137       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9138       if (ScalarVT != MVT::f32) {
9139         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9140                           DAG.getTargetConstant(0, DL, MVT::i32));
9141       }
9142       return Cvt;
9143     }
9144   }
9145 
9146   return SDValue();
9147 }
9148 
9149 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9150 
9151 // This is a variant of
9152 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9153 //
9154 // The normal DAG combiner will do this, but only if the add has one use since
9155 // that would increase the number of instructions.
9156 //
9157 // This prevents us from seeing a constant offset that can be folded into a
9158 // memory instruction's addressing mode. If we know the resulting add offset of
9159 // a pointer can be folded into an addressing offset, we can replace the pointer
9160 // operand with the add of new constant offset. This eliminates one of the uses,
9161 // and may allow the remaining use to also be simplified.
9162 //
9163 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9164                                                unsigned AddrSpace,
9165                                                EVT MemVT,
9166                                                DAGCombinerInfo &DCI) const {
9167   SDValue N0 = N->getOperand(0);
9168   SDValue N1 = N->getOperand(1);
9169 
9170   // We only do this to handle cases where it's profitable when there are
9171   // multiple uses of the add, so defer to the standard combine.
9172   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9173       N0->hasOneUse())
9174     return SDValue();
9175 
9176   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9177   if (!CN1)
9178     return SDValue();
9179 
9180   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9181   if (!CAdd)
9182     return SDValue();
9183 
9184   // If the resulting offset is too large, we can't fold it into the addressing
9185   // mode offset.
9186   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9187   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9188 
9189   AddrMode AM;
9190   AM.HasBaseReg = true;
9191   AM.BaseOffs = Offset.getSExtValue();
9192   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9193     return SDValue();
9194 
9195   SelectionDAG &DAG = DCI.DAG;
9196   SDLoc SL(N);
9197   EVT VT = N->getValueType(0);
9198 
9199   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9200   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9201 
9202   SDNodeFlags Flags;
9203   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9204                           (N0.getOpcode() == ISD::OR ||
9205                            N0->getFlags().hasNoUnsignedWrap()));
9206 
9207   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9208 }
9209 
9210 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9211 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9212 /// specific intrinsic, but they all place the pointer operand first.
9213 static unsigned getBasePtrIndex(const MemSDNode *N) {
9214   switch (N->getOpcode()) {
9215   case ISD::STORE:
9216   case ISD::INTRINSIC_W_CHAIN:
9217   case ISD::INTRINSIC_VOID:
9218     return 2;
9219   default:
9220     return 1;
9221   }
9222 }
9223 
9224 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9225                                                   DAGCombinerInfo &DCI) const {
9226   SelectionDAG &DAG = DCI.DAG;
9227   SDLoc SL(N);
9228 
9229   unsigned PtrIdx = getBasePtrIndex(N);
9230   SDValue Ptr = N->getOperand(PtrIdx);
9231 
9232   // TODO: We could also do this for multiplies.
9233   if (Ptr.getOpcode() == ISD::SHL) {
9234     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9235                                           N->getMemoryVT(), DCI);
9236     if (NewPtr) {
9237       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9238 
9239       NewOps[PtrIdx] = NewPtr;
9240       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9241     }
9242   }
9243 
9244   return SDValue();
9245 }
9246 
9247 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9248   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9249          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9250          (Opc == ISD::XOR && Val == 0);
9251 }
9252 
9253 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9254 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9255 // integer combine opportunities since most 64-bit operations are decomposed
9256 // this way.  TODO: We won't want this for SALU especially if it is an inline
9257 // immediate.
9258 SDValue SITargetLowering::splitBinaryBitConstantOp(
9259   DAGCombinerInfo &DCI,
9260   const SDLoc &SL,
9261   unsigned Opc, SDValue LHS,
9262   const ConstantSDNode *CRHS) const {
9263   uint64_t Val = CRHS->getZExtValue();
9264   uint32_t ValLo = Lo_32(Val);
9265   uint32_t ValHi = Hi_32(Val);
9266   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9267 
9268     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9269          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9270         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9271     // If we need to materialize a 64-bit immediate, it will be split up later
9272     // anyway. Avoid creating the harder to understand 64-bit immediate
9273     // materialization.
9274     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9275   }
9276 
9277   return SDValue();
9278 }
9279 
9280 // Returns true if argument is a boolean value which is not serialized into
9281 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9282 static bool isBoolSGPR(SDValue V) {
9283   if (V.getValueType() != MVT::i1)
9284     return false;
9285   switch (V.getOpcode()) {
9286   default:
9287     break;
9288   case ISD::SETCC:
9289   case AMDGPUISD::FP_CLASS:
9290     return true;
9291   case ISD::AND:
9292   case ISD::OR:
9293   case ISD::XOR:
9294     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9295   }
9296   return false;
9297 }
9298 
9299 // If a constant has all zeroes or all ones within each byte return it.
9300 // Otherwise return 0.
9301 static uint32_t getConstantPermuteMask(uint32_t C) {
9302   // 0xff for any zero byte in the mask
9303   uint32_t ZeroByteMask = 0;
9304   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9305   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9306   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9307   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9308   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9309   if ((NonZeroByteMask & C) != NonZeroByteMask)
9310     return 0; // Partial bytes selected.
9311   return C;
9312 }
9313 
9314 // Check if a node selects whole bytes from its operand 0 starting at a byte
9315 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9316 // or -1 if not succeeded.
9317 // Note byte select encoding:
9318 // value 0-3 selects corresponding source byte;
9319 // value 0xc selects zero;
9320 // value 0xff selects 0xff.
9321 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9322   assert(V.getValueSizeInBits() == 32);
9323 
9324   if (V.getNumOperands() != 2)
9325     return ~0;
9326 
9327   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9328   if (!N1)
9329     return ~0;
9330 
9331   uint32_t C = N1->getZExtValue();
9332 
9333   switch (V.getOpcode()) {
9334   default:
9335     break;
9336   case ISD::AND:
9337     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9338       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9339     }
9340     break;
9341 
9342   case ISD::OR:
9343     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9344       return (0x03020100 & ~ConstMask) | ConstMask;
9345     }
9346     break;
9347 
9348   case ISD::SHL:
9349     if (C % 8)
9350       return ~0;
9351 
9352     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9353 
9354   case ISD::SRL:
9355     if (C % 8)
9356       return ~0;
9357 
9358     return uint32_t(0x0c0c0c0c03020100ull >> C);
9359   }
9360 
9361   return ~0;
9362 }
9363 
9364 SDValue SITargetLowering::performAndCombine(SDNode *N,
9365                                             DAGCombinerInfo &DCI) const {
9366   if (DCI.isBeforeLegalize())
9367     return SDValue();
9368 
9369   SelectionDAG &DAG = DCI.DAG;
9370   EVT VT = N->getValueType(0);
9371   SDValue LHS = N->getOperand(0);
9372   SDValue RHS = N->getOperand(1);
9373 
9374 
9375   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9376   if (VT == MVT::i64 && CRHS) {
9377     if (SDValue Split
9378         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9379       return Split;
9380   }
9381 
9382   if (CRHS && VT == MVT::i32) {
9383     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9384     // nb = number of trailing zeroes in mask
9385     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9386     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9387     uint64_t Mask = CRHS->getZExtValue();
9388     unsigned Bits = countPopulation(Mask);
9389     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9390         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9391       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9392         unsigned Shift = CShift->getZExtValue();
9393         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9394         unsigned Offset = NB + Shift;
9395         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9396           SDLoc SL(N);
9397           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9398                                     LHS->getOperand(0),
9399                                     DAG.getConstant(Offset, SL, MVT::i32),
9400                                     DAG.getConstant(Bits, SL, MVT::i32));
9401           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9402           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9403                                     DAG.getValueType(NarrowVT));
9404           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9405                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9406           return Shl;
9407         }
9408       }
9409     }
9410 
9411     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9412     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9413         isa<ConstantSDNode>(LHS.getOperand(2))) {
9414       uint32_t Sel = getConstantPermuteMask(Mask);
9415       if (!Sel)
9416         return SDValue();
9417 
9418       // Select 0xc for all zero bytes
9419       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9420       SDLoc DL(N);
9421       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9422                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9423     }
9424   }
9425 
9426   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9427   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9428   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9429     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9430     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9431 
9432     SDValue X = LHS.getOperand(0);
9433     SDValue Y = RHS.getOperand(0);
9434     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9435       return SDValue();
9436 
9437     if (LCC == ISD::SETO) {
9438       if (X != LHS.getOperand(1))
9439         return SDValue();
9440 
9441       if (RCC == ISD::SETUNE) {
9442         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9443         if (!C1 || !C1->isInfinity() || C1->isNegative())
9444           return SDValue();
9445 
9446         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9447                               SIInstrFlags::N_SUBNORMAL |
9448                               SIInstrFlags::N_ZERO |
9449                               SIInstrFlags::P_ZERO |
9450                               SIInstrFlags::P_SUBNORMAL |
9451                               SIInstrFlags::P_NORMAL;
9452 
9453         static_assert(((~(SIInstrFlags::S_NAN |
9454                           SIInstrFlags::Q_NAN |
9455                           SIInstrFlags::N_INFINITY |
9456                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9457                       "mask not equal");
9458 
9459         SDLoc DL(N);
9460         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9461                            X, DAG.getConstant(Mask, DL, MVT::i32));
9462       }
9463     }
9464   }
9465 
9466   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9467     std::swap(LHS, RHS);
9468 
9469   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9470       RHS.hasOneUse()) {
9471     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9472     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9473     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9474     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9475     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9476         (RHS.getOperand(0) == LHS.getOperand(0) &&
9477          LHS.getOperand(0) == LHS.getOperand(1))) {
9478       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9479       unsigned NewMask = LCC == ISD::SETO ?
9480         Mask->getZExtValue() & ~OrdMask :
9481         Mask->getZExtValue() & OrdMask;
9482 
9483       SDLoc DL(N);
9484       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9485                          DAG.getConstant(NewMask, DL, MVT::i32));
9486     }
9487   }
9488 
9489   if (VT == MVT::i32 &&
9490       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9491     // and x, (sext cc from i1) => select cc, x, 0
9492     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9493       std::swap(LHS, RHS);
9494     if (isBoolSGPR(RHS.getOperand(0)))
9495       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9496                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9497   }
9498 
9499   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9500   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9501   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9502       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9503     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9504     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9505     if (LHSMask != ~0u && RHSMask != ~0u) {
9506       // Canonicalize the expression in an attempt to have fewer unique masks
9507       // and therefore fewer registers used to hold the masks.
9508       if (LHSMask > RHSMask) {
9509         std::swap(LHSMask, RHSMask);
9510         std::swap(LHS, RHS);
9511       }
9512 
9513       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9514       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9515       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9516       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9517 
9518       // Check of we need to combine values from two sources within a byte.
9519       if (!(LHSUsedLanes & RHSUsedLanes) &&
9520           // If we select high and lower word keep it for SDWA.
9521           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9522           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9523         // Each byte in each mask is either selector mask 0-3, or has higher
9524         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9525         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9526         // mask which is not 0xff wins. By anding both masks we have a correct
9527         // result except that 0x0c shall be corrected to give 0x0c only.
9528         uint32_t Mask = LHSMask & RHSMask;
9529         for (unsigned I = 0; I < 32; I += 8) {
9530           uint32_t ByteSel = 0xff << I;
9531           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9532             Mask &= (0x0c << I) & 0xffffffff;
9533         }
9534 
9535         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9536         // or 0x0c.
9537         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9538         SDLoc DL(N);
9539 
9540         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9541                            LHS.getOperand(0), RHS.getOperand(0),
9542                            DAG.getConstant(Sel, DL, MVT::i32));
9543       }
9544     }
9545   }
9546 
9547   return SDValue();
9548 }
9549 
9550 SDValue SITargetLowering::performOrCombine(SDNode *N,
9551                                            DAGCombinerInfo &DCI) const {
9552   SelectionDAG &DAG = DCI.DAG;
9553   SDValue LHS = N->getOperand(0);
9554   SDValue RHS = N->getOperand(1);
9555 
9556   EVT VT = N->getValueType(0);
9557   if (VT == MVT::i1) {
9558     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9559     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9560         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9561       SDValue Src = LHS.getOperand(0);
9562       if (Src != RHS.getOperand(0))
9563         return SDValue();
9564 
9565       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9566       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9567       if (!CLHS || !CRHS)
9568         return SDValue();
9569 
9570       // Only 10 bits are used.
9571       static const uint32_t MaxMask = 0x3ff;
9572 
9573       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9574       SDLoc DL(N);
9575       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9576                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9577     }
9578 
9579     return SDValue();
9580   }
9581 
9582   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9583   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9584       LHS.getOpcode() == AMDGPUISD::PERM &&
9585       isa<ConstantSDNode>(LHS.getOperand(2))) {
9586     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9587     if (!Sel)
9588       return SDValue();
9589 
9590     Sel |= LHS.getConstantOperandVal(2);
9591     SDLoc DL(N);
9592     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9593                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9594   }
9595 
9596   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9597   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9598   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9599       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9600     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9601     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9602     if (LHSMask != ~0u && RHSMask != ~0u) {
9603       // Canonicalize the expression in an attempt to have fewer unique masks
9604       // and therefore fewer registers used to hold the masks.
9605       if (LHSMask > RHSMask) {
9606         std::swap(LHSMask, RHSMask);
9607         std::swap(LHS, RHS);
9608       }
9609 
9610       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9611       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9612       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9613       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9614 
9615       // Check of we need to combine values from two sources within a byte.
9616       if (!(LHSUsedLanes & RHSUsedLanes) &&
9617           // If we select high and lower word keep it for SDWA.
9618           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9619           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9620         // Kill zero bytes selected by other mask. Zero value is 0xc.
9621         LHSMask &= ~RHSUsedLanes;
9622         RHSMask &= ~LHSUsedLanes;
9623         // Add 4 to each active LHS lane
9624         LHSMask |= LHSUsedLanes & 0x04040404;
9625         // Combine masks
9626         uint32_t Sel = LHSMask | RHSMask;
9627         SDLoc DL(N);
9628 
9629         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9630                            LHS.getOperand(0), RHS.getOperand(0),
9631                            DAG.getConstant(Sel, DL, MVT::i32));
9632       }
9633     }
9634   }
9635 
9636   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9637     return SDValue();
9638 
9639   // TODO: This could be a generic combine with a predicate for extracting the
9640   // high half of an integer being free.
9641 
9642   // (or i64:x, (zero_extend i32:y)) ->
9643   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9644   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9645       RHS.getOpcode() != ISD::ZERO_EXTEND)
9646     std::swap(LHS, RHS);
9647 
9648   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9649     SDValue ExtSrc = RHS.getOperand(0);
9650     EVT SrcVT = ExtSrc.getValueType();
9651     if (SrcVT == MVT::i32) {
9652       SDLoc SL(N);
9653       SDValue LowLHS, HiBits;
9654       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9655       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9656 
9657       DCI.AddToWorklist(LowOr.getNode());
9658       DCI.AddToWorklist(HiBits.getNode());
9659 
9660       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9661                                 LowOr, HiBits);
9662       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9663     }
9664   }
9665 
9666   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9667   if (CRHS) {
9668     if (SDValue Split
9669           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9670                                      N->getOperand(0), CRHS))
9671       return Split;
9672   }
9673 
9674   return SDValue();
9675 }
9676 
9677 SDValue SITargetLowering::performXorCombine(SDNode *N,
9678                                             DAGCombinerInfo &DCI) const {
9679   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9680     return RV;
9681 
9682   EVT VT = N->getValueType(0);
9683   if (VT != MVT::i64)
9684     return SDValue();
9685 
9686   SDValue LHS = N->getOperand(0);
9687   SDValue RHS = N->getOperand(1);
9688 
9689   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9690   if (CRHS) {
9691     if (SDValue Split
9692           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9693       return Split;
9694   }
9695 
9696   return SDValue();
9697 }
9698 
9699 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9700                                                    DAGCombinerInfo &DCI) const {
9701   if (!Subtarget->has16BitInsts() ||
9702       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9703     return SDValue();
9704 
9705   EVT VT = N->getValueType(0);
9706   if (VT != MVT::i32)
9707     return SDValue();
9708 
9709   SDValue Src = N->getOperand(0);
9710   if (Src.getValueType() != MVT::i16)
9711     return SDValue();
9712 
9713   return SDValue();
9714 }
9715 
9716 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9717                                                         DAGCombinerInfo &DCI)
9718                                                         const {
9719   SDValue Src = N->getOperand(0);
9720   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9721 
9722   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9723       VTSign->getVT() == MVT::i8) ||
9724       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9725       VTSign->getVT() == MVT::i16)) &&
9726       Src.hasOneUse()) {
9727     auto *M = cast<MemSDNode>(Src);
9728     SDValue Ops[] = {
9729       Src.getOperand(0), // Chain
9730       Src.getOperand(1), // rsrc
9731       Src.getOperand(2), // vindex
9732       Src.getOperand(3), // voffset
9733       Src.getOperand(4), // soffset
9734       Src.getOperand(5), // offset
9735       Src.getOperand(6),
9736       Src.getOperand(7)
9737     };
9738     // replace with BUFFER_LOAD_BYTE/SHORT
9739     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9740                                          Src.getOperand(0).getValueType());
9741     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9742                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9743     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9744                                                           ResList,
9745                                                           Ops, M->getMemoryVT(),
9746                                                           M->getMemOperand());
9747     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9748                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9749   }
9750   return SDValue();
9751 }
9752 
9753 SDValue SITargetLowering::performClassCombine(SDNode *N,
9754                                               DAGCombinerInfo &DCI) const {
9755   SelectionDAG &DAG = DCI.DAG;
9756   SDValue Mask = N->getOperand(1);
9757 
9758   // fp_class x, 0 -> false
9759   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9760     if (CMask->isZero())
9761       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9762   }
9763 
9764   if (N->getOperand(0).isUndef())
9765     return DAG.getUNDEF(MVT::i1);
9766 
9767   return SDValue();
9768 }
9769 
9770 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9771                                             DAGCombinerInfo &DCI) const {
9772   EVT VT = N->getValueType(0);
9773   SDValue N0 = N->getOperand(0);
9774 
9775   if (N0.isUndef())
9776     return N0;
9777 
9778   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9779                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9780     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9781                            N->getFlags());
9782   }
9783 
9784   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9785     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9786                            N0.getOperand(0), N->getFlags());
9787   }
9788 
9789   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9790 }
9791 
9792 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9793                                        unsigned MaxDepth) const {
9794   unsigned Opcode = Op.getOpcode();
9795   if (Opcode == ISD::FCANONICALIZE)
9796     return true;
9797 
9798   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9799     auto F = CFP->getValueAPF();
9800     if (F.isNaN() && F.isSignaling())
9801       return false;
9802     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9803   }
9804 
9805   // If source is a result of another standard FP operation it is already in
9806   // canonical form.
9807   if (MaxDepth == 0)
9808     return false;
9809 
9810   switch (Opcode) {
9811   // These will flush denorms if required.
9812   case ISD::FADD:
9813   case ISD::FSUB:
9814   case ISD::FMUL:
9815   case ISD::FCEIL:
9816   case ISD::FFLOOR:
9817   case ISD::FMA:
9818   case ISD::FMAD:
9819   case ISD::FSQRT:
9820   case ISD::FDIV:
9821   case ISD::FREM:
9822   case ISD::FP_ROUND:
9823   case ISD::FP_EXTEND:
9824   case AMDGPUISD::FMUL_LEGACY:
9825   case AMDGPUISD::FMAD_FTZ:
9826   case AMDGPUISD::RCP:
9827   case AMDGPUISD::RSQ:
9828   case AMDGPUISD::RSQ_CLAMP:
9829   case AMDGPUISD::RCP_LEGACY:
9830   case AMDGPUISD::RCP_IFLAG:
9831   case AMDGPUISD::DIV_SCALE:
9832   case AMDGPUISD::DIV_FMAS:
9833   case AMDGPUISD::DIV_FIXUP:
9834   case AMDGPUISD::FRACT:
9835   case AMDGPUISD::LDEXP:
9836   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9837   case AMDGPUISD::CVT_F32_UBYTE0:
9838   case AMDGPUISD::CVT_F32_UBYTE1:
9839   case AMDGPUISD::CVT_F32_UBYTE2:
9840   case AMDGPUISD::CVT_F32_UBYTE3:
9841     return true;
9842 
9843   // It can/will be lowered or combined as a bit operation.
9844   // Need to check their input recursively to handle.
9845   case ISD::FNEG:
9846   case ISD::FABS:
9847   case ISD::FCOPYSIGN:
9848     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9849 
9850   case ISD::FSIN:
9851   case ISD::FCOS:
9852   case ISD::FSINCOS:
9853     return Op.getValueType().getScalarType() != MVT::f16;
9854 
9855   case ISD::FMINNUM:
9856   case ISD::FMAXNUM:
9857   case ISD::FMINNUM_IEEE:
9858   case ISD::FMAXNUM_IEEE:
9859   case AMDGPUISD::CLAMP:
9860   case AMDGPUISD::FMED3:
9861   case AMDGPUISD::FMAX3:
9862   case AMDGPUISD::FMIN3: {
9863     // FIXME: Shouldn't treat the generic operations different based these.
9864     // However, we aren't really required to flush the result from
9865     // minnum/maxnum..
9866 
9867     // snans will be quieted, so we only need to worry about denormals.
9868     if (Subtarget->supportsMinMaxDenormModes() ||
9869         denormalsEnabledForType(DAG, Op.getValueType()))
9870       return true;
9871 
9872     // Flushing may be required.
9873     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9874     // targets need to check their input recursively.
9875 
9876     // FIXME: Does this apply with clamp? It's implemented with max.
9877     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9878       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9879         return false;
9880     }
9881 
9882     return true;
9883   }
9884   case ISD::SELECT: {
9885     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9886            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9887   }
9888   case ISD::BUILD_VECTOR: {
9889     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9890       SDValue SrcOp = Op.getOperand(i);
9891       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9892         return false;
9893     }
9894 
9895     return true;
9896   }
9897   case ISD::EXTRACT_VECTOR_ELT:
9898   case ISD::EXTRACT_SUBVECTOR: {
9899     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9900   }
9901   case ISD::INSERT_VECTOR_ELT: {
9902     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9903            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9904   }
9905   case ISD::UNDEF:
9906     // Could be anything.
9907     return false;
9908 
9909   case ISD::BITCAST:
9910     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9911   case ISD::TRUNCATE: {
9912     // Hack round the mess we make when legalizing extract_vector_elt
9913     if (Op.getValueType() == MVT::i16) {
9914       SDValue TruncSrc = Op.getOperand(0);
9915       if (TruncSrc.getValueType() == MVT::i32 &&
9916           TruncSrc.getOpcode() == ISD::BITCAST &&
9917           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9918         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9919       }
9920     }
9921     return false;
9922   }
9923   case ISD::INTRINSIC_WO_CHAIN: {
9924     unsigned IntrinsicID
9925       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9926     // TODO: Handle more intrinsics
9927     switch (IntrinsicID) {
9928     case Intrinsic::amdgcn_cvt_pkrtz:
9929     case Intrinsic::amdgcn_cubeid:
9930     case Intrinsic::amdgcn_frexp_mant:
9931     case Intrinsic::amdgcn_fdot2:
9932     case Intrinsic::amdgcn_rcp:
9933     case Intrinsic::amdgcn_rsq:
9934     case Intrinsic::amdgcn_rsq_clamp:
9935     case Intrinsic::amdgcn_rcp_legacy:
9936     case Intrinsic::amdgcn_rsq_legacy:
9937     case Intrinsic::amdgcn_trig_preop:
9938       return true;
9939     default:
9940       break;
9941     }
9942 
9943     LLVM_FALLTHROUGH;
9944   }
9945   default:
9946     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9947            DAG.isKnownNeverSNaN(Op);
9948   }
9949 
9950   llvm_unreachable("invalid operation");
9951 }
9952 
9953 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9954                                        unsigned MaxDepth) const {
9955   MachineRegisterInfo &MRI = MF.getRegInfo();
9956   MachineInstr *MI = MRI.getVRegDef(Reg);
9957   unsigned Opcode = MI->getOpcode();
9958 
9959   if (Opcode == AMDGPU::G_FCANONICALIZE)
9960     return true;
9961 
9962   Optional<FPValueAndVReg> FCR;
9963   // Constant splat (can be padded with undef) or scalar constant.
9964   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9965     if (FCR->Value.isSignaling())
9966       return false;
9967     return !FCR->Value.isDenormal() ||
9968            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9969   }
9970 
9971   if (MaxDepth == 0)
9972     return false;
9973 
9974   switch (Opcode) {
9975   case AMDGPU::G_FMINNUM_IEEE:
9976   case AMDGPU::G_FMAXNUM_IEEE: {
9977     if (Subtarget->supportsMinMaxDenormModes() ||
9978         denormalsEnabledForType(MRI.getType(Reg), MF))
9979       return true;
9980     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9981       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9982         return false;
9983     return true;
9984   }
9985   default:
9986     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9987            isKnownNeverSNaN(Reg, MRI);
9988   }
9989 
9990   llvm_unreachable("invalid operation");
9991 }
9992 
9993 // Constant fold canonicalize.
9994 SDValue SITargetLowering::getCanonicalConstantFP(
9995   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9996   // Flush denormals to 0 if not enabled.
9997   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9998     return DAG.getConstantFP(0.0, SL, VT);
9999 
10000   if (C.isNaN()) {
10001     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10002     if (C.isSignaling()) {
10003       // Quiet a signaling NaN.
10004       // FIXME: Is this supposed to preserve payload bits?
10005       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10006     }
10007 
10008     // Make sure it is the canonical NaN bitpattern.
10009     //
10010     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10011     // immediate?
10012     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10013       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10014   }
10015 
10016   // Already canonical.
10017   return DAG.getConstantFP(C, SL, VT);
10018 }
10019 
10020 static bool vectorEltWillFoldAway(SDValue Op) {
10021   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10022 }
10023 
10024 SDValue SITargetLowering::performFCanonicalizeCombine(
10025   SDNode *N,
10026   DAGCombinerInfo &DCI) const {
10027   SelectionDAG &DAG = DCI.DAG;
10028   SDValue N0 = N->getOperand(0);
10029   EVT VT = N->getValueType(0);
10030 
10031   // fcanonicalize undef -> qnan
10032   if (N0.isUndef()) {
10033     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10034     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10035   }
10036 
10037   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10038     EVT VT = N->getValueType(0);
10039     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10040   }
10041 
10042   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10043   //                                                   (fcanonicalize k)
10044   //
10045   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10046 
10047   // TODO: This could be better with wider vectors that will be split to v2f16,
10048   // and to consider uses since there aren't that many packed operations.
10049   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10050       isTypeLegal(MVT::v2f16)) {
10051     SDLoc SL(N);
10052     SDValue NewElts[2];
10053     SDValue Lo = N0.getOperand(0);
10054     SDValue Hi = N0.getOperand(1);
10055     EVT EltVT = Lo.getValueType();
10056 
10057     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10058       for (unsigned I = 0; I != 2; ++I) {
10059         SDValue Op = N0.getOperand(I);
10060         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10061           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10062                                               CFP->getValueAPF());
10063         } else if (Op.isUndef()) {
10064           // Handled below based on what the other operand is.
10065           NewElts[I] = Op;
10066         } else {
10067           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10068         }
10069       }
10070 
10071       // If one half is undef, and one is constant, prefer a splat vector rather
10072       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10073       // cheaper to use and may be free with a packed operation.
10074       if (NewElts[0].isUndef()) {
10075         if (isa<ConstantFPSDNode>(NewElts[1]))
10076           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10077             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10078       }
10079 
10080       if (NewElts[1].isUndef()) {
10081         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10082           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10083       }
10084 
10085       return DAG.getBuildVector(VT, SL, NewElts);
10086     }
10087   }
10088 
10089   unsigned SrcOpc = N0.getOpcode();
10090 
10091   // If it's free to do so, push canonicalizes further up the source, which may
10092   // find a canonical source.
10093   //
10094   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10095   // sNaNs.
10096   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10097     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10098     if (CRHS && N0.hasOneUse()) {
10099       SDLoc SL(N);
10100       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10101                                    N0.getOperand(0));
10102       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10103       DCI.AddToWorklist(Canon0.getNode());
10104 
10105       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10106     }
10107   }
10108 
10109   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10110 }
10111 
10112 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10113   switch (Opc) {
10114   case ISD::FMAXNUM:
10115   case ISD::FMAXNUM_IEEE:
10116     return AMDGPUISD::FMAX3;
10117   case ISD::SMAX:
10118     return AMDGPUISD::SMAX3;
10119   case ISD::UMAX:
10120     return AMDGPUISD::UMAX3;
10121   case ISD::FMINNUM:
10122   case ISD::FMINNUM_IEEE:
10123     return AMDGPUISD::FMIN3;
10124   case ISD::SMIN:
10125     return AMDGPUISD::SMIN3;
10126   case ISD::UMIN:
10127     return AMDGPUISD::UMIN3;
10128   default:
10129     llvm_unreachable("Not a min/max opcode");
10130   }
10131 }
10132 
10133 SDValue SITargetLowering::performIntMed3ImmCombine(
10134   SelectionDAG &DAG, const SDLoc &SL,
10135   SDValue Op0, SDValue Op1, bool Signed) const {
10136   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10137   if (!K1)
10138     return SDValue();
10139 
10140   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10141   if (!K0)
10142     return SDValue();
10143 
10144   if (Signed) {
10145     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10146       return SDValue();
10147   } else {
10148     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10149       return SDValue();
10150   }
10151 
10152   EVT VT = K0->getValueType(0);
10153   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10154   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10155     return DAG.getNode(Med3Opc, SL, VT,
10156                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10157   }
10158 
10159   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10160   if (VT == MVT::i16) {
10161     MVT NVT = MVT::i32;
10162     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10163 
10164     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10165     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10166     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10167 
10168     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10169     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10170   }
10171 
10172   return SDValue();
10173 }
10174 
10175 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10176   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10177     return C;
10178 
10179   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10180     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10181       return C;
10182   }
10183 
10184   return nullptr;
10185 }
10186 
10187 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10188                                                   const SDLoc &SL,
10189                                                   SDValue Op0,
10190                                                   SDValue Op1) const {
10191   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10192   if (!K1)
10193     return SDValue();
10194 
10195   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10196   if (!K0)
10197     return SDValue();
10198 
10199   // Ordered >= (although NaN inputs should have folded away by now).
10200   if (K0->getValueAPF() > K1->getValueAPF())
10201     return SDValue();
10202 
10203   const MachineFunction &MF = DAG.getMachineFunction();
10204   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10205 
10206   // TODO: Check IEEE bit enabled?
10207   EVT VT = Op0.getValueType();
10208   if (Info->getMode().DX10Clamp) {
10209     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10210     // hardware fmed3 behavior converting to a min.
10211     // FIXME: Should this be allowing -0.0?
10212     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10213       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10214   }
10215 
10216   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10217   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10218     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10219     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10220     // then give the other result, which is different from med3 with a NaN
10221     // input.
10222     SDValue Var = Op0.getOperand(0);
10223     if (!DAG.isKnownNeverSNaN(Var))
10224       return SDValue();
10225 
10226     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10227 
10228     if ((!K0->hasOneUse() ||
10229          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10230         (!K1->hasOneUse() ||
10231          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10232       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10233                          Var, SDValue(K0, 0), SDValue(K1, 0));
10234     }
10235   }
10236 
10237   return SDValue();
10238 }
10239 
10240 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10241                                                DAGCombinerInfo &DCI) const {
10242   SelectionDAG &DAG = DCI.DAG;
10243 
10244   EVT VT = N->getValueType(0);
10245   unsigned Opc = N->getOpcode();
10246   SDValue Op0 = N->getOperand(0);
10247   SDValue Op1 = N->getOperand(1);
10248 
10249   // Only do this if the inner op has one use since this will just increases
10250   // register pressure for no benefit.
10251 
10252   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10253       !VT.isVector() &&
10254       (VT == MVT::i32 || VT == MVT::f32 ||
10255        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10256     // max(max(a, b), c) -> max3(a, b, c)
10257     // min(min(a, b), c) -> min3(a, b, c)
10258     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10259       SDLoc DL(N);
10260       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10261                          DL,
10262                          N->getValueType(0),
10263                          Op0.getOperand(0),
10264                          Op0.getOperand(1),
10265                          Op1);
10266     }
10267 
10268     // Try commuted.
10269     // max(a, max(b, c)) -> max3(a, b, c)
10270     // min(a, min(b, c)) -> min3(a, b, c)
10271     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10272       SDLoc DL(N);
10273       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10274                          DL,
10275                          N->getValueType(0),
10276                          Op0,
10277                          Op1.getOperand(0),
10278                          Op1.getOperand(1));
10279     }
10280   }
10281 
10282   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10283   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10284     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10285       return Med3;
10286   }
10287 
10288   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10289     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10290       return Med3;
10291   }
10292 
10293   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10294   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10295        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10296        (Opc == AMDGPUISD::FMIN_LEGACY &&
10297         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10298       (VT == MVT::f32 || VT == MVT::f64 ||
10299        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10300        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10301       Op0.hasOneUse()) {
10302     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10303       return Res;
10304   }
10305 
10306   return SDValue();
10307 }
10308 
10309 static bool isClampZeroToOne(SDValue A, SDValue B) {
10310   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10311     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10312       // FIXME: Should this be allowing -0.0?
10313       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10314              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10315     }
10316   }
10317 
10318   return false;
10319 }
10320 
10321 // FIXME: Should only worry about snans for version with chain.
10322 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10323                                               DAGCombinerInfo &DCI) const {
10324   EVT VT = N->getValueType(0);
10325   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10326   // NaNs. With a NaN input, the order of the operands may change the result.
10327 
10328   SelectionDAG &DAG = DCI.DAG;
10329   SDLoc SL(N);
10330 
10331   SDValue Src0 = N->getOperand(0);
10332   SDValue Src1 = N->getOperand(1);
10333   SDValue Src2 = N->getOperand(2);
10334 
10335   if (isClampZeroToOne(Src0, Src1)) {
10336     // const_a, const_b, x -> clamp is safe in all cases including signaling
10337     // nans.
10338     // FIXME: Should this be allowing -0.0?
10339     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10340   }
10341 
10342   const MachineFunction &MF = DAG.getMachineFunction();
10343   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10344 
10345   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10346   // handling no dx10-clamp?
10347   if (Info->getMode().DX10Clamp) {
10348     // If NaNs is clamped to 0, we are free to reorder the inputs.
10349 
10350     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10351       std::swap(Src0, Src1);
10352 
10353     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10354       std::swap(Src1, Src2);
10355 
10356     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10357       std::swap(Src0, Src1);
10358 
10359     if (isClampZeroToOne(Src1, Src2))
10360       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10361   }
10362 
10363   return SDValue();
10364 }
10365 
10366 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10367                                                  DAGCombinerInfo &DCI) const {
10368   SDValue Src0 = N->getOperand(0);
10369   SDValue Src1 = N->getOperand(1);
10370   if (Src0.isUndef() && Src1.isUndef())
10371     return DCI.DAG.getUNDEF(N->getValueType(0));
10372   return SDValue();
10373 }
10374 
10375 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10376 // expanded into a set of cmp/select instructions.
10377 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10378                                                 unsigned NumElem,
10379                                                 bool IsDivergentIdx) {
10380   if (UseDivergentRegisterIndexing)
10381     return false;
10382 
10383   unsigned VecSize = EltSize * NumElem;
10384 
10385   // Sub-dword vectors of size 2 dword or less have better implementation.
10386   if (VecSize <= 64 && EltSize < 32)
10387     return false;
10388 
10389   // Always expand the rest of sub-dword instructions, otherwise it will be
10390   // lowered via memory.
10391   if (EltSize < 32)
10392     return true;
10393 
10394   // Always do this if var-idx is divergent, otherwise it will become a loop.
10395   if (IsDivergentIdx)
10396     return true;
10397 
10398   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10399   unsigned NumInsts = NumElem /* Number of compares */ +
10400                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10401   return NumInsts <= 16;
10402 }
10403 
10404 static bool shouldExpandVectorDynExt(SDNode *N) {
10405   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10406   if (isa<ConstantSDNode>(Idx))
10407     return false;
10408 
10409   SDValue Vec = N->getOperand(0);
10410   EVT VecVT = Vec.getValueType();
10411   EVT EltVT = VecVT.getVectorElementType();
10412   unsigned EltSize = EltVT.getSizeInBits();
10413   unsigned NumElem = VecVT.getVectorNumElements();
10414 
10415   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10416                                                     Idx->isDivergent());
10417 }
10418 
10419 SDValue SITargetLowering::performExtractVectorEltCombine(
10420   SDNode *N, DAGCombinerInfo &DCI) const {
10421   SDValue Vec = N->getOperand(0);
10422   SelectionDAG &DAG = DCI.DAG;
10423 
10424   EVT VecVT = Vec.getValueType();
10425   EVT EltVT = VecVT.getVectorElementType();
10426 
10427   if ((Vec.getOpcode() == ISD::FNEG ||
10428        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10429     SDLoc SL(N);
10430     EVT EltVT = N->getValueType(0);
10431     SDValue Idx = N->getOperand(1);
10432     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10433                               Vec.getOperand(0), Idx);
10434     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10435   }
10436 
10437   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10438   //    =>
10439   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10440   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10441   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10442   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10443     SDLoc SL(N);
10444     EVT EltVT = N->getValueType(0);
10445     SDValue Idx = N->getOperand(1);
10446     unsigned Opc = Vec.getOpcode();
10447 
10448     switch(Opc) {
10449     default:
10450       break;
10451       // TODO: Support other binary operations.
10452     case ISD::FADD:
10453     case ISD::FSUB:
10454     case ISD::FMUL:
10455     case ISD::ADD:
10456     case ISD::UMIN:
10457     case ISD::UMAX:
10458     case ISD::SMIN:
10459     case ISD::SMAX:
10460     case ISD::FMAXNUM:
10461     case ISD::FMINNUM:
10462     case ISD::FMAXNUM_IEEE:
10463     case ISD::FMINNUM_IEEE: {
10464       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10465                                  Vec.getOperand(0), Idx);
10466       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10467                                  Vec.getOperand(1), Idx);
10468 
10469       DCI.AddToWorklist(Elt0.getNode());
10470       DCI.AddToWorklist(Elt1.getNode());
10471       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10472     }
10473     }
10474   }
10475 
10476   unsigned VecSize = VecVT.getSizeInBits();
10477   unsigned EltSize = EltVT.getSizeInBits();
10478 
10479   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10480   if (::shouldExpandVectorDynExt(N)) {
10481     SDLoc SL(N);
10482     SDValue Idx = N->getOperand(1);
10483     SDValue V;
10484     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10485       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10486       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10487       if (I == 0)
10488         V = Elt;
10489       else
10490         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10491     }
10492     return V;
10493   }
10494 
10495   if (!DCI.isBeforeLegalize())
10496     return SDValue();
10497 
10498   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10499   // elements. This exposes more load reduction opportunities by replacing
10500   // multiple small extract_vector_elements with a single 32-bit extract.
10501   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10502   if (isa<MemSDNode>(Vec) &&
10503       EltSize <= 16 &&
10504       EltVT.isByteSized() &&
10505       VecSize > 32 &&
10506       VecSize % 32 == 0 &&
10507       Idx) {
10508     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10509 
10510     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10511     unsigned EltIdx = BitIndex / 32;
10512     unsigned LeftoverBitIdx = BitIndex % 32;
10513     SDLoc SL(N);
10514 
10515     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10516     DCI.AddToWorklist(Cast.getNode());
10517 
10518     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10519                               DAG.getConstant(EltIdx, SL, MVT::i32));
10520     DCI.AddToWorklist(Elt.getNode());
10521     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10522                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10523     DCI.AddToWorklist(Srl.getNode());
10524 
10525     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10526     DCI.AddToWorklist(Trunc.getNode());
10527     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10528   }
10529 
10530   return SDValue();
10531 }
10532 
10533 SDValue
10534 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10535                                                 DAGCombinerInfo &DCI) const {
10536   SDValue Vec = N->getOperand(0);
10537   SDValue Idx = N->getOperand(2);
10538   EVT VecVT = Vec.getValueType();
10539   EVT EltVT = VecVT.getVectorElementType();
10540 
10541   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10542   // => BUILD_VECTOR n x select (e, const-idx)
10543   if (!::shouldExpandVectorDynExt(N))
10544     return SDValue();
10545 
10546   SelectionDAG &DAG = DCI.DAG;
10547   SDLoc SL(N);
10548   SDValue Ins = N->getOperand(1);
10549   EVT IdxVT = Idx.getValueType();
10550 
10551   SmallVector<SDValue, 16> Ops;
10552   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10553     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10554     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10555     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10556     Ops.push_back(V);
10557   }
10558 
10559   return DAG.getBuildVector(VecVT, SL, Ops);
10560 }
10561 
10562 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10563                                           const SDNode *N0,
10564                                           const SDNode *N1) const {
10565   EVT VT = N0->getValueType(0);
10566 
10567   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10568   // support denormals ever.
10569   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10570        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10571         getSubtarget()->hasMadF16())) &&
10572        isOperationLegal(ISD::FMAD, VT))
10573     return ISD::FMAD;
10574 
10575   const TargetOptions &Options = DAG.getTarget().Options;
10576   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10577        (N0->getFlags().hasAllowContract() &&
10578         N1->getFlags().hasAllowContract())) &&
10579       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10580     return ISD::FMA;
10581   }
10582 
10583   return 0;
10584 }
10585 
10586 // For a reassociatable opcode perform:
10587 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10588 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10589                                                SelectionDAG &DAG) const {
10590   EVT VT = N->getValueType(0);
10591   if (VT != MVT::i32 && VT != MVT::i64)
10592     return SDValue();
10593 
10594   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10595     return SDValue();
10596 
10597   unsigned Opc = N->getOpcode();
10598   SDValue Op0 = N->getOperand(0);
10599   SDValue Op1 = N->getOperand(1);
10600 
10601   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10602     return SDValue();
10603 
10604   if (Op0->isDivergent())
10605     std::swap(Op0, Op1);
10606 
10607   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10608     return SDValue();
10609 
10610   SDValue Op2 = Op1.getOperand(1);
10611   Op1 = Op1.getOperand(0);
10612   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10613     return SDValue();
10614 
10615   if (Op1->isDivergent())
10616     std::swap(Op1, Op2);
10617 
10618   SDLoc SL(N);
10619   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10620   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10621 }
10622 
10623 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10624                            EVT VT,
10625                            SDValue N0, SDValue N1, SDValue N2,
10626                            bool Signed) {
10627   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10628   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10629   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10630   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10631 }
10632 
10633 SDValue SITargetLowering::performAddCombine(SDNode *N,
10634                                             DAGCombinerInfo &DCI) const {
10635   SelectionDAG &DAG = DCI.DAG;
10636   EVT VT = N->getValueType(0);
10637   SDLoc SL(N);
10638   SDValue LHS = N->getOperand(0);
10639   SDValue RHS = N->getOperand(1);
10640 
10641   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10642       && Subtarget->hasMad64_32() &&
10643       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10644       VT.getScalarSizeInBits() <= 64) {
10645     if (LHS.getOpcode() != ISD::MUL)
10646       std::swap(LHS, RHS);
10647 
10648     SDValue MulLHS = LHS.getOperand(0);
10649     SDValue MulRHS = LHS.getOperand(1);
10650     SDValue AddRHS = RHS;
10651 
10652     // TODO: Maybe restrict if SGPR inputs.
10653     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10654         numBitsUnsigned(MulRHS, DAG) <= 32) {
10655       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10656       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10657       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10658       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10659     }
10660 
10661     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10662       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10663       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10664       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10665       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10666     }
10667 
10668     return SDValue();
10669   }
10670 
10671   if (SDValue V = reassociateScalarOps(N, DAG)) {
10672     return V;
10673   }
10674 
10675   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10676     return SDValue();
10677 
10678   // add x, zext (setcc) => addcarry x, 0, setcc
10679   // add x, sext (setcc) => subcarry x, 0, setcc
10680   unsigned Opc = LHS.getOpcode();
10681   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10682       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10683     std::swap(RHS, LHS);
10684 
10685   Opc = RHS.getOpcode();
10686   switch (Opc) {
10687   default: break;
10688   case ISD::ZERO_EXTEND:
10689   case ISD::SIGN_EXTEND:
10690   case ISD::ANY_EXTEND: {
10691     auto Cond = RHS.getOperand(0);
10692     // If this won't be a real VOPC output, we would still need to insert an
10693     // extra instruction anyway.
10694     if (!isBoolSGPR(Cond))
10695       break;
10696     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10697     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10698     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10699     return DAG.getNode(Opc, SL, VTList, Args);
10700   }
10701   case ISD::ADDCARRY: {
10702     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10703     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10704     if (!C || C->getZExtValue() != 0) break;
10705     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10706     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10707   }
10708   }
10709   return SDValue();
10710 }
10711 
10712 SDValue SITargetLowering::performSubCombine(SDNode *N,
10713                                             DAGCombinerInfo &DCI) const {
10714   SelectionDAG &DAG = DCI.DAG;
10715   EVT VT = N->getValueType(0);
10716 
10717   if (VT != MVT::i32)
10718     return SDValue();
10719 
10720   SDLoc SL(N);
10721   SDValue LHS = N->getOperand(0);
10722   SDValue RHS = N->getOperand(1);
10723 
10724   // sub x, zext (setcc) => subcarry x, 0, setcc
10725   // sub x, sext (setcc) => addcarry x, 0, setcc
10726   unsigned Opc = RHS.getOpcode();
10727   switch (Opc) {
10728   default: break;
10729   case ISD::ZERO_EXTEND:
10730   case ISD::SIGN_EXTEND:
10731   case ISD::ANY_EXTEND: {
10732     auto Cond = RHS.getOperand(0);
10733     // If this won't be a real VOPC output, we would still need to insert an
10734     // extra instruction anyway.
10735     if (!isBoolSGPR(Cond))
10736       break;
10737     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10738     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10739     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10740     return DAG.getNode(Opc, SL, VTList, Args);
10741   }
10742   }
10743 
10744   if (LHS.getOpcode() == ISD::SUBCARRY) {
10745     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10746     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10747     if (!C || !C->isZero())
10748       return SDValue();
10749     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10750     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10751   }
10752   return SDValue();
10753 }
10754 
10755 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10756   DAGCombinerInfo &DCI) const {
10757 
10758   if (N->getValueType(0) != MVT::i32)
10759     return SDValue();
10760 
10761   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10762   if (!C || C->getZExtValue() != 0)
10763     return SDValue();
10764 
10765   SelectionDAG &DAG = DCI.DAG;
10766   SDValue LHS = N->getOperand(0);
10767 
10768   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10769   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10770   unsigned LHSOpc = LHS.getOpcode();
10771   unsigned Opc = N->getOpcode();
10772   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10773       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10774     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10775     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10776   }
10777   return SDValue();
10778 }
10779 
10780 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10781                                              DAGCombinerInfo &DCI) const {
10782   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10783     return SDValue();
10784 
10785   SelectionDAG &DAG = DCI.DAG;
10786   EVT VT = N->getValueType(0);
10787 
10788   SDLoc SL(N);
10789   SDValue LHS = N->getOperand(0);
10790   SDValue RHS = N->getOperand(1);
10791 
10792   // These should really be instruction patterns, but writing patterns with
10793   // source modifiers is a pain.
10794 
10795   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10796   if (LHS.getOpcode() == ISD::FADD) {
10797     SDValue A = LHS.getOperand(0);
10798     if (A == LHS.getOperand(1)) {
10799       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10800       if (FusedOp != 0) {
10801         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10802         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10803       }
10804     }
10805   }
10806 
10807   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10808   if (RHS.getOpcode() == ISD::FADD) {
10809     SDValue A = RHS.getOperand(0);
10810     if (A == RHS.getOperand(1)) {
10811       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10812       if (FusedOp != 0) {
10813         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10814         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10815       }
10816     }
10817   }
10818 
10819   return SDValue();
10820 }
10821 
10822 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10823                                              DAGCombinerInfo &DCI) const {
10824   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10825     return SDValue();
10826 
10827   SelectionDAG &DAG = DCI.DAG;
10828   SDLoc SL(N);
10829   EVT VT = N->getValueType(0);
10830   assert(!VT.isVector());
10831 
10832   // Try to get the fneg to fold into the source modifier. This undoes generic
10833   // DAG combines and folds them into the mad.
10834   //
10835   // Only do this if we are not trying to support denormals. v_mad_f32 does
10836   // not support denormals ever.
10837   SDValue LHS = N->getOperand(0);
10838   SDValue RHS = N->getOperand(1);
10839   if (LHS.getOpcode() == ISD::FADD) {
10840     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10841     SDValue A = LHS.getOperand(0);
10842     if (A == LHS.getOperand(1)) {
10843       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10844       if (FusedOp != 0){
10845         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10846         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10847 
10848         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10849       }
10850     }
10851   }
10852 
10853   if (RHS.getOpcode() == ISD::FADD) {
10854     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10855 
10856     SDValue A = RHS.getOperand(0);
10857     if (A == RHS.getOperand(1)) {
10858       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10859       if (FusedOp != 0){
10860         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10861         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10862       }
10863     }
10864   }
10865 
10866   return SDValue();
10867 }
10868 
10869 SDValue SITargetLowering::performFMACombine(SDNode *N,
10870                                             DAGCombinerInfo &DCI) const {
10871   SelectionDAG &DAG = DCI.DAG;
10872   EVT VT = N->getValueType(0);
10873   SDLoc SL(N);
10874 
10875   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10876     return SDValue();
10877 
10878   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10879   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10880   SDValue Op1 = N->getOperand(0);
10881   SDValue Op2 = N->getOperand(1);
10882   SDValue FMA = N->getOperand(2);
10883 
10884   if (FMA.getOpcode() != ISD::FMA ||
10885       Op1.getOpcode() != ISD::FP_EXTEND ||
10886       Op2.getOpcode() != ISD::FP_EXTEND)
10887     return SDValue();
10888 
10889   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10890   // regardless of the denorm mode setting. Therefore,
10891   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
10892   const TargetOptions &Options = DAG.getTarget().Options;
10893   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10894       (N->getFlags().hasAllowContract() &&
10895        FMA->getFlags().hasAllowContract())) {
10896     Op1 = Op1.getOperand(0);
10897     Op2 = Op2.getOperand(0);
10898     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10899         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10900       return SDValue();
10901 
10902     SDValue Vec1 = Op1.getOperand(0);
10903     SDValue Idx1 = Op1.getOperand(1);
10904     SDValue Vec2 = Op2.getOperand(0);
10905 
10906     SDValue FMAOp1 = FMA.getOperand(0);
10907     SDValue FMAOp2 = FMA.getOperand(1);
10908     SDValue FMAAcc = FMA.getOperand(2);
10909 
10910     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10911         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10912       return SDValue();
10913 
10914     FMAOp1 = FMAOp1.getOperand(0);
10915     FMAOp2 = FMAOp2.getOperand(0);
10916     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10917         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10918       return SDValue();
10919 
10920     SDValue Vec3 = FMAOp1.getOperand(0);
10921     SDValue Vec4 = FMAOp2.getOperand(0);
10922     SDValue Idx2 = FMAOp1.getOperand(1);
10923 
10924     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10925         // Idx1 and Idx2 cannot be the same.
10926         Idx1 == Idx2)
10927       return SDValue();
10928 
10929     if (Vec1 == Vec2 || Vec3 == Vec4)
10930       return SDValue();
10931 
10932     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10933       return SDValue();
10934 
10935     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10936         (Vec1 == Vec4 && Vec2 == Vec3)) {
10937       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10938                          DAG.getTargetConstant(0, SL, MVT::i1));
10939     }
10940   }
10941   return SDValue();
10942 }
10943 
10944 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10945                                               DAGCombinerInfo &DCI) const {
10946   SelectionDAG &DAG = DCI.DAG;
10947   SDLoc SL(N);
10948 
10949   SDValue LHS = N->getOperand(0);
10950   SDValue RHS = N->getOperand(1);
10951   EVT VT = LHS.getValueType();
10952   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10953 
10954   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10955   if (!CRHS) {
10956     CRHS = dyn_cast<ConstantSDNode>(LHS);
10957     if (CRHS) {
10958       std::swap(LHS, RHS);
10959       CC = getSetCCSwappedOperands(CC);
10960     }
10961   }
10962 
10963   if (CRHS) {
10964     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10965         isBoolSGPR(LHS.getOperand(0))) {
10966       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10967       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10968       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10969       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10970       if ((CRHS->isAllOnes() &&
10971            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10972           (CRHS->isZero() &&
10973            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10974         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10975                            DAG.getConstant(-1, SL, MVT::i1));
10976       if ((CRHS->isAllOnes() &&
10977            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10978           (CRHS->isZero() &&
10979            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10980         return LHS.getOperand(0);
10981     }
10982 
10983     const APInt &CRHSVal = CRHS->getAPIntValue();
10984     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10985         LHS.getOpcode() == ISD::SELECT &&
10986         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10987         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10988         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10989         isBoolSGPR(LHS.getOperand(0))) {
10990       // Given CT != FT:
10991       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10992       // setcc (select cc, CT, CF), CF, ne => cc
10993       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10994       // setcc (select cc, CT, CF), CT, eq => cc
10995       const APInt &CT = LHS.getConstantOperandAPInt(1);
10996       const APInt &CF = LHS.getConstantOperandAPInt(2);
10997 
10998       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10999           (CT == CRHSVal && CC == ISD::SETNE))
11000         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11001                            DAG.getConstant(-1, SL, MVT::i1));
11002       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11003           (CT == CRHSVal && CC == ISD::SETEQ))
11004         return LHS.getOperand(0);
11005     }
11006   }
11007 
11008   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11009                                            VT != MVT::f16))
11010     return SDValue();
11011 
11012   // Match isinf/isfinite pattern
11013   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11014   // (fcmp one (fabs x), inf) -> (fp_class x,
11015   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11016   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11017     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11018     if (!CRHS)
11019       return SDValue();
11020 
11021     const APFloat &APF = CRHS->getValueAPF();
11022     if (APF.isInfinity() && !APF.isNegative()) {
11023       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11024                                  SIInstrFlags::N_INFINITY;
11025       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11026                                     SIInstrFlags::P_ZERO |
11027                                     SIInstrFlags::N_NORMAL |
11028                                     SIInstrFlags::P_NORMAL |
11029                                     SIInstrFlags::N_SUBNORMAL |
11030                                     SIInstrFlags::P_SUBNORMAL;
11031       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11032       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11033                          DAG.getConstant(Mask, SL, MVT::i32));
11034     }
11035   }
11036 
11037   return SDValue();
11038 }
11039 
11040 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11041                                                      DAGCombinerInfo &DCI) const {
11042   SelectionDAG &DAG = DCI.DAG;
11043   SDLoc SL(N);
11044   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11045 
11046   SDValue Src = N->getOperand(0);
11047   SDValue Shift = N->getOperand(0);
11048 
11049   // TODO: Extend type shouldn't matter (assuming legal types).
11050   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11051     Shift = Shift.getOperand(0);
11052 
11053   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11054     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11055     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11056     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11057     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11058     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11059     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11060       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11061                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11062 
11063       unsigned ShiftOffset = 8 * Offset;
11064       if (Shift.getOpcode() == ISD::SHL)
11065         ShiftOffset -= C->getZExtValue();
11066       else
11067         ShiftOffset += C->getZExtValue();
11068 
11069       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11070         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11071                            MVT::f32, Shifted);
11072       }
11073     }
11074   }
11075 
11076   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11077   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11078   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11079     // We simplified Src. If this node is not dead, visit it again so it is
11080     // folded properly.
11081     if (N->getOpcode() != ISD::DELETED_NODE)
11082       DCI.AddToWorklist(N);
11083     return SDValue(N, 0);
11084   }
11085 
11086   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11087   if (SDValue DemandedSrc =
11088           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11089     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11090 
11091   return SDValue();
11092 }
11093 
11094 SDValue SITargetLowering::performClampCombine(SDNode *N,
11095                                               DAGCombinerInfo &DCI) const {
11096   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11097   if (!CSrc)
11098     return SDValue();
11099 
11100   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11101   const APFloat &F = CSrc->getValueAPF();
11102   APFloat Zero = APFloat::getZero(F.getSemantics());
11103   if (F < Zero ||
11104       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11105     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11106   }
11107 
11108   APFloat One(F.getSemantics(), "1.0");
11109   if (F > One)
11110     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11111 
11112   return SDValue(CSrc, 0);
11113 }
11114 
11115 
11116 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11117                                             DAGCombinerInfo &DCI) const {
11118   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11119     return SDValue();
11120   switch (N->getOpcode()) {
11121   case ISD::ADD:
11122     return performAddCombine(N, DCI);
11123   case ISD::SUB:
11124     return performSubCombine(N, DCI);
11125   case ISD::ADDCARRY:
11126   case ISD::SUBCARRY:
11127     return performAddCarrySubCarryCombine(N, DCI);
11128   case ISD::FADD:
11129     return performFAddCombine(N, DCI);
11130   case ISD::FSUB:
11131     return performFSubCombine(N, DCI);
11132   case ISD::SETCC:
11133     return performSetCCCombine(N, DCI);
11134   case ISD::FMAXNUM:
11135   case ISD::FMINNUM:
11136   case ISD::FMAXNUM_IEEE:
11137   case ISD::FMINNUM_IEEE:
11138   case ISD::SMAX:
11139   case ISD::SMIN:
11140   case ISD::UMAX:
11141   case ISD::UMIN:
11142   case AMDGPUISD::FMIN_LEGACY:
11143   case AMDGPUISD::FMAX_LEGACY:
11144     return performMinMaxCombine(N, DCI);
11145   case ISD::FMA:
11146     return performFMACombine(N, DCI);
11147   case ISD::AND:
11148     return performAndCombine(N, DCI);
11149   case ISD::OR:
11150     return performOrCombine(N, DCI);
11151   case ISD::XOR:
11152     return performXorCombine(N, DCI);
11153   case ISD::ZERO_EXTEND:
11154     return performZeroExtendCombine(N, DCI);
11155   case ISD::SIGN_EXTEND_INREG:
11156     return performSignExtendInRegCombine(N , DCI);
11157   case AMDGPUISD::FP_CLASS:
11158     return performClassCombine(N, DCI);
11159   case ISD::FCANONICALIZE:
11160     return performFCanonicalizeCombine(N, DCI);
11161   case AMDGPUISD::RCP:
11162     return performRcpCombine(N, DCI);
11163   case AMDGPUISD::FRACT:
11164   case AMDGPUISD::RSQ:
11165   case AMDGPUISD::RCP_LEGACY:
11166   case AMDGPUISD::RCP_IFLAG:
11167   case AMDGPUISD::RSQ_CLAMP:
11168   case AMDGPUISD::LDEXP: {
11169     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11170     SDValue Src = N->getOperand(0);
11171     if (Src.isUndef())
11172       return Src;
11173     break;
11174   }
11175   case ISD::SINT_TO_FP:
11176   case ISD::UINT_TO_FP:
11177     return performUCharToFloatCombine(N, DCI);
11178   case AMDGPUISD::CVT_F32_UBYTE0:
11179   case AMDGPUISD::CVT_F32_UBYTE1:
11180   case AMDGPUISD::CVT_F32_UBYTE2:
11181   case AMDGPUISD::CVT_F32_UBYTE3:
11182     return performCvtF32UByteNCombine(N, DCI);
11183   case AMDGPUISD::FMED3:
11184     return performFMed3Combine(N, DCI);
11185   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11186     return performCvtPkRTZCombine(N, DCI);
11187   case AMDGPUISD::CLAMP:
11188     return performClampCombine(N, DCI);
11189   case ISD::SCALAR_TO_VECTOR: {
11190     SelectionDAG &DAG = DCI.DAG;
11191     EVT VT = N->getValueType(0);
11192 
11193     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11194     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11195       SDLoc SL(N);
11196       SDValue Src = N->getOperand(0);
11197       EVT EltVT = Src.getValueType();
11198       if (EltVT == MVT::f16)
11199         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11200 
11201       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11202       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11203     }
11204 
11205     break;
11206   }
11207   case ISD::EXTRACT_VECTOR_ELT:
11208     return performExtractVectorEltCombine(N, DCI);
11209   case ISD::INSERT_VECTOR_ELT:
11210     return performInsertVectorEltCombine(N, DCI);
11211   case ISD::LOAD: {
11212     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11213       return Widended;
11214     LLVM_FALLTHROUGH;
11215   }
11216   default: {
11217     if (!DCI.isBeforeLegalize()) {
11218       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11219         return performMemSDNodeCombine(MemNode, DCI);
11220     }
11221 
11222     break;
11223   }
11224   }
11225 
11226   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11227 }
11228 
11229 /// Helper function for adjustWritemask
11230 static unsigned SubIdx2Lane(unsigned Idx) {
11231   switch (Idx) {
11232   default: return ~0u;
11233   case AMDGPU::sub0: return 0;
11234   case AMDGPU::sub1: return 1;
11235   case AMDGPU::sub2: return 2;
11236   case AMDGPU::sub3: return 3;
11237   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11238   }
11239 }
11240 
11241 /// Adjust the writemask of MIMG instructions
11242 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11243                                           SelectionDAG &DAG) const {
11244   unsigned Opcode = Node->getMachineOpcode();
11245 
11246   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11247   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11248   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11249     return Node; // not implemented for D16
11250 
11251   SDNode *Users[5] = { nullptr };
11252   unsigned Lane = 0;
11253   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11254   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11255   unsigned NewDmask = 0;
11256   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11257   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11258   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11259                   Node->getConstantOperandVal(LWEIdx))
11260                      ? true
11261                      : false;
11262   unsigned TFCLane = 0;
11263   bool HasChain = Node->getNumValues() > 1;
11264 
11265   if (OldDmask == 0) {
11266     // These are folded out, but on the chance it happens don't assert.
11267     return Node;
11268   }
11269 
11270   unsigned OldBitsSet = countPopulation(OldDmask);
11271   // Work out which is the TFE/LWE lane if that is enabled.
11272   if (UsesTFC) {
11273     TFCLane = OldBitsSet;
11274   }
11275 
11276   // Try to figure out the used register components
11277   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11278        I != E; ++I) {
11279 
11280     // Don't look at users of the chain.
11281     if (I.getUse().getResNo() != 0)
11282       continue;
11283 
11284     // Abort if we can't understand the usage
11285     if (!I->isMachineOpcode() ||
11286         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11287       return Node;
11288 
11289     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11290     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11291     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11292     // set, etc.
11293     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11294     if (Lane == ~0u)
11295       return Node;
11296 
11297     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11298     if (UsesTFC && Lane == TFCLane) {
11299       Users[Lane] = *I;
11300     } else {
11301       // Set which texture component corresponds to the lane.
11302       unsigned Comp;
11303       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11304         Comp = countTrailingZeros(Dmask);
11305         Dmask &= ~(1 << Comp);
11306       }
11307 
11308       // Abort if we have more than one user per component.
11309       if (Users[Lane])
11310         return Node;
11311 
11312       Users[Lane] = *I;
11313       NewDmask |= 1 << Comp;
11314     }
11315   }
11316 
11317   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11318   bool NoChannels = !NewDmask;
11319   if (NoChannels) {
11320     if (!UsesTFC) {
11321       // No uses of the result and not using TFC. Then do nothing.
11322       return Node;
11323     }
11324     // If the original dmask has one channel - then nothing to do
11325     if (OldBitsSet == 1)
11326       return Node;
11327     // Use an arbitrary dmask - required for the instruction to work
11328     NewDmask = 1;
11329   }
11330   // Abort if there's no change
11331   if (NewDmask == OldDmask)
11332     return Node;
11333 
11334   unsigned BitsSet = countPopulation(NewDmask);
11335 
11336   // Check for TFE or LWE - increase the number of channels by one to account
11337   // for the extra return value
11338   // This will need adjustment for D16 if this is also included in
11339   // adjustWriteMask (this function) but at present D16 are excluded.
11340   unsigned NewChannels = BitsSet + UsesTFC;
11341 
11342   int NewOpcode =
11343       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11344   assert(NewOpcode != -1 &&
11345          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11346          "failed to find equivalent MIMG op");
11347 
11348   // Adjust the writemask in the node
11349   SmallVector<SDValue, 12> Ops;
11350   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11351   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11352   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11353 
11354   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11355 
11356   MVT ResultVT = NewChannels == 1 ?
11357     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11358                            NewChannels == 5 ? 8 : NewChannels);
11359   SDVTList NewVTList = HasChain ?
11360     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11361 
11362 
11363   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11364                                               NewVTList, Ops);
11365 
11366   if (HasChain) {
11367     // Update chain.
11368     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11369     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11370   }
11371 
11372   if (NewChannels == 1) {
11373     assert(Node->hasNUsesOfValue(1, 0));
11374     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11375                                       SDLoc(Node), Users[Lane]->getValueType(0),
11376                                       SDValue(NewNode, 0));
11377     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11378     return nullptr;
11379   }
11380 
11381   // Update the users of the node with the new indices
11382   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11383     SDNode *User = Users[i];
11384     if (!User) {
11385       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11386       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11387       if (i || !NoChannels)
11388         continue;
11389     } else {
11390       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11391       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11392     }
11393 
11394     switch (Idx) {
11395     default: break;
11396     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11397     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11398     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11399     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11400     }
11401   }
11402 
11403   DAG.RemoveDeadNode(Node);
11404   return nullptr;
11405 }
11406 
11407 static bool isFrameIndexOp(SDValue Op) {
11408   if (Op.getOpcode() == ISD::AssertZext)
11409     Op = Op.getOperand(0);
11410 
11411   return isa<FrameIndexSDNode>(Op);
11412 }
11413 
11414 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11415 /// with frame index operands.
11416 /// LLVM assumes that inputs are to these instructions are registers.
11417 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11418                                                         SelectionDAG &DAG) const {
11419   if (Node->getOpcode() == ISD::CopyToReg) {
11420     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11421     SDValue SrcVal = Node->getOperand(2);
11422 
11423     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11424     // to try understanding copies to physical registers.
11425     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11426       SDLoc SL(Node);
11427       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11428       SDValue VReg = DAG.getRegister(
11429         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11430 
11431       SDNode *Glued = Node->getGluedNode();
11432       SDValue ToVReg
11433         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11434                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11435       SDValue ToResultReg
11436         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11437                            VReg, ToVReg.getValue(1));
11438       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11439       DAG.RemoveDeadNode(Node);
11440       return ToResultReg.getNode();
11441     }
11442   }
11443 
11444   SmallVector<SDValue, 8> Ops;
11445   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11446     if (!isFrameIndexOp(Node->getOperand(i))) {
11447       Ops.push_back(Node->getOperand(i));
11448       continue;
11449     }
11450 
11451     SDLoc DL(Node);
11452     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11453                                      Node->getOperand(i).getValueType(),
11454                                      Node->getOperand(i)), 0));
11455   }
11456 
11457   return DAG.UpdateNodeOperands(Node, Ops);
11458 }
11459 
11460 /// Fold the instructions after selecting them.
11461 /// Returns null if users were already updated.
11462 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11463                                           SelectionDAG &DAG) const {
11464   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11465   unsigned Opcode = Node->getMachineOpcode();
11466 
11467   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11468       !TII->isGather4(Opcode) &&
11469       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11470     return adjustWritemask(Node, DAG);
11471   }
11472 
11473   if (Opcode == AMDGPU::INSERT_SUBREG ||
11474       Opcode == AMDGPU::REG_SEQUENCE) {
11475     legalizeTargetIndependentNode(Node, DAG);
11476     return Node;
11477   }
11478 
11479   switch (Opcode) {
11480   case AMDGPU::V_DIV_SCALE_F32_e64:
11481   case AMDGPU::V_DIV_SCALE_F64_e64: {
11482     // Satisfy the operand register constraint when one of the inputs is
11483     // undefined. Ordinarily each undef value will have its own implicit_def of
11484     // a vreg, so force these to use a single register.
11485     SDValue Src0 = Node->getOperand(1);
11486     SDValue Src1 = Node->getOperand(3);
11487     SDValue Src2 = Node->getOperand(5);
11488 
11489     if ((Src0.isMachineOpcode() &&
11490          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11491         (Src0 == Src1 || Src0 == Src2))
11492       break;
11493 
11494     MVT VT = Src0.getValueType().getSimpleVT();
11495     const TargetRegisterClass *RC =
11496         getRegClassFor(VT, Src0.getNode()->isDivergent());
11497 
11498     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11499     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11500 
11501     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11502                                       UndefReg, Src0, SDValue());
11503 
11504     // src0 must be the same register as src1 or src2, even if the value is
11505     // undefined, so make sure we don't violate this constraint.
11506     if (Src0.isMachineOpcode() &&
11507         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11508       if (Src1.isMachineOpcode() &&
11509           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11510         Src0 = Src1;
11511       else if (Src2.isMachineOpcode() &&
11512                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11513         Src0 = Src2;
11514       else {
11515         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11516         Src0 = UndefReg;
11517         Src1 = UndefReg;
11518       }
11519     } else
11520       break;
11521 
11522     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11523     Ops[1] = Src0;
11524     Ops[3] = Src1;
11525     Ops[5] = Src2;
11526     Ops.push_back(ImpDef.getValue(1));
11527     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11528   }
11529   default:
11530     break;
11531   }
11532 
11533   return Node;
11534 }
11535 
11536 // Any MIMG instructions that use tfe or lwe require an initialization of the
11537 // result register that will be written in the case of a memory access failure.
11538 // The required code is also added to tie this init code to the result of the
11539 // img instruction.
11540 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11541   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11542   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11543   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11544   MachineBasicBlock &MBB = *MI.getParent();
11545 
11546   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11547   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11548   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11549 
11550   if (!TFE && !LWE) // intersect_ray
11551     return;
11552 
11553   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11554   unsigned LWEVal = LWE->getImm();
11555   unsigned D16Val = D16 ? D16->getImm() : 0;
11556 
11557   if (!TFEVal && !LWEVal)
11558     return;
11559 
11560   // At least one of TFE or LWE are non-zero
11561   // We have to insert a suitable initialization of the result value and
11562   // tie this to the dest of the image instruction.
11563 
11564   const DebugLoc &DL = MI.getDebugLoc();
11565 
11566   int DstIdx =
11567       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11568 
11569   // Calculate which dword we have to initialize to 0.
11570   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11571 
11572   // check that dmask operand is found.
11573   assert(MO_Dmask && "Expected dmask operand in instruction");
11574 
11575   unsigned dmask = MO_Dmask->getImm();
11576   // Determine the number of active lanes taking into account the
11577   // Gather4 special case
11578   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11579 
11580   bool Packed = !Subtarget->hasUnpackedD16VMem();
11581 
11582   unsigned InitIdx =
11583       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11584 
11585   // Abandon attempt if the dst size isn't large enough
11586   // - this is in fact an error but this is picked up elsewhere and
11587   // reported correctly.
11588   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11589   if (DstSize < InitIdx)
11590     return;
11591 
11592   // Create a register for the initialization value.
11593   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11594   unsigned NewDst = 0; // Final initialized value will be in here
11595 
11596   // If PRTStrictNull feature is enabled (the default) then initialize
11597   // all the result registers to 0, otherwise just the error indication
11598   // register (VGPRn+1)
11599   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11600   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11601 
11602   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11603   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11604     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11605     // Initialize dword
11606     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11607     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11608       .addImm(0);
11609     // Insert into the super-reg
11610     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11611       .addReg(PrevDst)
11612       .addReg(SubReg)
11613       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11614 
11615     PrevDst = NewDst;
11616   }
11617 
11618   // Add as an implicit operand
11619   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11620 
11621   // Tie the just added implicit operand to the dst
11622   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11623 }
11624 
11625 /// Assign the register class depending on the number of
11626 /// bits set in the writemask
11627 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11628                                                      SDNode *Node) const {
11629   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11630 
11631   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11632 
11633   if (TII->isVOP3(MI.getOpcode())) {
11634     // Make sure constant bus requirements are respected.
11635     TII->legalizeOperandsVOP3(MRI, MI);
11636 
11637     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11638     // This saves a chain-copy of registers and better balance register
11639     // use between vgpr and agpr as agpr tuples tend to be big.
11640     if (MI.getDesc().OpInfo) {
11641       unsigned Opc = MI.getOpcode();
11642       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11643       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11644                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11645         if (I == -1)
11646           break;
11647         MachineOperand &Op = MI.getOperand(I);
11648         if (!Op.isReg() || !Op.getReg().isVirtual())
11649           continue;
11650         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11651         if (!TRI->hasAGPRs(RC))
11652           continue;
11653         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11654         if (!Src || !Src->isCopy() ||
11655             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11656           continue;
11657         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11658         // All uses of agpr64 and agpr32 can also accept vgpr except for
11659         // v_accvgpr_read, but we do not produce agpr reads during selection,
11660         // so no use checks are needed.
11661         MRI.setRegClass(Op.getReg(), NewRC);
11662       }
11663 
11664       // Resolve the rest of AV operands to AGPRs.
11665       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11666         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11667           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11668           if (TRI->isVectorSuperClass(RC)) {
11669             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11670             MRI.setRegClass(Src2->getReg(), NewRC);
11671             if (Src2->isTied())
11672               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11673           }
11674         }
11675       }
11676     }
11677 
11678     return;
11679   }
11680 
11681   // Replace unused atomics with the no return version.
11682   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11683   if (NoRetAtomicOp != -1) {
11684     if (!Node->hasAnyUseOfValue(0)) {
11685       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11686                                                AMDGPU::OpName::cpol);
11687       if (CPolIdx != -1) {
11688         MachineOperand &CPol = MI.getOperand(CPolIdx);
11689         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11690       }
11691       MI.removeOperand(0);
11692       MI.setDesc(TII->get(NoRetAtomicOp));
11693       return;
11694     }
11695 
11696     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11697     // instruction, because the return type of these instructions is a vec2 of
11698     // the memory type, so it can be tied to the input operand.
11699     // This means these instructions always have a use, so we need to add a
11700     // special case to check if the atomic has only one extract_subreg use,
11701     // which itself has no uses.
11702     if ((Node->hasNUsesOfValue(1, 0) &&
11703          Node->use_begin()->isMachineOpcode() &&
11704          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11705          !Node->use_begin()->hasAnyUseOfValue(0))) {
11706       Register Def = MI.getOperand(0).getReg();
11707 
11708       // Change this into a noret atomic.
11709       MI.setDesc(TII->get(NoRetAtomicOp));
11710       MI.removeOperand(0);
11711 
11712       // If we only remove the def operand from the atomic instruction, the
11713       // extract_subreg will be left with a use of a vreg without a def.
11714       // So we need to insert an implicit_def to avoid machine verifier
11715       // errors.
11716       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11717               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11718     }
11719     return;
11720   }
11721 
11722   if (TII->isMIMG(MI) && !MI.mayStore())
11723     AddIMGInit(MI);
11724 }
11725 
11726 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11727                               uint64_t Val) {
11728   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11729   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11730 }
11731 
11732 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11733                                                 const SDLoc &DL,
11734                                                 SDValue Ptr) const {
11735   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11736 
11737   // Build the half of the subregister with the constants before building the
11738   // full 128-bit register. If we are building multiple resource descriptors,
11739   // this will allow CSEing of the 2-component register.
11740   const SDValue Ops0[] = {
11741     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11742     buildSMovImm32(DAG, DL, 0),
11743     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11744     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11745     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11746   };
11747 
11748   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11749                                                 MVT::v2i32, Ops0), 0);
11750 
11751   // Combine the constants and the pointer.
11752   const SDValue Ops1[] = {
11753     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11754     Ptr,
11755     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11756     SubRegHi,
11757     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11758   };
11759 
11760   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11761 }
11762 
11763 /// Return a resource descriptor with the 'Add TID' bit enabled
11764 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11765 ///        of the resource descriptor) to create an offset, which is added to
11766 ///        the resource pointer.
11767 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11768                                            SDValue Ptr, uint32_t RsrcDword1,
11769                                            uint64_t RsrcDword2And3) const {
11770   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11771   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11772   if (RsrcDword1) {
11773     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11774                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11775                     0);
11776   }
11777 
11778   SDValue DataLo = buildSMovImm32(DAG, DL,
11779                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11780   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11781 
11782   const SDValue Ops[] = {
11783     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11784     PtrLo,
11785     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11786     PtrHi,
11787     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11788     DataLo,
11789     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11790     DataHi,
11791     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11792   };
11793 
11794   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11795 }
11796 
11797 //===----------------------------------------------------------------------===//
11798 //                         SI Inline Assembly Support
11799 //===----------------------------------------------------------------------===//
11800 
11801 std::pair<unsigned, const TargetRegisterClass *>
11802 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11803                                                StringRef Constraint,
11804                                                MVT VT) const {
11805   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11806 
11807   const TargetRegisterClass *RC = nullptr;
11808   if (Constraint.size() == 1) {
11809     const unsigned BitWidth = VT.getSizeInBits();
11810     switch (Constraint[0]) {
11811     default:
11812       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11813     case 's':
11814     case 'r':
11815       switch (BitWidth) {
11816       case 16:
11817         RC = &AMDGPU::SReg_32RegClass;
11818         break;
11819       case 64:
11820         RC = &AMDGPU::SGPR_64RegClass;
11821         break;
11822       default:
11823         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11824         if (!RC)
11825           return std::make_pair(0U, nullptr);
11826         break;
11827       }
11828       break;
11829     case 'v':
11830       switch (BitWidth) {
11831       case 16:
11832         RC = &AMDGPU::VGPR_32RegClass;
11833         break;
11834       default:
11835         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11836         if (!RC)
11837           return std::make_pair(0U, nullptr);
11838         break;
11839       }
11840       break;
11841     case 'a':
11842       if (!Subtarget->hasMAIInsts())
11843         break;
11844       switch (BitWidth) {
11845       case 16:
11846         RC = &AMDGPU::AGPR_32RegClass;
11847         break;
11848       default:
11849         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11850         if (!RC)
11851           return std::make_pair(0U, nullptr);
11852         break;
11853       }
11854       break;
11855     }
11856     // We actually support i128, i16 and f16 as inline parameters
11857     // even if they are not reported as legal
11858     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11859                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11860       return std::make_pair(0U, RC);
11861   }
11862 
11863   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11864     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11865     if (RegName.consume_front("v")) {
11866       RC = &AMDGPU::VGPR_32RegClass;
11867     } else if (RegName.consume_front("s")) {
11868       RC = &AMDGPU::SGPR_32RegClass;
11869     } else if (RegName.consume_front("a")) {
11870       RC = &AMDGPU::AGPR_32RegClass;
11871     }
11872 
11873     if (RC) {
11874       uint32_t Idx;
11875       if (RegName.consume_front("[")) {
11876         uint32_t End;
11877         bool Failed = RegName.consumeInteger(10, Idx);
11878         Failed |= !RegName.consume_front(":");
11879         Failed |= RegName.consumeInteger(10, End);
11880         Failed |= !RegName.consume_back("]");
11881         if (!Failed) {
11882           uint32_t Width = (End - Idx + 1) * 32;
11883           MCRegister Reg = RC->getRegister(Idx);
11884           if (SIRegisterInfo::isVGPRClass(RC))
11885             RC = TRI->getVGPRClassForBitWidth(Width);
11886           else if (SIRegisterInfo::isSGPRClass(RC))
11887             RC = TRI->getSGPRClassForBitWidth(Width);
11888           else if (SIRegisterInfo::isAGPRClass(RC))
11889             RC = TRI->getAGPRClassForBitWidth(Width);
11890           if (RC) {
11891             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11892             return std::make_pair(Reg, RC);
11893           }
11894         }
11895       } else {
11896         bool Failed = RegName.getAsInteger(10, Idx);
11897         if (!Failed && Idx < RC->getNumRegs())
11898           return std::make_pair(RC->getRegister(Idx), RC);
11899       }
11900     }
11901   }
11902 
11903   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11904   if (Ret.first)
11905     Ret.second = TRI->getPhysRegClass(Ret.first);
11906 
11907   return Ret;
11908 }
11909 
11910 static bool isImmConstraint(StringRef Constraint) {
11911   if (Constraint.size() == 1) {
11912     switch (Constraint[0]) {
11913     default: break;
11914     case 'I':
11915     case 'J':
11916     case 'A':
11917     case 'B':
11918     case 'C':
11919       return true;
11920     }
11921   } else if (Constraint == "DA" ||
11922              Constraint == "DB") {
11923     return true;
11924   }
11925   return false;
11926 }
11927 
11928 SITargetLowering::ConstraintType
11929 SITargetLowering::getConstraintType(StringRef Constraint) const {
11930   if (Constraint.size() == 1) {
11931     switch (Constraint[0]) {
11932     default: break;
11933     case 's':
11934     case 'v':
11935     case 'a':
11936       return C_RegisterClass;
11937     }
11938   }
11939   if (isImmConstraint(Constraint)) {
11940     return C_Other;
11941   }
11942   return TargetLowering::getConstraintType(Constraint);
11943 }
11944 
11945 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11946   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11947     Val = Val & maskTrailingOnes<uint64_t>(Size);
11948   }
11949   return Val;
11950 }
11951 
11952 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11953                                                     std::string &Constraint,
11954                                                     std::vector<SDValue> &Ops,
11955                                                     SelectionDAG &DAG) const {
11956   if (isImmConstraint(Constraint)) {
11957     uint64_t Val;
11958     if (getAsmOperandConstVal(Op, Val) &&
11959         checkAsmConstraintVal(Op, Constraint, Val)) {
11960       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11961       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11962     }
11963   } else {
11964     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11965   }
11966 }
11967 
11968 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11969   unsigned Size = Op.getScalarValueSizeInBits();
11970   if (Size > 64)
11971     return false;
11972 
11973   if (Size == 16 && !Subtarget->has16BitInsts())
11974     return false;
11975 
11976   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11977     Val = C->getSExtValue();
11978     return true;
11979   }
11980   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11981     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11982     return true;
11983   }
11984   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11985     if (Size != 16 || Op.getNumOperands() != 2)
11986       return false;
11987     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11988       return false;
11989     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11990       Val = C->getSExtValue();
11991       return true;
11992     }
11993     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11994       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11995       return true;
11996     }
11997   }
11998 
11999   return false;
12000 }
12001 
12002 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12003                                              const std::string &Constraint,
12004                                              uint64_t Val) const {
12005   if (Constraint.size() == 1) {
12006     switch (Constraint[0]) {
12007     case 'I':
12008       return AMDGPU::isInlinableIntLiteral(Val);
12009     case 'J':
12010       return isInt<16>(Val);
12011     case 'A':
12012       return checkAsmConstraintValA(Op, Val);
12013     case 'B':
12014       return isInt<32>(Val);
12015     case 'C':
12016       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12017              AMDGPU::isInlinableIntLiteral(Val);
12018     default:
12019       break;
12020     }
12021   } else if (Constraint.size() == 2) {
12022     if (Constraint == "DA") {
12023       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12024       int64_t LoBits = static_cast<int32_t>(Val);
12025       return checkAsmConstraintValA(Op, HiBits, 32) &&
12026              checkAsmConstraintValA(Op, LoBits, 32);
12027     }
12028     if (Constraint == "DB") {
12029       return true;
12030     }
12031   }
12032   llvm_unreachable("Invalid asm constraint");
12033 }
12034 
12035 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12036                                               uint64_t Val,
12037                                               unsigned MaxSize) const {
12038   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12039   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12040   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12041       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12042       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12043     return true;
12044   }
12045   return false;
12046 }
12047 
12048 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12049   switch (UnalignedClassID) {
12050   case AMDGPU::VReg_64RegClassID:
12051     return AMDGPU::VReg_64_Align2RegClassID;
12052   case AMDGPU::VReg_96RegClassID:
12053     return AMDGPU::VReg_96_Align2RegClassID;
12054   case AMDGPU::VReg_128RegClassID:
12055     return AMDGPU::VReg_128_Align2RegClassID;
12056   case AMDGPU::VReg_160RegClassID:
12057     return AMDGPU::VReg_160_Align2RegClassID;
12058   case AMDGPU::VReg_192RegClassID:
12059     return AMDGPU::VReg_192_Align2RegClassID;
12060   case AMDGPU::VReg_224RegClassID:
12061     return AMDGPU::VReg_224_Align2RegClassID;
12062   case AMDGPU::VReg_256RegClassID:
12063     return AMDGPU::VReg_256_Align2RegClassID;
12064   case AMDGPU::VReg_512RegClassID:
12065     return AMDGPU::VReg_512_Align2RegClassID;
12066   case AMDGPU::VReg_1024RegClassID:
12067     return AMDGPU::VReg_1024_Align2RegClassID;
12068   case AMDGPU::AReg_64RegClassID:
12069     return AMDGPU::AReg_64_Align2RegClassID;
12070   case AMDGPU::AReg_96RegClassID:
12071     return AMDGPU::AReg_96_Align2RegClassID;
12072   case AMDGPU::AReg_128RegClassID:
12073     return AMDGPU::AReg_128_Align2RegClassID;
12074   case AMDGPU::AReg_160RegClassID:
12075     return AMDGPU::AReg_160_Align2RegClassID;
12076   case AMDGPU::AReg_192RegClassID:
12077     return AMDGPU::AReg_192_Align2RegClassID;
12078   case AMDGPU::AReg_256RegClassID:
12079     return AMDGPU::AReg_256_Align2RegClassID;
12080   case AMDGPU::AReg_512RegClassID:
12081     return AMDGPU::AReg_512_Align2RegClassID;
12082   case AMDGPU::AReg_1024RegClassID:
12083     return AMDGPU::AReg_1024_Align2RegClassID;
12084   default:
12085     return -1;
12086   }
12087 }
12088 
12089 // Figure out which registers should be reserved for stack access. Only after
12090 // the function is legalized do we know all of the non-spill stack objects or if
12091 // calls are present.
12092 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12093   MachineRegisterInfo &MRI = MF.getRegInfo();
12094   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12095   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12096   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12097   const SIInstrInfo *TII = ST.getInstrInfo();
12098 
12099   if (Info->isEntryFunction()) {
12100     // Callable functions have fixed registers used for stack access.
12101     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12102   }
12103 
12104   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12105                              Info->getStackPtrOffsetReg()));
12106   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12107     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12108 
12109   // We need to worry about replacing the default register with itself in case
12110   // of MIR testcases missing the MFI.
12111   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12112     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12113 
12114   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12115     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12116 
12117   Info->limitOccupancy(MF);
12118 
12119   if (ST.isWave32() && !MF.empty()) {
12120     for (auto &MBB : MF) {
12121       for (auto &MI : MBB) {
12122         TII->fixImplicitOperands(MI);
12123       }
12124     }
12125   }
12126 
12127   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12128   // classes if required. Ideally the register class constraints would differ
12129   // per-subtarget, but there's no easy way to achieve that right now. This is
12130   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12131   // from using them as the register class for legal types.
12132   if (ST.needsAlignedVGPRs()) {
12133     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12134       const Register Reg = Register::index2VirtReg(I);
12135       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12136       if (!RC)
12137         continue;
12138       int NewClassID = getAlignedAGPRClassID(RC->getID());
12139       if (NewClassID != -1)
12140         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12141     }
12142   }
12143 
12144   TargetLoweringBase::finalizeLowering(MF);
12145 }
12146 
12147 void SITargetLowering::computeKnownBitsForFrameIndex(
12148   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12149   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12150 
12151   // Set the high bits to zero based on the maximum allowed scratch size per
12152   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12153   // calculation won't overflow, so assume the sign bit is never set.
12154   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12155 }
12156 
12157 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12158                                    KnownBits &Known, unsigned Dim) {
12159   unsigned MaxValue =
12160       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12161   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12162 }
12163 
12164 void SITargetLowering::computeKnownBitsForTargetInstr(
12165     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12166     const MachineRegisterInfo &MRI, unsigned Depth) const {
12167   const MachineInstr *MI = MRI.getVRegDef(R);
12168   switch (MI->getOpcode()) {
12169   case AMDGPU::G_INTRINSIC: {
12170     switch (MI->getIntrinsicID()) {
12171     case Intrinsic::amdgcn_workitem_id_x:
12172       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12173       break;
12174     case Intrinsic::amdgcn_workitem_id_y:
12175       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12176       break;
12177     case Intrinsic::amdgcn_workitem_id_z:
12178       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12179       break;
12180     case Intrinsic::amdgcn_mbcnt_lo:
12181     case Intrinsic::amdgcn_mbcnt_hi: {
12182       // These return at most the wavefront size - 1.
12183       unsigned Size = MRI.getType(R).getSizeInBits();
12184       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12185       break;
12186     }
12187     case Intrinsic::amdgcn_groupstaticsize: {
12188       // We can report everything over the maximum size as 0. We can't report
12189       // based on the actual size because we don't know if it's accurate or not
12190       // at any given point.
12191       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12192       break;
12193     }
12194     }
12195     break;
12196   }
12197   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12198     Known.Zero.setHighBits(24);
12199     break;
12200   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12201     Known.Zero.setHighBits(16);
12202     break;
12203   }
12204 }
12205 
12206 Align SITargetLowering::computeKnownAlignForTargetInstr(
12207   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12208   unsigned Depth) const {
12209   const MachineInstr *MI = MRI.getVRegDef(R);
12210   switch (MI->getOpcode()) {
12211   case AMDGPU::G_INTRINSIC:
12212   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12213     // FIXME: Can this move to generic code? What about the case where the call
12214     // site specifies a lower alignment?
12215     Intrinsic::ID IID = MI->getIntrinsicID();
12216     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12217     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12218     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12219       return *RetAlign;
12220     return Align(1);
12221   }
12222   default:
12223     return Align(1);
12224   }
12225 }
12226 
12227 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12228   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12229   const Align CacheLineAlign = Align(64);
12230 
12231   // Pre-GFX10 target did not benefit from loop alignment
12232   if (!ML || DisableLoopAlignment ||
12233       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12234       getSubtarget()->hasInstFwdPrefetchBug())
12235     return PrefAlign;
12236 
12237   // On GFX10 I$ is 4 x 64 bytes cache lines.
12238   // By default prefetcher keeps one cache line behind and reads two ahead.
12239   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12240   // behind and one ahead.
12241   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12242   // If loop fits 64 bytes it always spans no more than two cache lines and
12243   // does not need an alignment.
12244   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12245   // Else if loop is less or equal 192 bytes we need two lines behind.
12246 
12247   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12248   const MachineBasicBlock *Header = ML->getHeader();
12249   if (Header->getAlignment() != PrefAlign)
12250     return Header->getAlignment(); // Already processed.
12251 
12252   unsigned LoopSize = 0;
12253   for (const MachineBasicBlock *MBB : ML->blocks()) {
12254     // If inner loop block is aligned assume in average half of the alignment
12255     // size to be added as nops.
12256     if (MBB != Header)
12257       LoopSize += MBB->getAlignment().value() / 2;
12258 
12259     for (const MachineInstr &MI : *MBB) {
12260       LoopSize += TII->getInstSizeInBytes(MI);
12261       if (LoopSize > 192)
12262         return PrefAlign;
12263     }
12264   }
12265 
12266   if (LoopSize <= 64)
12267     return PrefAlign;
12268 
12269   if (LoopSize <= 128)
12270     return CacheLineAlign;
12271 
12272   // If any of parent loops is surrounded by prefetch instructions do not
12273   // insert new for inner loop, which would reset parent's settings.
12274   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12275     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12276       auto I = Exit->getFirstNonDebugInstr();
12277       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12278         return CacheLineAlign;
12279     }
12280   }
12281 
12282   MachineBasicBlock *Pre = ML->getLoopPreheader();
12283   MachineBasicBlock *Exit = ML->getExitBlock();
12284 
12285   if (Pre && Exit) {
12286     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12287             TII->get(AMDGPU::S_INST_PREFETCH))
12288       .addImm(1); // prefetch 2 lines behind PC
12289 
12290     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12291             TII->get(AMDGPU::S_INST_PREFETCH))
12292       .addImm(2); // prefetch 1 line behind PC
12293   }
12294 
12295   return CacheLineAlign;
12296 }
12297 
12298 LLVM_ATTRIBUTE_UNUSED
12299 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12300   assert(N->getOpcode() == ISD::CopyFromReg);
12301   do {
12302     // Follow the chain until we find an INLINEASM node.
12303     N = N->getOperand(0).getNode();
12304     if (N->getOpcode() == ISD::INLINEASM ||
12305         N->getOpcode() == ISD::INLINEASM_BR)
12306       return true;
12307   } while (N->getOpcode() == ISD::CopyFromReg);
12308   return false;
12309 }
12310 
12311 bool SITargetLowering::isSDNodeSourceOfDivergence(
12312     const SDNode *N, FunctionLoweringInfo *FLI,
12313     LegacyDivergenceAnalysis *KDA) const {
12314   switch (N->getOpcode()) {
12315   case ISD::CopyFromReg: {
12316     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12317     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12318     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12319     Register Reg = R->getReg();
12320 
12321     // FIXME: Why does this need to consider isLiveIn?
12322     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12323       return !TRI->isSGPRReg(MRI, Reg);
12324 
12325     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12326       return KDA->isDivergent(V);
12327 
12328     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12329     return !TRI->isSGPRReg(MRI, Reg);
12330   }
12331   case ISD::LOAD: {
12332     const LoadSDNode *L = cast<LoadSDNode>(N);
12333     unsigned AS = L->getAddressSpace();
12334     // A flat load may access private memory.
12335     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12336   }
12337   case ISD::CALLSEQ_END:
12338     return true;
12339   case ISD::INTRINSIC_WO_CHAIN:
12340     return AMDGPU::isIntrinsicSourceOfDivergence(
12341         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12342   case ISD::INTRINSIC_W_CHAIN:
12343     return AMDGPU::isIntrinsicSourceOfDivergence(
12344         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12345   case AMDGPUISD::ATOMIC_CMP_SWAP:
12346   case AMDGPUISD::ATOMIC_INC:
12347   case AMDGPUISD::ATOMIC_DEC:
12348   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12349   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12350   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12351   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12352   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12353   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12354   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12355   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12356   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12357   case AMDGPUISD::BUFFER_ATOMIC_AND:
12358   case AMDGPUISD::BUFFER_ATOMIC_OR:
12359   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12360   case AMDGPUISD::BUFFER_ATOMIC_INC:
12361   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12362   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12363   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12364   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12365   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12366   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12367     // Target-specific read-modify-write atomics are sources of divergence.
12368     return true;
12369   default:
12370     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12371       // Generic read-modify-write atomics are sources of divergence.
12372       return A->readMem() && A->writeMem();
12373     }
12374     return false;
12375   }
12376 }
12377 
12378 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12379                                                EVT VT) const {
12380   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12381   case MVT::f32:
12382     return hasFP32Denormals(DAG.getMachineFunction());
12383   case MVT::f64:
12384   case MVT::f16:
12385     return hasFP64FP16Denormals(DAG.getMachineFunction());
12386   default:
12387     return false;
12388   }
12389 }
12390 
12391 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12392                                                MachineFunction &MF) const {
12393   switch (Ty.getScalarSizeInBits()) {
12394   case 32:
12395     return hasFP32Denormals(MF);
12396   case 64:
12397   case 16:
12398     return hasFP64FP16Denormals(MF);
12399   default:
12400     return false;
12401   }
12402 }
12403 
12404 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12405                                                     const SelectionDAG &DAG,
12406                                                     bool SNaN,
12407                                                     unsigned Depth) const {
12408   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12409     const MachineFunction &MF = DAG.getMachineFunction();
12410     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12411 
12412     if (Info->getMode().DX10Clamp)
12413       return true; // Clamped to 0.
12414     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12415   }
12416 
12417   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12418                                                             SNaN, Depth);
12419 }
12420 
12421 // Global FP atomic instructions have a hardcoded FP mode and do not support
12422 // FP32 denormals, and only support v2f16 denormals.
12423 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12424   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12425   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12426   if (&Flt == &APFloat::IEEEsingle())
12427     return DenormMode == DenormalMode::getPreserveSign();
12428   return DenormMode == DenormalMode::getIEEE();
12429 }
12430 
12431 TargetLowering::AtomicExpansionKind
12432 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12433   unsigned AS = RMW->getPointerAddressSpace();
12434   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12435     return AtomicExpansionKind::NotAtomic;
12436 
12437   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12438     OptimizationRemarkEmitter ORE(RMW->getFunction());
12439     LLVMContext &Ctx = RMW->getFunction()->getContext();
12440     SmallVector<StringRef> SSNs;
12441     Ctx.getSyncScopeNames(SSNs);
12442     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12443                         ? "system"
12444                         : SSNs[RMW->getSyncScopeID()];
12445     ORE.emit([&]() {
12446       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12447              << "Hardware instruction generated for atomic "
12448              << RMW->getOperationName(RMW->getOperation())
12449              << " operation at memory scope " << MemScope
12450              << " due to an unsafe request.";
12451     });
12452     return Kind;
12453   };
12454 
12455   switch (RMW->getOperation()) {
12456   case AtomicRMWInst::FAdd: {
12457     Type *Ty = RMW->getType();
12458 
12459     // We don't have a way to support 16-bit atomics now, so just leave them
12460     // as-is.
12461     if (Ty->isHalfTy())
12462       return AtomicExpansionKind::None;
12463 
12464     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12465       return AtomicExpansionKind::CmpXChg;
12466 
12467     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12468          Subtarget->hasAtomicFaddInsts()) {
12469       if (Subtarget->hasGFX940Insts())
12470         return AtomicExpansionKind::None;
12471 
12472       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12473       // floating point atomic instructions. May generate more efficient code,
12474       // but may not respect rounding and denormal modes, and may give incorrect
12475       // results for certain memory destinations.
12476       if (RMW->getFunction()
12477               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12478               .getValueAsString() != "true")
12479         return AtomicExpansionKind::CmpXChg;
12480 
12481       if (Subtarget->hasGFX90AInsts()) {
12482         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12483           return AtomicExpansionKind::CmpXChg;
12484 
12485         auto SSID = RMW->getSyncScopeID();
12486         if (SSID == SyncScope::System ||
12487             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12488           return AtomicExpansionKind::CmpXChg;
12489 
12490         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12491       }
12492 
12493       if (AS == AMDGPUAS::FLAT_ADDRESS)
12494         return AtomicExpansionKind::CmpXChg;
12495 
12496       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12497                               : AtomicExpansionKind::CmpXChg;
12498     }
12499 
12500     // DS FP atomics do respect the denormal mode, but the rounding mode is
12501     // fixed to round-to-nearest-even.
12502     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12503     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12504       if (!Ty->isDoubleTy())
12505         return AtomicExpansionKind::None;
12506 
12507       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12508         return AtomicExpansionKind::None;
12509 
12510       return RMW->getFunction()
12511                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12512                          .getValueAsString() == "true"
12513                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12514                  : AtomicExpansionKind::CmpXChg;
12515     }
12516 
12517     return AtomicExpansionKind::CmpXChg;
12518   }
12519   default:
12520     break;
12521   }
12522 
12523   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12524 }
12525 
12526 TargetLowering::AtomicExpansionKind
12527 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12528   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12529              ? AtomicExpansionKind::NotAtomic
12530              : AtomicExpansionKind::None;
12531 }
12532 
12533 TargetLowering::AtomicExpansionKind
12534 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12535   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12536              ? AtomicExpansionKind::NotAtomic
12537              : AtomicExpansionKind::None;
12538 }
12539 
12540 TargetLowering::AtomicExpansionKind
12541 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12542   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12543              ? AtomicExpansionKind::NotAtomic
12544              : AtomicExpansionKind::None;
12545 }
12546 
12547 const TargetRegisterClass *
12548 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12549   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12550   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12551   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12552     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12553                                                : &AMDGPU::SReg_32RegClass;
12554   if (!TRI->isSGPRClass(RC) && !isDivergent)
12555     return TRI->getEquivalentSGPRClass(RC);
12556   else if (TRI->isSGPRClass(RC) && isDivergent)
12557     return TRI->getEquivalentVGPRClass(RC);
12558 
12559   return RC;
12560 }
12561 
12562 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12563 // uniform values (as produced by the mask results of control flow intrinsics)
12564 // used outside of divergent blocks. The phi users need to also be treated as
12565 // always uniform.
12566 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12567                       unsigned WaveSize) {
12568   // FIXME: We assume we never cast the mask results of a control flow
12569   // intrinsic.
12570   // Early exit if the type won't be consistent as a compile time hack.
12571   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12572   if (!IT || IT->getBitWidth() != WaveSize)
12573     return false;
12574 
12575   if (!isa<Instruction>(V))
12576     return false;
12577   if (!Visited.insert(V).second)
12578     return false;
12579   bool Result = false;
12580   for (auto U : V->users()) {
12581     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12582       if (V == U->getOperand(1)) {
12583         switch (Intrinsic->getIntrinsicID()) {
12584         default:
12585           Result = false;
12586           break;
12587         case Intrinsic::amdgcn_if_break:
12588         case Intrinsic::amdgcn_if:
12589         case Intrinsic::amdgcn_else:
12590           Result = true;
12591           break;
12592         }
12593       }
12594       if (V == U->getOperand(0)) {
12595         switch (Intrinsic->getIntrinsicID()) {
12596         default:
12597           Result = false;
12598           break;
12599         case Intrinsic::amdgcn_end_cf:
12600         case Intrinsic::amdgcn_loop:
12601           Result = true;
12602           break;
12603         }
12604       }
12605     } else {
12606       Result = hasCFUser(U, Visited, WaveSize);
12607     }
12608     if (Result)
12609       break;
12610   }
12611   return Result;
12612 }
12613 
12614 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12615                                                const Value *V) const {
12616   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12617     if (CI->isInlineAsm()) {
12618       // FIXME: This cannot give a correct answer. This should only trigger in
12619       // the case where inline asm returns mixed SGPR and VGPR results, used
12620       // outside the defining block. We don't have a specific result to
12621       // consider, so this assumes if any value is SGPR, the overall register
12622       // also needs to be SGPR.
12623       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12624       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12625           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12626       for (auto &TC : TargetConstraints) {
12627         if (TC.Type == InlineAsm::isOutput) {
12628           ComputeConstraintToUse(TC, SDValue());
12629           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12630               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12631           if (RC && SIRI->isSGPRClass(RC))
12632             return true;
12633         }
12634       }
12635     }
12636   }
12637   SmallPtrSet<const Value *, 16> Visited;
12638   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12639 }
12640 
12641 std::pair<InstructionCost, MVT>
12642 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12643                                           Type *Ty) const {
12644   std::pair<InstructionCost, MVT> Cost =
12645       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12646   auto Size = DL.getTypeSizeInBits(Ty);
12647   // Maximum load or store can handle 8 dwords for scalar and 4 for
12648   // vector ALU. Let's assume anything above 8 dwords is expensive
12649   // even if legal.
12650   if (Size <= 256)
12651     return Cost;
12652 
12653   Cost.first += (Size + 255) / 256;
12654   return Cost;
12655 }
12656 
12657 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12658   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12659   for (; I != E; ++I) {
12660     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12661       if (getBasePtrIndex(M) == I.getOperandNo())
12662         return true;
12663     }
12664   }
12665   return false;
12666 }
12667 
12668 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12669                                            SDValue N1) const {
12670   if (!N0.hasOneUse())
12671     return false;
12672   // Take care of the opportunity to keep N0 uniform
12673   if (N0->isDivergent() || !N1->isDivergent())
12674     return true;
12675   // Check if we have a good chance to form the memory access pattern with the
12676   // base and offset
12677   return (DAG.isBaseWithConstantOffset(N0) &&
12678           hasMemSDNodeUser(*N0->use_begin()));
12679 }
12680 
12681 MachineMemOperand::Flags
12682 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12683   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12684   if (I.getMetadata("amdgpu.noclobber"))
12685     return MONoClobber;
12686   return MachineMemOperand::MONone;
12687 }
12688