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 "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "Utils/AMDGPUBaseInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/DAGCombine.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineLoopInfo.h"
45 #include "llvm/CodeGen/MachineMemOperand.h"
46 #include "llvm/CodeGen/MachineModuleInfo.h"
47 #include "llvm/CodeGen/MachineOperand.h"
48 #include "llvm/CodeGen/MachineRegisterInfo.h"
49 #include "llvm/CodeGen/SelectionDAG.h"
50 #include "llvm/CodeGen/SelectionDAGNodes.h"
51 #include "llvm/CodeGen/TargetCallingConv.h"
52 #include "llvm/CodeGen/TargetRegisterInfo.h"
53 #include "llvm/CodeGen/ValueTypes.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/DiagnosticInfo.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/KnownBits.h"
72 #include "llvm/Support/MachineValueType.h"
73 #include "llvm/Support/MathExtras.h"
74 #include "llvm/Target/TargetOptions.h"
75 #include <cassert>
76 #include <cmath>
77 #include <cstdint>
78 #include <iterator>
79 #include <tuple>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 #define DEBUG_TYPE "si-lower"
86 
87 STATISTIC(NumTailCalls, "Number of tail calls");
88 
89 static cl::opt<bool> DisableLoopAlignment(
90   "amdgpu-disable-loop-alignment",
91   cl::desc("Do not align and prefetch loops"),
92   cl::init(false));
93 
94 static cl::opt<bool> VGPRReserveforSGPRSpill(
95     "amdgpu-reserve-vgpr-for-sgpr-spill",
96     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
97 
98 static cl::opt<bool> UseDivergentRegisterIndexing(
99   "amdgpu-use-divergent-register-indexing",
100   cl::Hidden,
101   cl::desc("Use indirect register addressing for divergent indexes"),
102   cl::init(false));
103 
104 static bool hasFP32Denormals(const MachineFunction &MF) {
105   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
106   return Info->getMode().allFP32Denormals();
107 }
108 
109 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
110   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
111   return Info->getMode().allFP64FP16Denormals();
112 }
113 
114 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
115   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
116   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
117     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
118       return AMDGPU::SGPR0 + Reg;
119     }
120   }
121   llvm_unreachable("Cannot allocate sgpr");
122 }
123 
124 SITargetLowering::SITargetLowering(const TargetMachine &TM,
125                                    const GCNSubtarget &STI)
126     : AMDGPUTargetLowering(TM, STI),
127       Subtarget(&STI) {
128   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
129   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
130 
131   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
132   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
133 
134   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
135   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
136   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
137 
138   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
139   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
140 
141   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
142   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
143 
144   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
145   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
146 
147   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
148   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
149 
150   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
151   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
152 
153   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
154   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
155 
156   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
157   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
158 
159   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
160   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
161 
162   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
163   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
164 
165   if (Subtarget->has16BitInsts()) {
166     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
167     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
168 
169     // Unless there are also VOP3P operations, not operations are really legal.
170     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
171     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
172     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
173     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
174   }
175 
176   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
177   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
178 
179   computeRegisterProperties(Subtarget->getRegisterInfo());
180 
181   // The boolean content concept here is too inflexible. Compares only ever
182   // really produce a 1-bit result. Any copy/extend from these will turn into a
183   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
184   // it's what most targets use.
185   setBooleanContents(ZeroOrOneBooleanContent);
186   setBooleanVectorContents(ZeroOrOneBooleanContent);
187 
188   // We need to custom lower vector stores from local memory
189   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
190   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::i1, Custom);
196   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
197 
198   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
199   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
204   setOperationAction(ISD::STORE, MVT::i1, Custom);
205   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
206 
207   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
208   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
209   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
210   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
211   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
212   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
213   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
214   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
215   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
216   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
217   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
218   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
219   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
220   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
221   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
222   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
223 
224   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
225   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
227   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
228   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
229 
230   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
231   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
232 
233   setOperationAction(ISD::SELECT, MVT::i1, Promote);
234   setOperationAction(ISD::SELECT, MVT::i64, Custom);
235   setOperationAction(ISD::SELECT, MVT::f64, Promote);
236   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
237 
238   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
239   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
242   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
243 
244   setOperationAction(ISD::SETCC, MVT::i1, Promote);
245   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
246   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
247   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
248 
249   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
250   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
251   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
252   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
253   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
254   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
255   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
256   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
257 
258   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
266 
267   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
268   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
269   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
270   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
271   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
272   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
273 
274   setOperationAction(ISD::UADDO, MVT::i32, Legal);
275   setOperationAction(ISD::USUBO, MVT::i32, Legal);
276 
277   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
278   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
279 
280   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
281   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
282   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
283 
284 #if 0
285   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
286   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
287 #endif
288 
289   // We only support LOAD/STORE and vector manipulation ops for vectors
290   // with > 4 elements.
291   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
292                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
293                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
294                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
295     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
296       switch (Op) {
297       case ISD::LOAD:
298       case ISD::STORE:
299       case ISD::BUILD_VECTOR:
300       case ISD::BITCAST:
301       case ISD::EXTRACT_VECTOR_ELT:
302       case ISD::INSERT_VECTOR_ELT:
303       case ISD::INSERT_SUBVECTOR:
304       case ISD::EXTRACT_SUBVECTOR:
305       case ISD::SCALAR_TO_VECTOR:
306         break;
307       case ISD::CONCAT_VECTORS:
308         setOperationAction(Op, VT, Custom);
309         break;
310       default:
311         setOperationAction(Op, VT, Expand);
312         break;
313       }
314     }
315   }
316 
317   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
318 
319   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
320   // is expanded to avoid having two separate loops in case the index is a VGPR.
321 
322   // Most operations are naturally 32-bit vector operations. We only support
323   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
324   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
325     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
326     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
327 
328     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
329     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
330 
331     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
332     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
333 
334     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
335     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
336   }
337 
338   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
339     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
340     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
341 
342     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
343     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
344 
345     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
346     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
347 
348     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
349     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
350   }
351 
352   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
353     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
354     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
355 
356     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
357     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
358 
359     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
360     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
361 
362     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
363     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
364   }
365 
366   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
367     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
368     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
369 
370     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
371     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
372 
373     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
374     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
375 
376     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
377     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
378   }
379 
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
383   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
384 
385   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
386   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
387 
388   // Avoid stack access for these.
389   // TODO: Generalize to more vector types.
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
394 
395   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
400 
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
403   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
404 
405   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
406   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
407   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
408   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
409 
410   // Deal with vec3 vector operations when widened to vec4.
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
415 
416   // Deal with vec5 vector operations when widened to vec8.
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
420   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
421 
422   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
423   // and output demarshalling
424   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
425   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
426 
427   // We can't return success/failure, only the old value,
428   // let LLVM add the comparison
429   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
430   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
431 
432   if (Subtarget->hasFlatAddressSpace()) {
433     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
434     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
435   }
436 
437   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
438 
439   // FIXME: This should be narrowed to i32, but that only happens if i64 is
440   // illegal.
441   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
442   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
443   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
444 
445   // On SI this is s_memtime and s_memrealtime on VI.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
447   setOperationAction(ISD::TRAP, MVT::Other, Custom);
448   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
449 
450   if (Subtarget->has16BitInsts()) {
451     setOperationAction(ISD::FPOW, MVT::f16, Promote);
452     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
453     setOperationAction(ISD::FLOG, MVT::f16, Custom);
454     setOperationAction(ISD::FEXP, MVT::f16, Custom);
455     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
456   }
457 
458   if (Subtarget->hasMadMacF32Insts())
459     setOperationAction(ISD::FMAD, MVT::f32, Legal);
460 
461   if (!Subtarget->hasBFI()) {
462     // fcopysign can be done in a single instruction with BFI.
463     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
464     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465   }
466 
467   if (!Subtarget->hasBCNT(32))
468     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
469 
470   if (!Subtarget->hasBCNT(64))
471     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
472 
473   if (Subtarget->hasFFBH())
474     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
475 
476   if (Subtarget->hasFFBL())
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
478 
479   // We only really have 32-bit BFE instructions (and 16-bit on VI).
480   //
481   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
482   // effort to match them now. We want this to be false for i64 cases when the
483   // extraction isn't restricted to the upper or lower half. Ideally we would
484   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
485   // span the midpoint are probably relatively rare, so don't worry about them
486   // for now.
487   if (Subtarget->hasBFE())
488     setHasExtractBitsInsn(true);
489 
490   // Clamp modifier on add/sub
491   if (Subtarget->hasIntClamp()) {
492     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
493     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
494   }
495 
496   if (Subtarget->hasAddNoCarry()) {
497     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
498     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
500     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
501   }
502 
503   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
504   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
506   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
507 
508 
509   // These are really only legal for ieee_mode functions. We should be avoiding
510   // them for functions that don't have ieee_mode enabled, so just say they are
511   // legal.
512   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
513   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
515   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
516 
517 
518   if (Subtarget->haveRoundOpsF64()) {
519     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
520     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
521     setOperationAction(ISD::FRINT, MVT::f64, Legal);
522   } else {
523     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
524     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
525     setOperationAction(ISD::FRINT, MVT::f64, Custom);
526     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
527   }
528 
529   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
530 
531   setOperationAction(ISD::FSIN, MVT::f32, Custom);
532   setOperationAction(ISD::FCOS, MVT::f32, Custom);
533   setOperationAction(ISD::FDIV, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f64, Custom);
535 
536   if (Subtarget->has16BitInsts()) {
537     setOperationAction(ISD::Constant, MVT::i16, Legal);
538 
539     setOperationAction(ISD::SMIN, MVT::i16, Legal);
540     setOperationAction(ISD::SMAX, MVT::i16, Legal);
541 
542     setOperationAction(ISD::UMIN, MVT::i16, Legal);
543     setOperationAction(ISD::UMAX, MVT::i16, Legal);
544 
545     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
546     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
547 
548     setOperationAction(ISD::ROTR, MVT::i16, Promote);
549     setOperationAction(ISD::ROTL, MVT::i16, Promote);
550 
551     setOperationAction(ISD::SDIV, MVT::i16, Promote);
552     setOperationAction(ISD::UDIV, MVT::i16, Promote);
553     setOperationAction(ISD::SREM, MVT::i16, Promote);
554     setOperationAction(ISD::UREM, MVT::i16, Promote);
555     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
556     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
557 
558     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
559 
560     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
562     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
564     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
565 
566     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
567 
568     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
569 
570     setOperationAction(ISD::LOAD, MVT::i16, Custom);
571 
572     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
573 
574     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
575     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
576     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
577     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
578 
579     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
580     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
581 
582     // F16 - Constant Actions.
583     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
584 
585     // F16 - Load/Store Actions.
586     setOperationAction(ISD::LOAD, MVT::f16, Promote);
587     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
588     setOperationAction(ISD::STORE, MVT::f16, Promote);
589     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
590 
591     // F16 - VOP1 Actions.
592     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
593     setOperationAction(ISD::FCOS, MVT::f16, Custom);
594     setOperationAction(ISD::FSIN, MVT::f16, Custom);
595 
596     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
597     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
598 
599     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
600     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
601     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
602     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::FROUND, MVT::f16, Custom);
604 
605     // F16 - VOP2 Actions.
606     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
607     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
608 
609     setOperationAction(ISD::FDIV, MVT::f16, Custom);
610 
611     // F16 - VOP3 Actions.
612     setOperationAction(ISD::FMA, MVT::f16, Legal);
613     if (STI.hasMadF16())
614       setOperationAction(ISD::FMAD, MVT::f16, Legal);
615 
616     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
617       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
618         switch (Op) {
619         case ISD::LOAD:
620         case ISD::STORE:
621         case ISD::BUILD_VECTOR:
622         case ISD::BITCAST:
623         case ISD::EXTRACT_VECTOR_ELT:
624         case ISD::INSERT_VECTOR_ELT:
625         case ISD::INSERT_SUBVECTOR:
626         case ISD::EXTRACT_SUBVECTOR:
627         case ISD::SCALAR_TO_VECTOR:
628           break;
629         case ISD::CONCAT_VECTORS:
630           setOperationAction(Op, VT, Custom);
631           break;
632         default:
633           setOperationAction(Op, VT, Expand);
634           break;
635         }
636       }
637     }
638 
639     // v_perm_b32 can handle either of these.
640     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
641     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
643 
644     // XXX - Do these do anything? Vector constants turn into build_vector.
645     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
646     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
647 
648     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
649     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
650 
651     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
652     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
653     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
655 
656     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
657     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
658     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
659     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
660 
661     setOperationAction(ISD::AND, MVT::v2i16, Promote);
662     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
663     setOperationAction(ISD::OR, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
665     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
667 
668     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
669     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
670     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
671     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
672 
673     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
674     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
675     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
676     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
677 
678     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
679     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
682 
683     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
684     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
686 
687     if (!Subtarget->hasVOP3PInsts()) {
688       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
690     }
691 
692     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
693     // This isn't really legal, but this avoids the legalizer unrolling it (and
694     // allows matching fneg (fabs x) patterns)
695     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
696 
697     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
698     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
700     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
701 
702     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
703     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
704 
705     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
706     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
707   }
708 
709   if (Subtarget->hasVOP3PInsts()) {
710     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
711     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
712     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
713     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
716     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
717     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
719     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
720 
721     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
722     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
725 
726     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
727     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
729 
730     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
731     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
732 
733     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
734 
735     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
737 
738     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
740 
741     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
742     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
744     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
745     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
746     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
747 
748     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
749     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
750     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
752 
753     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
754     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
757 
758     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
759     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
761 
762     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
763     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
764 
765     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
766     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
768 
769     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
770     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
772   }
773 
774   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
775   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
776 
777   if (Subtarget->has16BitInsts()) {
778     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
779     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
780     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
781     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
782   } else {
783     // Legalization hack.
784     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
785     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
786 
787     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
788     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
789   }
790 
791   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
792     setOperationAction(ISD::SELECT, VT, Custom);
793   }
794 
795   setOperationAction(ISD::SMULO, MVT::i64, Custom);
796   setOperationAction(ISD::UMULO, MVT::i64, Custom);
797 
798   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
799   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
801   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
802   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
803   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
804   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
805 
806   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
807   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
808   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
809   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
810   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
811   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
812   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
813   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
814   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
815 
816   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
817   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
818   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
819   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
820   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
821   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
822   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
823   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
824 
825   setTargetDAGCombine(ISD::ADD);
826   setTargetDAGCombine(ISD::ADDCARRY);
827   setTargetDAGCombine(ISD::SUB);
828   setTargetDAGCombine(ISD::SUBCARRY);
829   setTargetDAGCombine(ISD::FADD);
830   setTargetDAGCombine(ISD::FSUB);
831   setTargetDAGCombine(ISD::FMINNUM);
832   setTargetDAGCombine(ISD::FMAXNUM);
833   setTargetDAGCombine(ISD::FMINNUM_IEEE);
834   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
835   setTargetDAGCombine(ISD::FMA);
836   setTargetDAGCombine(ISD::SMIN);
837   setTargetDAGCombine(ISD::SMAX);
838   setTargetDAGCombine(ISD::UMIN);
839   setTargetDAGCombine(ISD::UMAX);
840   setTargetDAGCombine(ISD::SETCC);
841   setTargetDAGCombine(ISD::AND);
842   setTargetDAGCombine(ISD::OR);
843   setTargetDAGCombine(ISD::XOR);
844   setTargetDAGCombine(ISD::SINT_TO_FP);
845   setTargetDAGCombine(ISD::UINT_TO_FP);
846   setTargetDAGCombine(ISD::FCANONICALIZE);
847   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
848   setTargetDAGCombine(ISD::ZERO_EXTEND);
849   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
850   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
851   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
852 
853   // All memory operations. Some folding on the pointer operand is done to help
854   // matching the constant offsets in the addressing modes.
855   setTargetDAGCombine(ISD::LOAD);
856   setTargetDAGCombine(ISD::STORE);
857   setTargetDAGCombine(ISD::ATOMIC_LOAD);
858   setTargetDAGCombine(ISD::ATOMIC_STORE);
859   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
860   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
861   setTargetDAGCombine(ISD::ATOMIC_SWAP);
862   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
863   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
864   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
865   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
866   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
867   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
868   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
869   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
870   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
871   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
872   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
873 
874   // FIXME: In other contexts we pretend this is a per-function property.
875   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
876 
877   setSchedulingPreference(Sched::RegPressure);
878 }
879 
880 const GCNSubtarget *SITargetLowering::getSubtarget() const {
881   return Subtarget;
882 }
883 
884 //===----------------------------------------------------------------------===//
885 // TargetLowering queries
886 //===----------------------------------------------------------------------===//
887 
888 // v_mad_mix* support a conversion from f16 to f32.
889 //
890 // There is only one special case when denormals are enabled we don't currently,
891 // where this is OK to use.
892 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
893                                        EVT DestVT, EVT SrcVT) const {
894   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
895           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
896     DestVT.getScalarType() == MVT::f32 &&
897     SrcVT.getScalarType() == MVT::f16 &&
898     // TODO: This probably only requires no input flushing?
899     !hasFP32Denormals(DAG.getMachineFunction());
900 }
901 
902 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
903   // SI has some legal vector types, but no legal vector operations. Say no
904   // shuffles are legal in order to prefer scalarizing some vector operations.
905   return false;
906 }
907 
908 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
909                                                     CallingConv::ID CC,
910                                                     EVT VT) const {
911   if (CC == CallingConv::AMDGPU_KERNEL)
912     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
913 
914   if (VT.isVector()) {
915     EVT ScalarVT = VT.getScalarType();
916     unsigned Size = ScalarVT.getSizeInBits();
917     if (Size == 32)
918       return ScalarVT.getSimpleVT();
919 
920     if (Size > 32)
921       return MVT::i32;
922 
923     if (Size == 16 && Subtarget->has16BitInsts())
924       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
925   } else if (VT.getSizeInBits() > 32)
926     return MVT::i32;
927 
928   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
929 }
930 
931 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
932                                                          CallingConv::ID CC,
933                                                          EVT VT) const {
934   if (CC == CallingConv::AMDGPU_KERNEL)
935     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
936 
937   if (VT.isVector()) {
938     unsigned NumElts = VT.getVectorNumElements();
939     EVT ScalarVT = VT.getScalarType();
940     unsigned Size = ScalarVT.getSizeInBits();
941 
942     if (Size == 32)
943       return NumElts;
944 
945     if (Size > 32)
946       return NumElts * ((Size + 31) / 32);
947 
948     if (Size == 16 && Subtarget->has16BitInsts())
949       return (NumElts + 1) / 2;
950   } else if (VT.getSizeInBits() > 32)
951     return (VT.getSizeInBits() + 31) / 32;
952 
953   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
954 }
955 
956 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
957   LLVMContext &Context, CallingConv::ID CC,
958   EVT VT, EVT &IntermediateVT,
959   unsigned &NumIntermediates, MVT &RegisterVT) const {
960   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
961     unsigned NumElts = VT.getVectorNumElements();
962     EVT ScalarVT = VT.getScalarType();
963     unsigned Size = ScalarVT.getSizeInBits();
964     if (Size == 32) {
965       RegisterVT = ScalarVT.getSimpleVT();
966       IntermediateVT = RegisterVT;
967       NumIntermediates = NumElts;
968       return NumIntermediates;
969     }
970 
971     if (Size > 32) {
972       RegisterVT = MVT::i32;
973       IntermediateVT = RegisterVT;
974       NumIntermediates = NumElts * ((Size + 31) / 32);
975       return NumIntermediates;
976     }
977 
978     // FIXME: We should fix the ABI to be the same on targets without 16-bit
979     // support, but unless we can properly handle 3-vectors, it will be still be
980     // inconsistent.
981     if (Size == 16 && Subtarget->has16BitInsts()) {
982       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
983       IntermediateVT = RegisterVT;
984       NumIntermediates = (NumElts + 1) / 2;
985       return NumIntermediates;
986     }
987   }
988 
989   return TargetLowering::getVectorTypeBreakdownForCallingConv(
990     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
991 }
992 
993 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
994   assert(DMaskLanes != 0);
995 
996   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
997     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
998     return EVT::getVectorVT(Ty->getContext(),
999                             EVT::getEVT(VT->getElementType()),
1000                             NumElts);
1001   }
1002 
1003   return EVT::getEVT(Ty);
1004 }
1005 
1006 // Peek through TFE struct returns to only use the data size.
1007 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1008   auto *ST = dyn_cast<StructType>(Ty);
1009   if (!ST)
1010     return memVTFromImageData(Ty, DMaskLanes);
1011 
1012   // Some intrinsics return an aggregate type - special case to work out the
1013   // correct memVT.
1014   //
1015   // Only limited forms of aggregate type currently expected.
1016   if (ST->getNumContainedTypes() != 2 ||
1017       !ST->getContainedType(1)->isIntegerTy(32))
1018     return EVT();
1019   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1020 }
1021 
1022 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1023                                           const CallInst &CI,
1024                                           MachineFunction &MF,
1025                                           unsigned IntrID) const {
1026   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1027           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1028     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1029                                                   (Intrinsic::ID)IntrID);
1030     if (Attr.hasFnAttribute(Attribute::ReadNone))
1031       return false;
1032 
1033     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1034 
1035     if (RsrcIntr->IsImage) {
1036       Info.ptrVal = MFI->getImagePSV(
1037         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1038         CI.getArgOperand(RsrcIntr->RsrcArg));
1039       Info.align.reset();
1040     } else {
1041       Info.ptrVal = MFI->getBufferPSV(
1042         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1043         CI.getArgOperand(RsrcIntr->RsrcArg));
1044     }
1045 
1046     Info.flags = MachineMemOperand::MODereferenceable;
1047     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1048       unsigned DMaskLanes = 4;
1049 
1050       if (RsrcIntr->IsImage) {
1051         const AMDGPU::ImageDimIntrinsicInfo *Intr
1052           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1053         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1054           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1055 
1056         if (!BaseOpcode->Gather4) {
1057           // If this isn't a gather, we may have excess loaded elements in the
1058           // IR type. Check the dmask for the real number of elements loaded.
1059           unsigned DMask
1060             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1061           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1062         }
1063 
1064         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1065       } else
1066         Info.memVT = EVT::getEVT(CI.getType());
1067 
1068       // FIXME: What does alignment mean for an image?
1069       Info.opc = ISD::INTRINSIC_W_CHAIN;
1070       Info.flags |= MachineMemOperand::MOLoad;
1071     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1072       Info.opc = ISD::INTRINSIC_VOID;
1073 
1074       Type *DataTy = CI.getArgOperand(0)->getType();
1075       if (RsrcIntr->IsImage) {
1076         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1077         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1078         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1079       } else
1080         Info.memVT = EVT::getEVT(DataTy);
1081 
1082       Info.flags |= MachineMemOperand::MOStore;
1083     } else {
1084       // Atomic
1085       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1086                                             ISD::INTRINSIC_W_CHAIN;
1087       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1088       Info.flags = MachineMemOperand::MOLoad |
1089                    MachineMemOperand::MOStore |
1090                    MachineMemOperand::MODereferenceable;
1091 
1092       // XXX - Should this be volatile without known ordering?
1093       Info.flags |= MachineMemOperand::MOVolatile;
1094     }
1095     return true;
1096   }
1097 
1098   switch (IntrID) {
1099   case Intrinsic::amdgcn_atomic_inc:
1100   case Intrinsic::amdgcn_atomic_dec:
1101   case Intrinsic::amdgcn_ds_ordered_add:
1102   case Intrinsic::amdgcn_ds_ordered_swap:
1103   case Intrinsic::amdgcn_ds_fadd:
1104   case Intrinsic::amdgcn_ds_fmin:
1105   case Intrinsic::amdgcn_ds_fmax: {
1106     Info.opc = ISD::INTRINSIC_W_CHAIN;
1107     Info.memVT = MVT::getVT(CI.getType());
1108     Info.ptrVal = CI.getOperand(0);
1109     Info.align.reset();
1110     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1111 
1112     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1113     if (!Vol->isZero())
1114       Info.flags |= MachineMemOperand::MOVolatile;
1115 
1116     return true;
1117   }
1118   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1119     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1120 
1121     Info.opc = ISD::INTRINSIC_VOID;
1122     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1123     Info.ptrVal = MFI->getBufferPSV(
1124       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1125       CI.getArgOperand(1));
1126     Info.align.reset();
1127     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1128 
1129     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1130     if (!Vol || !Vol->isZero())
1131       Info.flags |= MachineMemOperand::MOVolatile;
1132 
1133     return true;
1134   }
1135   case Intrinsic::amdgcn_global_atomic_fadd: {
1136     Info.opc = ISD::INTRINSIC_VOID;
1137     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1138                             ->getPointerElementType());
1139     Info.ptrVal = CI.getOperand(0);
1140     Info.align.reset();
1141     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1142 
1143     return true;
1144   }
1145   case Intrinsic::amdgcn_ds_append:
1146   case Intrinsic::amdgcn_ds_consume: {
1147     Info.opc = ISD::INTRINSIC_W_CHAIN;
1148     Info.memVT = MVT::getVT(CI.getType());
1149     Info.ptrVal = CI.getOperand(0);
1150     Info.align.reset();
1151     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1152 
1153     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1154     if (!Vol->isZero())
1155       Info.flags |= MachineMemOperand::MOVolatile;
1156 
1157     return true;
1158   }
1159   case Intrinsic::amdgcn_global_atomic_csub: {
1160     Info.opc = ISD::INTRINSIC_W_CHAIN;
1161     Info.memVT = MVT::getVT(CI.getType());
1162     Info.ptrVal = CI.getOperand(0);
1163     Info.align.reset();
1164     Info.flags = MachineMemOperand::MOLoad |
1165                  MachineMemOperand::MOStore |
1166                  MachineMemOperand::MOVolatile;
1167     return true;
1168   }
1169   case Intrinsic::amdgcn_ds_gws_init:
1170   case Intrinsic::amdgcn_ds_gws_barrier:
1171   case Intrinsic::amdgcn_ds_gws_sema_v:
1172   case Intrinsic::amdgcn_ds_gws_sema_br:
1173   case Intrinsic::amdgcn_ds_gws_sema_p:
1174   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1175     Info.opc = ISD::INTRINSIC_VOID;
1176 
1177     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1178     Info.ptrVal =
1179         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1180 
1181     // This is an abstract access, but we need to specify a type and size.
1182     Info.memVT = MVT::i32;
1183     Info.size = 4;
1184     Info.align = Align(4);
1185 
1186     Info.flags = MachineMemOperand::MOStore;
1187     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1188       Info.flags = MachineMemOperand::MOLoad;
1189     return true;
1190   }
1191   default:
1192     return false;
1193   }
1194 }
1195 
1196 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1197                                             SmallVectorImpl<Value*> &Ops,
1198                                             Type *&AccessTy) const {
1199   switch (II->getIntrinsicID()) {
1200   case Intrinsic::amdgcn_atomic_inc:
1201   case Intrinsic::amdgcn_atomic_dec:
1202   case Intrinsic::amdgcn_ds_ordered_add:
1203   case Intrinsic::amdgcn_ds_ordered_swap:
1204   case Intrinsic::amdgcn_ds_append:
1205   case Intrinsic::amdgcn_ds_consume:
1206   case Intrinsic::amdgcn_ds_fadd:
1207   case Intrinsic::amdgcn_ds_fmin:
1208   case Intrinsic::amdgcn_ds_fmax:
1209   case Intrinsic::amdgcn_global_atomic_fadd:
1210   case Intrinsic::amdgcn_global_atomic_csub: {
1211     Value *Ptr = II->getArgOperand(0);
1212     AccessTy = II->getType();
1213     Ops.push_back(Ptr);
1214     return true;
1215   }
1216   default:
1217     return false;
1218   }
1219 }
1220 
1221 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1222   if (!Subtarget->hasFlatInstOffsets()) {
1223     // Flat instructions do not have offsets, and only have the register
1224     // address.
1225     return AM.BaseOffs == 0 && AM.Scale == 0;
1226   }
1227 
1228   return AM.Scale == 0 &&
1229          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1230                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1231                                   /*Signed=*/false));
1232 }
1233 
1234 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1235   if (Subtarget->hasFlatGlobalInsts())
1236     return AM.Scale == 0 &&
1237            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1238                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1239                                     /*Signed=*/true));
1240 
1241   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1242       // Assume the we will use FLAT for all global memory accesses
1243       // on VI.
1244       // FIXME: This assumption is currently wrong.  On VI we still use
1245       // MUBUF instructions for the r + i addressing mode.  As currently
1246       // implemented, the MUBUF instructions only work on buffer < 4GB.
1247       // It may be possible to support > 4GB buffers with MUBUF instructions,
1248       // by setting the stride value in the resource descriptor which would
1249       // increase the size limit to (stride * 4GB).  However, this is risky,
1250       // because it has never been validated.
1251     return isLegalFlatAddressingMode(AM);
1252   }
1253 
1254   return isLegalMUBUFAddressingMode(AM);
1255 }
1256 
1257 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1258   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1259   // additionally can do r + r + i with addr64. 32-bit has more addressing
1260   // mode options. Depending on the resource constant, it can also do
1261   // (i64 r0) + (i32 r1) * (i14 i).
1262   //
1263   // Private arrays end up using a scratch buffer most of the time, so also
1264   // assume those use MUBUF instructions. Scratch loads / stores are currently
1265   // implemented as mubuf instructions with offen bit set, so slightly
1266   // different than the normal addr64.
1267   if (!isUInt<12>(AM.BaseOffs))
1268     return false;
1269 
1270   // FIXME: Since we can split immediate into soffset and immediate offset,
1271   // would it make sense to allow any immediate?
1272 
1273   switch (AM.Scale) {
1274   case 0: // r + i or just i, depending on HasBaseReg.
1275     return true;
1276   case 1:
1277     return true; // We have r + r or r + i.
1278   case 2:
1279     if (AM.HasBaseReg) {
1280       // Reject 2 * r + r.
1281       return false;
1282     }
1283 
1284     // Allow 2 * r as r + r
1285     // Or  2 * r + i is allowed as r + r + i.
1286     return true;
1287   default: // Don't allow n * r
1288     return false;
1289   }
1290 }
1291 
1292 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1293                                              const AddrMode &AM, Type *Ty,
1294                                              unsigned AS, Instruction *I) const {
1295   // No global is ever allowed as a base.
1296   if (AM.BaseGV)
1297     return false;
1298 
1299   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1300     return isLegalGlobalAddressingMode(AM);
1301 
1302   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1303       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1304       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1305     // If the offset isn't a multiple of 4, it probably isn't going to be
1306     // correctly aligned.
1307     // FIXME: Can we get the real alignment here?
1308     if (AM.BaseOffs % 4 != 0)
1309       return isLegalMUBUFAddressingMode(AM);
1310 
1311     // There are no SMRD extloads, so if we have to do a small type access we
1312     // will use a MUBUF load.
1313     // FIXME?: We also need to do this if unaligned, but we don't know the
1314     // alignment here.
1315     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1316       return isLegalGlobalAddressingMode(AM);
1317 
1318     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1319       // SMRD instructions have an 8-bit, dword offset on SI.
1320       if (!isUInt<8>(AM.BaseOffs / 4))
1321         return false;
1322     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1323       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1324       // in 8-bits, it can use a smaller encoding.
1325       if (!isUInt<32>(AM.BaseOffs / 4))
1326         return false;
1327     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1328       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1329       if (!isUInt<20>(AM.BaseOffs))
1330         return false;
1331     } else
1332       llvm_unreachable("unhandled generation");
1333 
1334     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1335       return true;
1336 
1337     if (AM.Scale == 1 && AM.HasBaseReg)
1338       return true;
1339 
1340     return false;
1341 
1342   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1343     return isLegalMUBUFAddressingMode(AM);
1344   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1345              AS == AMDGPUAS::REGION_ADDRESS) {
1346     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1347     // field.
1348     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1349     // an 8-bit dword offset but we don't know the alignment here.
1350     if (!isUInt<16>(AM.BaseOffs))
1351       return false;
1352 
1353     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1354       return true;
1355 
1356     if (AM.Scale == 1 && AM.HasBaseReg)
1357       return true;
1358 
1359     return false;
1360   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1361              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1362     // For an unknown address space, this usually means that this is for some
1363     // reason being used for pure arithmetic, and not based on some addressing
1364     // computation. We don't have instructions that compute pointers with any
1365     // addressing modes, so treat them as having no offset like flat
1366     // instructions.
1367     return isLegalFlatAddressingMode(AM);
1368   }
1369 
1370   // Assume a user alias of global for unknown address spaces.
1371   return isLegalGlobalAddressingMode(AM);
1372 }
1373 
1374 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1375                                         const SelectionDAG &DAG) const {
1376   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1377     return (MemVT.getSizeInBits() <= 4 * 32);
1378   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1379     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1380     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1381   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1382     return (MemVT.getSizeInBits() <= 2 * 32);
1383   }
1384   return true;
1385 }
1386 
1387 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1388     unsigned Size, unsigned AddrSpace, Align Alignment,
1389     MachineMemOperand::Flags Flags, bool *IsFast) const {
1390   if (IsFast)
1391     *IsFast = false;
1392 
1393   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1394       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1395     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1396     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1397     // with adjacent offsets.
1398     bool AlignedBy4 = Alignment >= Align(4);
1399     if (IsFast)
1400       *IsFast = AlignedBy4;
1401 
1402     return AlignedBy4;
1403   }
1404 
1405   // FIXME: We have to be conservative here and assume that flat operations
1406   // will access scratch.  If we had access to the IR function, then we
1407   // could determine if any private memory was used in the function.
1408   if (!Subtarget->hasUnalignedScratchAccess() &&
1409       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1410        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1411     bool AlignedBy4 = Alignment >= Align(4);
1412     if (IsFast)
1413       *IsFast = AlignedBy4;
1414 
1415     return AlignedBy4;
1416   }
1417 
1418   if (Subtarget->hasUnalignedBufferAccess()) {
1419     // If we have an uniform constant load, it still requires using a slow
1420     // buffer instruction if unaligned.
1421     if (IsFast) {
1422       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1423       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1424       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1425                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1426         Alignment >= Align(4) : Alignment != Align(2);
1427     }
1428 
1429     return true;
1430   }
1431 
1432   // Smaller than dword value must be aligned.
1433   if (Size < 32)
1434     return false;
1435 
1436   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1437   // byte-address are ignored, thus forcing Dword alignment.
1438   // This applies to private, global, and constant memory.
1439   if (IsFast)
1440     *IsFast = true;
1441 
1442   return Size >= 32 && Alignment >= Align(4);
1443 }
1444 
1445 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1446     EVT VT, unsigned AddrSpace, unsigned Alignment,
1447     MachineMemOperand::Flags Flags, bool *IsFast) const {
1448   if (IsFast)
1449     *IsFast = false;
1450 
1451   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1452   // which isn't a simple VT.
1453   // Until MVT is extended to handle this, simply check for the size and
1454   // rely on the condition below: allow accesses if the size is a multiple of 4.
1455   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1456                            VT.getStoreSize() > 16)) {
1457     return false;
1458   }
1459 
1460   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1461                                             Align(Alignment), Flags, IsFast);
1462 }
1463 
1464 EVT SITargetLowering::getOptimalMemOpType(
1465     const MemOp &Op, const AttributeList &FuncAttributes) const {
1466   // FIXME: Should account for address space here.
1467 
1468   // The default fallback uses the private pointer size as a guess for a type to
1469   // use. Make sure we switch these to 64-bit accesses.
1470 
1471   if (Op.size() >= 16 &&
1472       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1473     return MVT::v4i32;
1474 
1475   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1476     return MVT::v2i32;
1477 
1478   // Use the default.
1479   return MVT::Other;
1480 }
1481 
1482 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1483   const MemSDNode *MemNode = cast<MemSDNode>(N);
1484   const Value *Ptr = MemNode->getMemOperand()->getValue();
1485   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1486   return I && I->getMetadata("amdgpu.noclobber");
1487 }
1488 
1489 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1490                                            unsigned DestAS) const {
1491   // Flat -> private/local is a simple truncate.
1492   // Flat -> global is no-op
1493   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1494     return true;
1495 
1496   const GCNTargetMachine &TM =
1497       static_cast<const GCNTargetMachine &>(getTargetMachine());
1498   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1499 }
1500 
1501 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1502   const MemSDNode *MemNode = cast<MemSDNode>(N);
1503 
1504   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1505 }
1506 
1507 TargetLoweringBase::LegalizeTypeAction
1508 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1509   int NumElts = VT.getVectorNumElements();
1510   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1511     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1512   return TargetLoweringBase::getPreferredVectorAction(VT);
1513 }
1514 
1515 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1516                                                          Type *Ty) const {
1517   // FIXME: Could be smarter if called for vector constants.
1518   return true;
1519 }
1520 
1521 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1522   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1523     switch (Op) {
1524     case ISD::LOAD:
1525     case ISD::STORE:
1526 
1527     // These operations are done with 32-bit instructions anyway.
1528     case ISD::AND:
1529     case ISD::OR:
1530     case ISD::XOR:
1531     case ISD::SELECT:
1532       // TODO: Extensions?
1533       return true;
1534     default:
1535       return false;
1536     }
1537   }
1538 
1539   // SimplifySetCC uses this function to determine whether or not it should
1540   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1541   if (VT == MVT::i1 && Op == ISD::SETCC)
1542     return false;
1543 
1544   return TargetLowering::isTypeDesirableForOp(Op, VT);
1545 }
1546 
1547 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1548                                                    const SDLoc &SL,
1549                                                    SDValue Chain,
1550                                                    uint64_t Offset) const {
1551   const DataLayout &DL = DAG.getDataLayout();
1552   MachineFunction &MF = DAG.getMachineFunction();
1553   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1554 
1555   const ArgDescriptor *InputPtrReg;
1556   const TargetRegisterClass *RC;
1557   LLT ArgTy;
1558 
1559   std::tie(InputPtrReg, RC, ArgTy) =
1560       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1561 
1562   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1563   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1564   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1565     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1566 
1567   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1568 }
1569 
1570 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1571                                             const SDLoc &SL) const {
1572   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1573                                                FIRST_IMPLICIT);
1574   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1575 }
1576 
1577 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1578                                          const SDLoc &SL, SDValue Val,
1579                                          bool Signed,
1580                                          const ISD::InputArg *Arg) const {
1581   // First, if it is a widened vector, narrow it.
1582   if (VT.isVector() &&
1583       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1584     EVT NarrowedVT =
1585         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1586                          VT.getVectorNumElements());
1587     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1588                       DAG.getConstant(0, SL, MVT::i32));
1589   }
1590 
1591   // Then convert the vector elements or scalar value.
1592   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1593       VT.bitsLT(MemVT)) {
1594     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1595     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1596   }
1597 
1598   if (MemVT.isFloatingPoint())
1599     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1600   else if (Signed)
1601     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1602   else
1603     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1604 
1605   return Val;
1606 }
1607 
1608 SDValue SITargetLowering::lowerKernargMemParameter(
1609     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1610     uint64_t Offset, Align Alignment, bool Signed,
1611     const ISD::InputArg *Arg) const {
1612   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1613 
1614   // Try to avoid using an extload by loading earlier than the argument address,
1615   // and extracting the relevant bits. The load should hopefully be merged with
1616   // the previous argument.
1617   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1618     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1619     int64_t AlignDownOffset = alignDown(Offset, 4);
1620     int64_t OffsetDiff = Offset - AlignDownOffset;
1621 
1622     EVT IntVT = MemVT.changeTypeToInteger();
1623 
1624     // TODO: If we passed in the base kernel offset we could have a better
1625     // alignment than 4, but we don't really need it.
1626     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1627     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1628                                MachineMemOperand::MODereferenceable |
1629                                MachineMemOperand::MOInvariant);
1630 
1631     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1632     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1633 
1634     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1635     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1636     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1637 
1638 
1639     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1640   }
1641 
1642   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1643   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1644                              MachineMemOperand::MODereferenceable |
1645                                  MachineMemOperand::MOInvariant);
1646 
1647   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1648   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1649 }
1650 
1651 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1652                                               const SDLoc &SL, SDValue Chain,
1653                                               const ISD::InputArg &Arg) const {
1654   MachineFunction &MF = DAG.getMachineFunction();
1655   MachineFrameInfo &MFI = MF.getFrameInfo();
1656 
1657   if (Arg.Flags.isByVal()) {
1658     unsigned Size = Arg.Flags.getByValSize();
1659     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1660     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1661   }
1662 
1663   unsigned ArgOffset = VA.getLocMemOffset();
1664   unsigned ArgSize = VA.getValVT().getStoreSize();
1665 
1666   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1667 
1668   // Create load nodes to retrieve arguments from the stack.
1669   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1670   SDValue ArgValue;
1671 
1672   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1673   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1674   MVT MemVT = VA.getValVT();
1675 
1676   switch (VA.getLocInfo()) {
1677   default:
1678     break;
1679   case CCValAssign::BCvt:
1680     MemVT = VA.getLocVT();
1681     break;
1682   case CCValAssign::SExt:
1683     ExtType = ISD::SEXTLOAD;
1684     break;
1685   case CCValAssign::ZExt:
1686     ExtType = ISD::ZEXTLOAD;
1687     break;
1688   case CCValAssign::AExt:
1689     ExtType = ISD::EXTLOAD;
1690     break;
1691   }
1692 
1693   ArgValue = DAG.getExtLoad(
1694     ExtType, SL, VA.getLocVT(), Chain, FIN,
1695     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1696     MemVT);
1697   return ArgValue;
1698 }
1699 
1700 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1701   const SIMachineFunctionInfo &MFI,
1702   EVT VT,
1703   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1704   const ArgDescriptor *Reg;
1705   const TargetRegisterClass *RC;
1706   LLT Ty;
1707 
1708   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1709   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1710 }
1711 
1712 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1713                                    CallingConv::ID CallConv,
1714                                    ArrayRef<ISD::InputArg> Ins,
1715                                    BitVector &Skipped,
1716                                    FunctionType *FType,
1717                                    SIMachineFunctionInfo *Info) {
1718   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1719     const ISD::InputArg *Arg = &Ins[I];
1720 
1721     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1722            "vector type argument should have been split");
1723 
1724     // First check if it's a PS input addr.
1725     if (CallConv == CallingConv::AMDGPU_PS &&
1726         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1727       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1728 
1729       // Inconveniently only the first part of the split is marked as isSplit,
1730       // so skip to the end. We only want to increment PSInputNum once for the
1731       // entire split argument.
1732       if (Arg->Flags.isSplit()) {
1733         while (!Arg->Flags.isSplitEnd()) {
1734           assert((!Arg->VT.isVector() ||
1735                   Arg->VT.getScalarSizeInBits() == 16) &&
1736                  "unexpected vector split in ps argument type");
1737           if (!SkipArg)
1738             Splits.push_back(*Arg);
1739           Arg = &Ins[++I];
1740         }
1741       }
1742 
1743       if (SkipArg) {
1744         // We can safely skip PS inputs.
1745         Skipped.set(Arg->getOrigArgIndex());
1746         ++PSInputNum;
1747         continue;
1748       }
1749 
1750       Info->markPSInputAllocated(PSInputNum);
1751       if (Arg->Used)
1752         Info->markPSInputEnabled(PSInputNum);
1753 
1754       ++PSInputNum;
1755     }
1756 
1757     Splits.push_back(*Arg);
1758   }
1759 }
1760 
1761 // Allocate special inputs passed in VGPRs.
1762 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1763                                                       MachineFunction &MF,
1764                                                       const SIRegisterInfo &TRI,
1765                                                       SIMachineFunctionInfo &Info) const {
1766   const LLT S32 = LLT::scalar(32);
1767   MachineRegisterInfo &MRI = MF.getRegInfo();
1768 
1769   if (Info.hasWorkItemIDX()) {
1770     Register Reg = AMDGPU::VGPR0;
1771     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1772 
1773     CCInfo.AllocateReg(Reg);
1774     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1775   }
1776 
1777   if (Info.hasWorkItemIDY()) {
1778     Register Reg = AMDGPU::VGPR1;
1779     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1780 
1781     CCInfo.AllocateReg(Reg);
1782     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1783   }
1784 
1785   if (Info.hasWorkItemIDZ()) {
1786     Register Reg = AMDGPU::VGPR2;
1787     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1788 
1789     CCInfo.AllocateReg(Reg);
1790     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1791   }
1792 }
1793 
1794 // Try to allocate a VGPR at the end of the argument list, or if no argument
1795 // VGPRs are left allocating a stack slot.
1796 // If \p Mask is is given it indicates bitfield position in the register.
1797 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1798 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1799                                          ArgDescriptor Arg = ArgDescriptor()) {
1800   if (Arg.isSet())
1801     return ArgDescriptor::createArg(Arg, Mask);
1802 
1803   ArrayRef<MCPhysReg> ArgVGPRs
1804     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1805   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1806   if (RegIdx == ArgVGPRs.size()) {
1807     // Spill to stack required.
1808     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1809 
1810     return ArgDescriptor::createStack(Offset, Mask);
1811   }
1812 
1813   unsigned Reg = ArgVGPRs[RegIdx];
1814   Reg = CCInfo.AllocateReg(Reg);
1815   assert(Reg != AMDGPU::NoRegister);
1816 
1817   MachineFunction &MF = CCInfo.getMachineFunction();
1818   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1819   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1820   return ArgDescriptor::createRegister(Reg, Mask);
1821 }
1822 
1823 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1824                                              const TargetRegisterClass *RC,
1825                                              unsigned NumArgRegs) {
1826   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1827   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1828   if (RegIdx == ArgSGPRs.size())
1829     report_fatal_error("ran out of SGPRs for arguments");
1830 
1831   unsigned Reg = ArgSGPRs[RegIdx];
1832   Reg = CCInfo.AllocateReg(Reg);
1833   assert(Reg != AMDGPU::NoRegister);
1834 
1835   MachineFunction &MF = CCInfo.getMachineFunction();
1836   MF.addLiveIn(Reg, RC);
1837   return ArgDescriptor::createRegister(Reg);
1838 }
1839 
1840 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1841   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1842 }
1843 
1844 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1845   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1846 }
1847 
1848 /// Allocate implicit function VGPR arguments at the end of allocated user
1849 /// arguments.
1850 void SITargetLowering::allocateSpecialInputVGPRs(
1851   CCState &CCInfo, MachineFunction &MF,
1852   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1853   const unsigned Mask = 0x3ff;
1854   ArgDescriptor Arg;
1855 
1856   if (Info.hasWorkItemIDX()) {
1857     Arg = allocateVGPR32Input(CCInfo, Mask);
1858     Info.setWorkItemIDX(Arg);
1859   }
1860 
1861   if (Info.hasWorkItemIDY()) {
1862     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1863     Info.setWorkItemIDY(Arg);
1864   }
1865 
1866   if (Info.hasWorkItemIDZ())
1867     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1868 }
1869 
1870 /// Allocate implicit function VGPR arguments in fixed registers.
1871 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1872   CCState &CCInfo, MachineFunction &MF,
1873   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1874   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1875   if (!Reg)
1876     report_fatal_error("failed to allocated VGPR for implicit arguments");
1877 
1878   const unsigned Mask = 0x3ff;
1879   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1880   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1881   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1882 }
1883 
1884 void SITargetLowering::allocateSpecialInputSGPRs(
1885   CCState &CCInfo,
1886   MachineFunction &MF,
1887   const SIRegisterInfo &TRI,
1888   SIMachineFunctionInfo &Info) const {
1889   auto &ArgInfo = Info.getArgInfo();
1890 
1891   // TODO: Unify handling with private memory pointers.
1892 
1893   if (Info.hasDispatchPtr())
1894     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1895 
1896   if (Info.hasQueuePtr())
1897     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1898 
1899   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1900   // constant offset from the kernarg segment.
1901   if (Info.hasImplicitArgPtr())
1902     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1903 
1904   if (Info.hasDispatchID())
1905     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1906 
1907   // flat_scratch_init is not applicable for non-kernel functions.
1908 
1909   if (Info.hasWorkGroupIDX())
1910     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1911 
1912   if (Info.hasWorkGroupIDY())
1913     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1914 
1915   if (Info.hasWorkGroupIDZ())
1916     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1917 }
1918 
1919 // Allocate special inputs passed in user SGPRs.
1920 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1921                                             MachineFunction &MF,
1922                                             const SIRegisterInfo &TRI,
1923                                             SIMachineFunctionInfo &Info) const {
1924   if (Info.hasImplicitBufferPtr()) {
1925     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1926     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1927     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1928   }
1929 
1930   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1931   if (Info.hasPrivateSegmentBuffer()) {
1932     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1933     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1934     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1935   }
1936 
1937   if (Info.hasDispatchPtr()) {
1938     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1939     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1940     CCInfo.AllocateReg(DispatchPtrReg);
1941   }
1942 
1943   if (Info.hasQueuePtr()) {
1944     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1945     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1946     CCInfo.AllocateReg(QueuePtrReg);
1947   }
1948 
1949   if (Info.hasKernargSegmentPtr()) {
1950     MachineRegisterInfo &MRI = MF.getRegInfo();
1951     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1952     CCInfo.AllocateReg(InputPtrReg);
1953 
1954     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1955     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1956   }
1957 
1958   if (Info.hasDispatchID()) {
1959     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1960     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1961     CCInfo.AllocateReg(DispatchIDReg);
1962   }
1963 
1964   if (Info.hasFlatScratchInit()) {
1965     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1966     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1967     CCInfo.AllocateReg(FlatScratchInitReg);
1968   }
1969 
1970   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1971   // these from the dispatch pointer.
1972 }
1973 
1974 // Allocate special input registers that are initialized per-wave.
1975 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1976                                            MachineFunction &MF,
1977                                            SIMachineFunctionInfo &Info,
1978                                            CallingConv::ID CallConv,
1979                                            bool IsShader) const {
1980   if (Info.hasWorkGroupIDX()) {
1981     unsigned Reg = Info.addWorkGroupIDX();
1982     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1983     CCInfo.AllocateReg(Reg);
1984   }
1985 
1986   if (Info.hasWorkGroupIDY()) {
1987     unsigned Reg = Info.addWorkGroupIDY();
1988     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1989     CCInfo.AllocateReg(Reg);
1990   }
1991 
1992   if (Info.hasWorkGroupIDZ()) {
1993     unsigned Reg = Info.addWorkGroupIDZ();
1994     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1995     CCInfo.AllocateReg(Reg);
1996   }
1997 
1998   if (Info.hasWorkGroupInfo()) {
1999     unsigned Reg = Info.addWorkGroupInfo();
2000     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2001     CCInfo.AllocateReg(Reg);
2002   }
2003 
2004   if (Info.hasPrivateSegmentWaveByteOffset()) {
2005     // Scratch wave offset passed in system SGPR.
2006     unsigned PrivateSegmentWaveByteOffsetReg;
2007 
2008     if (IsShader) {
2009       PrivateSegmentWaveByteOffsetReg =
2010         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2011 
2012       // This is true if the scratch wave byte offset doesn't have a fixed
2013       // location.
2014       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2015         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2016         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2017       }
2018     } else
2019       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2020 
2021     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2022     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2023   }
2024 }
2025 
2026 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2027                                      MachineFunction &MF,
2028                                      const SIRegisterInfo &TRI,
2029                                      SIMachineFunctionInfo &Info) {
2030   // Now that we've figured out where the scratch register inputs are, see if
2031   // should reserve the arguments and use them directly.
2032   MachineFrameInfo &MFI = MF.getFrameInfo();
2033   bool HasStackObjects = MFI.hasStackObjects();
2034   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2035 
2036   // Record that we know we have non-spill stack objects so we don't need to
2037   // check all stack objects later.
2038   if (HasStackObjects)
2039     Info.setHasNonSpillStackObjects(true);
2040 
2041   // Everything live out of a block is spilled with fast regalloc, so it's
2042   // almost certain that spilling will be required.
2043   if (TM.getOptLevel() == CodeGenOpt::None)
2044     HasStackObjects = true;
2045 
2046   // For now assume stack access is needed in any callee functions, so we need
2047   // the scratch registers to pass in.
2048   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2049 
2050   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2051     // If we have stack objects, we unquestionably need the private buffer
2052     // resource. For the Code Object V2 ABI, this will be the first 4 user
2053     // SGPR inputs. We can reserve those and use them directly.
2054 
2055     Register PrivateSegmentBufferReg =
2056         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2057     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2058   } else {
2059     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2060     // We tentatively reserve the last registers (skipping the last registers
2061     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2062     // we'll replace these with the ones immediately after those which were
2063     // really allocated. In the prologue copies will be inserted from the
2064     // argument to these reserved registers.
2065 
2066     // Without HSA, relocations are used for the scratch pointer and the
2067     // buffer resource setup is always inserted in the prologue. Scratch wave
2068     // offset is still in an input SGPR.
2069     Info.setScratchRSrcReg(ReservedBufferReg);
2070   }
2071 
2072   MachineRegisterInfo &MRI = MF.getRegInfo();
2073 
2074   // For entry functions we have to set up the stack pointer if we use it,
2075   // whereas non-entry functions get this "for free". This means there is no
2076   // intrinsic advantage to using S32 over S34 in cases where we do not have
2077   // calls but do need a frame pointer (i.e. if we are requested to have one
2078   // because frame pointer elimination is disabled). To keep things simple we
2079   // only ever use S32 as the call ABI stack pointer, and so using it does not
2080   // imply we need a separate frame pointer.
2081   //
2082   // Try to use s32 as the SP, but move it if it would interfere with input
2083   // arguments. This won't work with calls though.
2084   //
2085   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2086   // registers.
2087   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2088     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2089   } else {
2090     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2091 
2092     if (MFI.hasCalls())
2093       report_fatal_error("call in graphics shader with too many input SGPRs");
2094 
2095     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2096       if (!MRI.isLiveIn(Reg)) {
2097         Info.setStackPtrOffsetReg(Reg);
2098         break;
2099       }
2100     }
2101 
2102     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2103       report_fatal_error("failed to find register for SP");
2104   }
2105 
2106   // hasFP should be accurate for entry functions even before the frame is
2107   // finalized, because it does not rely on the known stack size, only
2108   // properties like whether variable sized objects are present.
2109   if (ST.getFrameLowering()->hasFP(MF)) {
2110     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2111   }
2112 }
2113 
2114 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2115   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2116   return !Info->isEntryFunction();
2117 }
2118 
2119 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2120 
2121 }
2122 
2123 void SITargetLowering::insertCopiesSplitCSR(
2124   MachineBasicBlock *Entry,
2125   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2126   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2127 
2128   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2129   if (!IStart)
2130     return;
2131 
2132   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2133   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2134   MachineBasicBlock::iterator MBBI = Entry->begin();
2135   for (const MCPhysReg *I = IStart; *I; ++I) {
2136     const TargetRegisterClass *RC = nullptr;
2137     if (AMDGPU::SReg_64RegClass.contains(*I))
2138       RC = &AMDGPU::SGPR_64RegClass;
2139     else if (AMDGPU::SReg_32RegClass.contains(*I))
2140       RC = &AMDGPU::SGPR_32RegClass;
2141     else
2142       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2143 
2144     Register NewVR = MRI->createVirtualRegister(RC);
2145     // Create copy from CSR to a virtual register.
2146     Entry->addLiveIn(*I);
2147     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2148       .addReg(*I);
2149 
2150     // Insert the copy-back instructions right before the terminator.
2151     for (auto *Exit : Exits)
2152       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2153               TII->get(TargetOpcode::COPY), *I)
2154         .addReg(NewVR);
2155   }
2156 }
2157 
2158 SDValue SITargetLowering::LowerFormalArguments(
2159     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2160     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2161     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2162   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2163 
2164   MachineFunction &MF = DAG.getMachineFunction();
2165   const Function &Fn = MF.getFunction();
2166   FunctionType *FType = MF.getFunction().getFunctionType();
2167   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2168 
2169   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2170     DiagnosticInfoUnsupported NoGraphicsHSA(
2171         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2172     DAG.getContext()->diagnose(NoGraphicsHSA);
2173     return DAG.getEntryNode();
2174   }
2175 
2176   SmallVector<ISD::InputArg, 16> Splits;
2177   SmallVector<CCValAssign, 16> ArgLocs;
2178   BitVector Skipped(Ins.size());
2179   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2180                  *DAG.getContext());
2181 
2182   bool IsShader = AMDGPU::isShader(CallConv);
2183   bool IsKernel = AMDGPU::isKernel(CallConv);
2184   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2185 
2186   if (IsShader) {
2187     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2188 
2189     // At least one interpolation mode must be enabled or else the GPU will
2190     // hang.
2191     //
2192     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2193     // set PSInputAddr, the user wants to enable some bits after the compilation
2194     // based on run-time states. Since we can't know what the final PSInputEna
2195     // will look like, so we shouldn't do anything here and the user should take
2196     // responsibility for the correct programming.
2197     //
2198     // Otherwise, the following restrictions apply:
2199     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2200     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2201     //   enabled too.
2202     if (CallConv == CallingConv::AMDGPU_PS) {
2203       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2204            ((Info->getPSInputAddr() & 0xF) == 0 &&
2205             Info->isPSInputAllocated(11))) {
2206         CCInfo.AllocateReg(AMDGPU::VGPR0);
2207         CCInfo.AllocateReg(AMDGPU::VGPR1);
2208         Info->markPSInputAllocated(0);
2209         Info->markPSInputEnabled(0);
2210       }
2211       if (Subtarget->isAmdPalOS()) {
2212         // For isAmdPalOS, the user does not enable some bits after compilation
2213         // based on run-time states; the register values being generated here are
2214         // the final ones set in hardware. Therefore we need to apply the
2215         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2216         // a bit is set in PSInputAddr but not PSInputEnable is where the
2217         // frontend set up an input arg for a particular interpolation mode, but
2218         // nothing uses that input arg. Really we should have an earlier pass
2219         // that removes such an arg.)
2220         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2221         if ((PsInputBits & 0x7F) == 0 ||
2222             ((PsInputBits & 0xF) == 0 &&
2223              (PsInputBits >> 11 & 1)))
2224           Info->markPSInputEnabled(
2225               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2226       }
2227     }
2228 
2229     assert(!Info->hasDispatchPtr() &&
2230            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2231            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2232            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2233            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2234            !Info->hasWorkItemIDZ());
2235   } else if (IsKernel) {
2236     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2237   } else {
2238     Splits.append(Ins.begin(), Ins.end());
2239   }
2240 
2241   if (IsEntryFunc) {
2242     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2243     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2244   } else {
2245     // For the fixed ABI, pass workitem IDs in the last argument register.
2246     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2247       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2248   }
2249 
2250   if (IsKernel) {
2251     analyzeFormalArgumentsCompute(CCInfo, Ins);
2252   } else {
2253     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2254     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2255   }
2256 
2257   SmallVector<SDValue, 16> Chains;
2258 
2259   // FIXME: This is the minimum kernel argument alignment. We should improve
2260   // this to the maximum alignment of the arguments.
2261   //
2262   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2263   // kern arg offset.
2264   const Align KernelArgBaseAlign = Align(16);
2265 
2266   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2267     const ISD::InputArg &Arg = Ins[i];
2268     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2269       InVals.push_back(DAG.getUNDEF(Arg.VT));
2270       continue;
2271     }
2272 
2273     CCValAssign &VA = ArgLocs[ArgIdx++];
2274     MVT VT = VA.getLocVT();
2275 
2276     if (IsEntryFunc && VA.isMemLoc()) {
2277       VT = Ins[i].VT;
2278       EVT MemVT = VA.getLocVT();
2279 
2280       const uint64_t Offset = VA.getLocMemOffset();
2281       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2282 
2283       if (Arg.Flags.isByRef()) {
2284         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2285 
2286         const GCNTargetMachine &TM =
2287             static_cast<const GCNTargetMachine &>(getTargetMachine());
2288         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2289                                     Arg.Flags.getPointerAddrSpace())) {
2290           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2291                                      Arg.Flags.getPointerAddrSpace());
2292         }
2293 
2294         InVals.push_back(Ptr);
2295         continue;
2296       }
2297 
2298       SDValue Arg = lowerKernargMemParameter(
2299         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2300       Chains.push_back(Arg.getValue(1));
2301 
2302       auto *ParamTy =
2303         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2304       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2305           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2306                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2307         // On SI local pointers are just offsets into LDS, so they are always
2308         // less than 16-bits.  On CI and newer they could potentially be
2309         // real pointers, so we can't guarantee their size.
2310         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2311                           DAG.getValueType(MVT::i16));
2312       }
2313 
2314       InVals.push_back(Arg);
2315       continue;
2316     } else if (!IsEntryFunc && VA.isMemLoc()) {
2317       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2318       InVals.push_back(Val);
2319       if (!Arg.Flags.isByVal())
2320         Chains.push_back(Val.getValue(1));
2321       continue;
2322     }
2323 
2324     assert(VA.isRegLoc() && "Parameter must be in a register!");
2325 
2326     Register Reg = VA.getLocReg();
2327     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2328     EVT ValVT = VA.getValVT();
2329 
2330     Reg = MF.addLiveIn(Reg, RC);
2331     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2332 
2333     if (Arg.Flags.isSRet()) {
2334       // The return object should be reasonably addressable.
2335 
2336       // FIXME: This helps when the return is a real sret. If it is a
2337       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2338       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2339       unsigned NumBits
2340         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2341       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2342         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2343     }
2344 
2345     // If this is an 8 or 16-bit value, it is really passed promoted
2346     // to 32 bits. Insert an assert[sz]ext to capture this, then
2347     // truncate to the right size.
2348     switch (VA.getLocInfo()) {
2349     case CCValAssign::Full:
2350       break;
2351     case CCValAssign::BCvt:
2352       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2353       break;
2354     case CCValAssign::SExt:
2355       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2356                         DAG.getValueType(ValVT));
2357       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2358       break;
2359     case CCValAssign::ZExt:
2360       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2361                         DAG.getValueType(ValVT));
2362       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2363       break;
2364     case CCValAssign::AExt:
2365       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2366       break;
2367     default:
2368       llvm_unreachable("Unknown loc info!");
2369     }
2370 
2371     InVals.push_back(Val);
2372   }
2373 
2374   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2375     // Special inputs come after user arguments.
2376     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2377   }
2378 
2379   // Start adding system SGPRs.
2380   if (IsEntryFunc) {
2381     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2382   } else {
2383     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2384     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2385   }
2386 
2387   auto &ArgUsageInfo =
2388     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2389   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2390 
2391   unsigned StackArgSize = CCInfo.getNextStackOffset();
2392   Info->setBytesInStackArgArea(StackArgSize);
2393 
2394   return Chains.empty() ? Chain :
2395     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2396 }
2397 
2398 // TODO: If return values can't fit in registers, we should return as many as
2399 // possible in registers before passing on stack.
2400 bool SITargetLowering::CanLowerReturn(
2401   CallingConv::ID CallConv,
2402   MachineFunction &MF, bool IsVarArg,
2403   const SmallVectorImpl<ISD::OutputArg> &Outs,
2404   LLVMContext &Context) const {
2405   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2406   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2407   // for shaders. Vector types should be explicitly handled by CC.
2408   if (AMDGPU::isEntryFunctionCC(CallConv))
2409     return true;
2410 
2411   SmallVector<CCValAssign, 16> RVLocs;
2412   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2413   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2414 }
2415 
2416 SDValue
2417 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2418                               bool isVarArg,
2419                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2420                               const SmallVectorImpl<SDValue> &OutVals,
2421                               const SDLoc &DL, SelectionDAG &DAG) const {
2422   MachineFunction &MF = DAG.getMachineFunction();
2423   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2424 
2425   if (AMDGPU::isKernel(CallConv)) {
2426     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2427                                              OutVals, DL, DAG);
2428   }
2429 
2430   bool IsShader = AMDGPU::isShader(CallConv);
2431 
2432   Info->setIfReturnsVoid(Outs.empty());
2433   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2434 
2435   // CCValAssign - represent the assignment of the return value to a location.
2436   SmallVector<CCValAssign, 48> RVLocs;
2437   SmallVector<ISD::OutputArg, 48> Splits;
2438 
2439   // CCState - Info about the registers and stack slots.
2440   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2441                  *DAG.getContext());
2442 
2443   // Analyze outgoing return values.
2444   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2445 
2446   SDValue Flag;
2447   SmallVector<SDValue, 48> RetOps;
2448   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2449 
2450   // Add return address for callable functions.
2451   if (!Info->isEntryFunction()) {
2452     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2453     SDValue ReturnAddrReg = CreateLiveInRegister(
2454       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2455 
2456     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2457         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2458         MVT::i64);
2459     Chain =
2460         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2461     Flag = Chain.getValue(1);
2462     RetOps.push_back(ReturnAddrVirtualReg);
2463   }
2464 
2465   // Copy the result values into the output registers.
2466   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2467        ++I, ++RealRVLocIdx) {
2468     CCValAssign &VA = RVLocs[I];
2469     assert(VA.isRegLoc() && "Can only return in registers!");
2470     // TODO: Partially return in registers if return values don't fit.
2471     SDValue Arg = OutVals[RealRVLocIdx];
2472 
2473     // Copied from other backends.
2474     switch (VA.getLocInfo()) {
2475     case CCValAssign::Full:
2476       break;
2477     case CCValAssign::BCvt:
2478       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2479       break;
2480     case CCValAssign::SExt:
2481       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2482       break;
2483     case CCValAssign::ZExt:
2484       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2485       break;
2486     case CCValAssign::AExt:
2487       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2488       break;
2489     default:
2490       llvm_unreachable("Unknown loc info!");
2491     }
2492 
2493     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2494     Flag = Chain.getValue(1);
2495     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2496   }
2497 
2498   // FIXME: Does sret work properly?
2499   if (!Info->isEntryFunction()) {
2500     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2501     const MCPhysReg *I =
2502       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2503     if (I) {
2504       for (; *I; ++I) {
2505         if (AMDGPU::SReg_64RegClass.contains(*I))
2506           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2507         else if (AMDGPU::SReg_32RegClass.contains(*I))
2508           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2509         else
2510           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2511       }
2512     }
2513   }
2514 
2515   // Update chain and glue.
2516   RetOps[0] = Chain;
2517   if (Flag.getNode())
2518     RetOps.push_back(Flag);
2519 
2520   unsigned Opc = AMDGPUISD::ENDPGM;
2521   if (!IsWaveEnd)
2522     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2523   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2524 }
2525 
2526 SDValue SITargetLowering::LowerCallResult(
2527     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2528     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2529     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2530     SDValue ThisVal) const {
2531   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2532 
2533   // Assign locations to each value returned by this call.
2534   SmallVector<CCValAssign, 16> RVLocs;
2535   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2536                  *DAG.getContext());
2537   CCInfo.AnalyzeCallResult(Ins, RetCC);
2538 
2539   // Copy all of the result registers out of their specified physreg.
2540   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2541     CCValAssign VA = RVLocs[i];
2542     SDValue Val;
2543 
2544     if (VA.isRegLoc()) {
2545       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2546       Chain = Val.getValue(1);
2547       InFlag = Val.getValue(2);
2548     } else if (VA.isMemLoc()) {
2549       report_fatal_error("TODO: return values in memory");
2550     } else
2551       llvm_unreachable("unknown argument location type");
2552 
2553     switch (VA.getLocInfo()) {
2554     case CCValAssign::Full:
2555       break;
2556     case CCValAssign::BCvt:
2557       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2558       break;
2559     case CCValAssign::ZExt:
2560       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2561                         DAG.getValueType(VA.getValVT()));
2562       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2563       break;
2564     case CCValAssign::SExt:
2565       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2566                         DAG.getValueType(VA.getValVT()));
2567       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2568       break;
2569     case CCValAssign::AExt:
2570       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2571       break;
2572     default:
2573       llvm_unreachable("Unknown loc info!");
2574     }
2575 
2576     InVals.push_back(Val);
2577   }
2578 
2579   return Chain;
2580 }
2581 
2582 // Add code to pass special inputs required depending on used features separate
2583 // from the explicit user arguments present in the IR.
2584 void SITargetLowering::passSpecialInputs(
2585     CallLoweringInfo &CLI,
2586     CCState &CCInfo,
2587     const SIMachineFunctionInfo &Info,
2588     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2589     SmallVectorImpl<SDValue> &MemOpChains,
2590     SDValue Chain) const {
2591   // If we don't have a call site, this was a call inserted by
2592   // legalization. These can never use special inputs.
2593   if (!CLI.CB)
2594     return;
2595 
2596   SelectionDAG &DAG = CLI.DAG;
2597   const SDLoc &DL = CLI.DL;
2598 
2599   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2600   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2601 
2602   const AMDGPUFunctionArgInfo *CalleeArgInfo
2603     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2604   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2605     auto &ArgUsageInfo =
2606       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2607     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2608   }
2609 
2610   // TODO: Unify with private memory register handling. This is complicated by
2611   // the fact that at least in kernels, the input argument is not necessarily
2612   // in the same location as the input.
2613   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2614     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2615     AMDGPUFunctionArgInfo::QUEUE_PTR,
2616     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2617     AMDGPUFunctionArgInfo::DISPATCH_ID,
2618     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2619     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2620     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2621   };
2622 
2623   for (auto InputID : InputRegs) {
2624     const ArgDescriptor *OutgoingArg;
2625     const TargetRegisterClass *ArgRC;
2626     LLT ArgTy;
2627 
2628     std::tie(OutgoingArg, ArgRC, ArgTy) =
2629         CalleeArgInfo->getPreloadedValue(InputID);
2630     if (!OutgoingArg)
2631       continue;
2632 
2633     const ArgDescriptor *IncomingArg;
2634     const TargetRegisterClass *IncomingArgRC;
2635     LLT Ty;
2636     std::tie(IncomingArg, IncomingArgRC, Ty) =
2637         CallerArgInfo.getPreloadedValue(InputID);
2638     assert(IncomingArgRC == ArgRC);
2639 
2640     // All special arguments are ints for now.
2641     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2642     SDValue InputReg;
2643 
2644     if (IncomingArg) {
2645       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2646     } else {
2647       // The implicit arg ptr is special because it doesn't have a corresponding
2648       // input for kernels, and is computed from the kernarg segment pointer.
2649       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2650       InputReg = getImplicitArgPtr(DAG, DL);
2651     }
2652 
2653     if (OutgoingArg->isRegister()) {
2654       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2655       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2656         report_fatal_error("failed to allocate implicit input argument");
2657     } else {
2658       unsigned SpecialArgOffset =
2659           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2660       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2661                                               SpecialArgOffset);
2662       MemOpChains.push_back(ArgStore);
2663     }
2664   }
2665 
2666   // Pack workitem IDs into a single register or pass it as is if already
2667   // packed.
2668   const ArgDescriptor *OutgoingArg;
2669   const TargetRegisterClass *ArgRC;
2670   LLT Ty;
2671 
2672   std::tie(OutgoingArg, ArgRC, Ty) =
2673       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2674   if (!OutgoingArg)
2675     std::tie(OutgoingArg, ArgRC, Ty) =
2676         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2677   if (!OutgoingArg)
2678     std::tie(OutgoingArg, ArgRC, Ty) =
2679         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2680   if (!OutgoingArg)
2681     return;
2682 
2683   const ArgDescriptor *IncomingArgX = std::get<0>(
2684       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2685   const ArgDescriptor *IncomingArgY = std::get<0>(
2686       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2687   const ArgDescriptor *IncomingArgZ = std::get<0>(
2688       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2689 
2690   SDValue InputReg;
2691   SDLoc SL;
2692 
2693   // If incoming ids are not packed we need to pack them.
2694   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2695     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2696 
2697   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2698     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2699     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2700                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2701     InputReg = InputReg.getNode() ?
2702                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2703   }
2704 
2705   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2706     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2707     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2708                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2709     InputReg = InputReg.getNode() ?
2710                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2711   }
2712 
2713   if (!InputReg.getNode()) {
2714     // Workitem ids are already packed, any of present incoming arguments
2715     // will carry all required fields.
2716     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2717       IncomingArgX ? *IncomingArgX :
2718       IncomingArgY ? *IncomingArgY :
2719                      *IncomingArgZ, ~0u);
2720     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2721   }
2722 
2723   if (OutgoingArg->isRegister()) {
2724     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2725     CCInfo.AllocateReg(OutgoingArg->getRegister());
2726   } else {
2727     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2728     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2729                                             SpecialArgOffset);
2730     MemOpChains.push_back(ArgStore);
2731   }
2732 }
2733 
2734 static bool canGuaranteeTCO(CallingConv::ID CC) {
2735   return CC == CallingConv::Fast;
2736 }
2737 
2738 /// Return true if we might ever do TCO for calls with this calling convention.
2739 static bool mayTailCallThisCC(CallingConv::ID CC) {
2740   switch (CC) {
2741   case CallingConv::C:
2742     return true;
2743   default:
2744     return canGuaranteeTCO(CC);
2745   }
2746 }
2747 
2748 bool SITargetLowering::isEligibleForTailCallOptimization(
2749     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2750     const SmallVectorImpl<ISD::OutputArg> &Outs,
2751     const SmallVectorImpl<SDValue> &OutVals,
2752     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2753   if (!mayTailCallThisCC(CalleeCC))
2754     return false;
2755 
2756   MachineFunction &MF = DAG.getMachineFunction();
2757   const Function &CallerF = MF.getFunction();
2758   CallingConv::ID CallerCC = CallerF.getCallingConv();
2759   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2760   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2761 
2762   // Kernels aren't callable, and don't have a live in return address so it
2763   // doesn't make sense to do a tail call with entry functions.
2764   if (!CallerPreserved)
2765     return false;
2766 
2767   bool CCMatch = CallerCC == CalleeCC;
2768 
2769   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2770     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2771       return true;
2772     return false;
2773   }
2774 
2775   // TODO: Can we handle var args?
2776   if (IsVarArg)
2777     return false;
2778 
2779   for (const Argument &Arg : CallerF.args()) {
2780     if (Arg.hasByValAttr())
2781       return false;
2782   }
2783 
2784   LLVMContext &Ctx = *DAG.getContext();
2785 
2786   // Check that the call results are passed in the same way.
2787   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2788                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2789                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2790     return false;
2791 
2792   // The callee has to preserve all registers the caller needs to preserve.
2793   if (!CCMatch) {
2794     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2795     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2796       return false;
2797   }
2798 
2799   // Nothing more to check if the callee is taking no arguments.
2800   if (Outs.empty())
2801     return true;
2802 
2803   SmallVector<CCValAssign, 16> ArgLocs;
2804   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2805 
2806   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2807 
2808   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2809   // If the stack arguments for this call do not fit into our own save area then
2810   // the call cannot be made tail.
2811   // TODO: Is this really necessary?
2812   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2813     return false;
2814 
2815   const MachineRegisterInfo &MRI = MF.getRegInfo();
2816   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2817 }
2818 
2819 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2820   if (!CI->isTailCall())
2821     return false;
2822 
2823   const Function *ParentFn = CI->getParent()->getParent();
2824   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2825     return false;
2826   return true;
2827 }
2828 
2829 // The wave scratch offset register is used as the global base pointer.
2830 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2831                                     SmallVectorImpl<SDValue> &InVals) const {
2832   SelectionDAG &DAG = CLI.DAG;
2833   const SDLoc &DL = CLI.DL;
2834   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2835   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2836   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2837   SDValue Chain = CLI.Chain;
2838   SDValue Callee = CLI.Callee;
2839   bool &IsTailCall = CLI.IsTailCall;
2840   CallingConv::ID CallConv = CLI.CallConv;
2841   bool IsVarArg = CLI.IsVarArg;
2842   bool IsSibCall = false;
2843   bool IsThisReturn = false;
2844   MachineFunction &MF = DAG.getMachineFunction();
2845 
2846   if (Callee.isUndef() || isNullConstant(Callee)) {
2847     if (!CLI.IsTailCall) {
2848       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2849         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2850     }
2851 
2852     return Chain;
2853   }
2854 
2855   if (IsVarArg) {
2856     return lowerUnhandledCall(CLI, InVals,
2857                               "unsupported call to variadic function ");
2858   }
2859 
2860   if (!CLI.CB)
2861     report_fatal_error("unsupported libcall legalization");
2862 
2863   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2864       !CLI.CB->getCalledFunction()) {
2865     return lowerUnhandledCall(CLI, InVals,
2866                               "unsupported indirect call to function ");
2867   }
2868 
2869   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2870     return lowerUnhandledCall(CLI, InVals,
2871                               "unsupported required tail call to function ");
2872   }
2873 
2874   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2875     // Note the issue is with the CC of the calling function, not of the call
2876     // itself.
2877     return lowerUnhandledCall(CLI, InVals,
2878                           "unsupported call from graphics shader of function ");
2879   }
2880 
2881   if (IsTailCall) {
2882     IsTailCall = isEligibleForTailCallOptimization(
2883       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2884     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2885       report_fatal_error("failed to perform tail call elimination on a call "
2886                          "site marked musttail");
2887     }
2888 
2889     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2890 
2891     // A sibling call is one where we're under the usual C ABI and not planning
2892     // to change that but can still do a tail call:
2893     if (!TailCallOpt && IsTailCall)
2894       IsSibCall = true;
2895 
2896     if (IsTailCall)
2897       ++NumTailCalls;
2898   }
2899 
2900   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2901   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2902   SmallVector<SDValue, 8> MemOpChains;
2903 
2904   // Analyze operands of the call, assigning locations to each operand.
2905   SmallVector<CCValAssign, 16> ArgLocs;
2906   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2907   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2908 
2909   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2910     // With a fixed ABI, allocate fixed registers before user arguments.
2911     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2912   }
2913 
2914   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2915 
2916   // Get a count of how many bytes are to be pushed on the stack.
2917   unsigned NumBytes = CCInfo.getNextStackOffset();
2918 
2919   if (IsSibCall) {
2920     // Since we're not changing the ABI to make this a tail call, the memory
2921     // operands are already available in the caller's incoming argument space.
2922     NumBytes = 0;
2923   }
2924 
2925   // FPDiff is the byte offset of the call's argument area from the callee's.
2926   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2927   // by this amount for a tail call. In a sibling call it must be 0 because the
2928   // caller will deallocate the entire stack and the callee still expects its
2929   // arguments to begin at SP+0. Completely unused for non-tail calls.
2930   int32_t FPDiff = 0;
2931   MachineFrameInfo &MFI = MF.getFrameInfo();
2932 
2933   // Adjust the stack pointer for the new arguments...
2934   // These operations are automatically eliminated by the prolog/epilog pass
2935   if (!IsSibCall) {
2936     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2937 
2938     SmallVector<SDValue, 4> CopyFromChains;
2939 
2940     // In the HSA case, this should be an identity copy.
2941     SDValue ScratchRSrcReg
2942       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2943     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2944     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2945     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2946   }
2947 
2948   MVT PtrVT = MVT::i32;
2949 
2950   // Walk the register/memloc assignments, inserting copies/loads.
2951   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2952     CCValAssign &VA = ArgLocs[i];
2953     SDValue Arg = OutVals[i];
2954 
2955     // Promote the value if needed.
2956     switch (VA.getLocInfo()) {
2957     case CCValAssign::Full:
2958       break;
2959     case CCValAssign::BCvt:
2960       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2961       break;
2962     case CCValAssign::ZExt:
2963       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2964       break;
2965     case CCValAssign::SExt:
2966       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2967       break;
2968     case CCValAssign::AExt:
2969       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2970       break;
2971     case CCValAssign::FPExt:
2972       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2973       break;
2974     default:
2975       llvm_unreachable("Unknown loc info!");
2976     }
2977 
2978     if (VA.isRegLoc()) {
2979       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2980     } else {
2981       assert(VA.isMemLoc());
2982 
2983       SDValue DstAddr;
2984       MachinePointerInfo DstInfo;
2985 
2986       unsigned LocMemOffset = VA.getLocMemOffset();
2987       int32_t Offset = LocMemOffset;
2988 
2989       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2990       MaybeAlign Alignment;
2991 
2992       if (IsTailCall) {
2993         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2994         unsigned OpSize = Flags.isByVal() ?
2995           Flags.getByValSize() : VA.getValVT().getStoreSize();
2996 
2997         // FIXME: We can have better than the minimum byval required alignment.
2998         Alignment =
2999             Flags.isByVal()
3000                 ? Flags.getNonZeroByValAlign()
3001                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3002 
3003         Offset = Offset + FPDiff;
3004         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3005 
3006         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3007         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3008 
3009         // Make sure any stack arguments overlapping with where we're storing
3010         // are loaded before this eventual operation. Otherwise they'll be
3011         // clobbered.
3012 
3013         // FIXME: Why is this really necessary? This seems to just result in a
3014         // lot of code to copy the stack and write them back to the same
3015         // locations, which are supposed to be immutable?
3016         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3017       } else {
3018         DstAddr = PtrOff;
3019         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3020         Alignment =
3021             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3022       }
3023 
3024       if (Outs[i].Flags.isByVal()) {
3025         SDValue SizeNode =
3026             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3027         SDValue Cpy =
3028             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3029                           Outs[i].Flags.getNonZeroByValAlign(),
3030                           /*isVol = */ false, /*AlwaysInline = */ true,
3031                           /*isTailCall = */ false, DstInfo,
3032                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3033 
3034         MemOpChains.push_back(Cpy);
3035       } else {
3036         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
3037                                      Alignment ? Alignment->value() : 0);
3038         MemOpChains.push_back(Store);
3039       }
3040     }
3041   }
3042 
3043   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
3044     // Copy special input registers after user input arguments.
3045     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3046   }
3047 
3048   if (!MemOpChains.empty())
3049     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3050 
3051   // Build a sequence of copy-to-reg nodes chained together with token chain
3052   // and flag operands which copy the outgoing args into the appropriate regs.
3053   SDValue InFlag;
3054   for (auto &RegToPass : RegsToPass) {
3055     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3056                              RegToPass.second, InFlag);
3057     InFlag = Chain.getValue(1);
3058   }
3059 
3060 
3061   SDValue PhysReturnAddrReg;
3062   if (IsTailCall) {
3063     // Since the return is being combined with the call, we need to pass on the
3064     // return address.
3065 
3066     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3067     SDValue ReturnAddrReg = CreateLiveInRegister(
3068       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3069 
3070     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3071                                         MVT::i64);
3072     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3073     InFlag = Chain.getValue(1);
3074   }
3075 
3076   // We don't usually want to end the call-sequence here because we would tidy
3077   // the frame up *after* the call, however in the ABI-changing tail-call case
3078   // we've carefully laid out the parameters so that when sp is reset they'll be
3079   // in the correct location.
3080   if (IsTailCall && !IsSibCall) {
3081     Chain = DAG.getCALLSEQ_END(Chain,
3082                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3083                                DAG.getTargetConstant(0, DL, MVT::i32),
3084                                InFlag, DL);
3085     InFlag = Chain.getValue(1);
3086   }
3087 
3088   std::vector<SDValue> Ops;
3089   Ops.push_back(Chain);
3090   Ops.push_back(Callee);
3091   // Add a redundant copy of the callee global which will not be legalized, as
3092   // we need direct access to the callee later.
3093   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3094     const GlobalValue *GV = GSD->getGlobal();
3095     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3096   } else {
3097     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3098   }
3099 
3100   if (IsTailCall) {
3101     // Each tail call may have to adjust the stack by a different amount, so
3102     // this information must travel along with the operation for eventual
3103     // consumption by emitEpilogue.
3104     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3105 
3106     Ops.push_back(PhysReturnAddrReg);
3107   }
3108 
3109   // Add argument registers to the end of the list so that they are known live
3110   // into the call.
3111   for (auto &RegToPass : RegsToPass) {
3112     Ops.push_back(DAG.getRegister(RegToPass.first,
3113                                   RegToPass.second.getValueType()));
3114   }
3115 
3116   // Add a register mask operand representing the call-preserved registers.
3117 
3118   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3119   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3120   assert(Mask && "Missing call preserved mask for calling convention");
3121   Ops.push_back(DAG.getRegisterMask(Mask));
3122 
3123   if (InFlag.getNode())
3124     Ops.push_back(InFlag);
3125 
3126   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3127 
3128   // If we're doing a tall call, use a TC_RETURN here rather than an
3129   // actual call instruction.
3130   if (IsTailCall) {
3131     MFI.setHasTailCall();
3132     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3133   }
3134 
3135   // Returns a chain and a flag for retval copy to use.
3136   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3137   Chain = Call.getValue(0);
3138   InFlag = Call.getValue(1);
3139 
3140   uint64_t CalleePopBytes = NumBytes;
3141   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3142                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3143                              InFlag, DL);
3144   if (!Ins.empty())
3145     InFlag = Chain.getValue(1);
3146 
3147   // Handle result values, copying them out of physregs into vregs that we
3148   // return.
3149   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3150                          InVals, IsThisReturn,
3151                          IsThisReturn ? OutVals[0] : SDValue());
3152 }
3153 
3154 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3155 // except for applying the wave size scale to the increment amount.
3156 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3157     SDValue Op, SelectionDAG &DAG) const {
3158   const MachineFunction &MF = DAG.getMachineFunction();
3159   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3160 
3161   SDLoc dl(Op);
3162   EVT VT = Op.getValueType();
3163   SDValue Tmp1 = Op;
3164   SDValue Tmp2 = Op.getValue(1);
3165   SDValue Tmp3 = Op.getOperand(2);
3166   SDValue Chain = Tmp1.getOperand(0);
3167 
3168   Register SPReg = Info->getStackPtrOffsetReg();
3169 
3170   // Chain the dynamic stack allocation so that it doesn't modify the stack
3171   // pointer when other instructions are using the stack.
3172   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3173 
3174   SDValue Size  = Tmp2.getOperand(1);
3175   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3176   Chain = SP.getValue(1);
3177   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3178   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3179   const TargetFrameLowering *TFL = ST.getFrameLowering();
3180   unsigned Opc =
3181     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3182     ISD::ADD : ISD::SUB;
3183 
3184   SDValue ScaledSize = DAG.getNode(
3185       ISD::SHL, dl, VT, Size,
3186       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3187 
3188   Align StackAlign = TFL->getStackAlign();
3189   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3190   if (Alignment && *Alignment > StackAlign) {
3191     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3192                        DAG.getConstant(-(uint64_t)Alignment->value()
3193                                            << ST.getWavefrontSizeLog2(),
3194                                        dl, VT));
3195   }
3196 
3197   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3198   Tmp2 = DAG.getCALLSEQ_END(
3199       Chain, DAG.getIntPtrConstant(0, dl, true),
3200       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3201 
3202   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3203 }
3204 
3205 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3206                                                   SelectionDAG &DAG) const {
3207   // We only handle constant sizes here to allow non-entry block, static sized
3208   // allocas. A truly dynamic value is more difficult to support because we
3209   // don't know if the size value is uniform or not. If the size isn't uniform,
3210   // we would need to do a wave reduction to get the maximum size to know how
3211   // much to increment the uniform stack pointer.
3212   SDValue Size = Op.getOperand(1);
3213   if (isa<ConstantSDNode>(Size))
3214       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3215 
3216   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3217 }
3218 
3219 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3220                                              const MachineFunction &MF) const {
3221   Register Reg = StringSwitch<Register>(RegName)
3222     .Case("m0", AMDGPU::M0)
3223     .Case("exec", AMDGPU::EXEC)
3224     .Case("exec_lo", AMDGPU::EXEC_LO)
3225     .Case("exec_hi", AMDGPU::EXEC_HI)
3226     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3227     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3228     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3229     .Default(Register());
3230 
3231   if (Reg == AMDGPU::NoRegister) {
3232     report_fatal_error(Twine("invalid register name \""
3233                              + StringRef(RegName)  + "\"."));
3234 
3235   }
3236 
3237   if (!Subtarget->hasFlatScrRegister() &&
3238        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3239     report_fatal_error(Twine("invalid register \""
3240                              + StringRef(RegName)  + "\" for subtarget."));
3241   }
3242 
3243   switch (Reg) {
3244   case AMDGPU::M0:
3245   case AMDGPU::EXEC_LO:
3246   case AMDGPU::EXEC_HI:
3247   case AMDGPU::FLAT_SCR_LO:
3248   case AMDGPU::FLAT_SCR_HI:
3249     if (VT.getSizeInBits() == 32)
3250       return Reg;
3251     break;
3252   case AMDGPU::EXEC:
3253   case AMDGPU::FLAT_SCR:
3254     if (VT.getSizeInBits() == 64)
3255       return Reg;
3256     break;
3257   default:
3258     llvm_unreachable("missing register type checking");
3259   }
3260 
3261   report_fatal_error(Twine("invalid type for register \""
3262                            + StringRef(RegName) + "\"."));
3263 }
3264 
3265 // If kill is not the last instruction, split the block so kill is always a
3266 // proper terminator.
3267 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3268                                                     MachineBasicBlock *BB) const {
3269   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3270 
3271   MachineBasicBlock::iterator SplitPoint(&MI);
3272   ++SplitPoint;
3273 
3274   if (SplitPoint == BB->end()) {
3275     // Don't bother with a new block.
3276     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3277     return BB;
3278   }
3279 
3280   MachineFunction *MF = BB->getParent();
3281   MachineBasicBlock *SplitBB
3282     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3283 
3284   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3285   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3286 
3287   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3288   BB->addSuccessor(SplitBB);
3289 
3290   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3291   return SplitBB;
3292 }
3293 
3294 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3295 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3296 // be the first instruction in the remainder block.
3297 //
3298 /// \returns { LoopBody, Remainder }
3299 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3300 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3301   MachineFunction *MF = MBB.getParent();
3302   MachineBasicBlock::iterator I(&MI);
3303 
3304   // To insert the loop we need to split the block. Move everything after this
3305   // point to a new block, and insert a new empty block between the two.
3306   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3307   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3308   MachineFunction::iterator MBBI(MBB);
3309   ++MBBI;
3310 
3311   MF->insert(MBBI, LoopBB);
3312   MF->insert(MBBI, RemainderBB);
3313 
3314   LoopBB->addSuccessor(LoopBB);
3315   LoopBB->addSuccessor(RemainderBB);
3316 
3317   // Move the rest of the block into a new block.
3318   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3319 
3320   if (InstInLoop) {
3321     auto Next = std::next(I);
3322 
3323     // Move instruction to loop body.
3324     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3325 
3326     // Move the rest of the block.
3327     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3328   } else {
3329     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3330   }
3331 
3332   MBB.addSuccessor(LoopBB);
3333 
3334   return std::make_pair(LoopBB, RemainderBB);
3335 }
3336 
3337 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3338 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3339   MachineBasicBlock *MBB = MI.getParent();
3340   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3341   auto I = MI.getIterator();
3342   auto E = std::next(I);
3343 
3344   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3345     .addImm(0);
3346 
3347   MIBundleBuilder Bundler(*MBB, I, E);
3348   finalizeBundle(*MBB, Bundler.begin());
3349 }
3350 
3351 MachineBasicBlock *
3352 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3353                                          MachineBasicBlock *BB) const {
3354   const DebugLoc &DL = MI.getDebugLoc();
3355 
3356   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3357 
3358   MachineBasicBlock *LoopBB;
3359   MachineBasicBlock *RemainderBB;
3360   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3361 
3362   // Apparently kill flags are only valid if the def is in the same block?
3363   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3364     Src->setIsKill(false);
3365 
3366   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3367 
3368   MachineBasicBlock::iterator I = LoopBB->end();
3369 
3370   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3371     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3372 
3373   // Clear TRAP_STS.MEM_VIOL
3374   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3375     .addImm(0)
3376     .addImm(EncodedReg);
3377 
3378   bundleInstWithWaitcnt(MI);
3379 
3380   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3381 
3382   // Load and check TRAP_STS.MEM_VIOL
3383   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3384     .addImm(EncodedReg);
3385 
3386   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3387   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3388     .addReg(Reg, RegState::Kill)
3389     .addImm(0);
3390   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3391     .addMBB(LoopBB);
3392 
3393   return RemainderBB;
3394 }
3395 
3396 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3397 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3398 // will only do one iteration. In the worst case, this will loop 64 times.
3399 //
3400 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3401 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3402   const SIInstrInfo *TII,
3403   MachineRegisterInfo &MRI,
3404   MachineBasicBlock &OrigBB,
3405   MachineBasicBlock &LoopBB,
3406   const DebugLoc &DL,
3407   const MachineOperand &IdxReg,
3408   unsigned InitReg,
3409   unsigned ResultReg,
3410   unsigned PhiReg,
3411   unsigned InitSaveExecReg,
3412   int Offset,
3413   bool UseGPRIdxMode,
3414   bool IsIndirectSrc) {
3415   MachineFunction *MF = OrigBB.getParent();
3416   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3417   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3418   MachineBasicBlock::iterator I = LoopBB.begin();
3419 
3420   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3421   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3422   Register NewExec = MRI.createVirtualRegister(BoolRC);
3423   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3424   Register CondReg = MRI.createVirtualRegister(BoolRC);
3425 
3426   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3427     .addReg(InitReg)
3428     .addMBB(&OrigBB)
3429     .addReg(ResultReg)
3430     .addMBB(&LoopBB);
3431 
3432   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3433     .addReg(InitSaveExecReg)
3434     .addMBB(&OrigBB)
3435     .addReg(NewExec)
3436     .addMBB(&LoopBB);
3437 
3438   // Read the next variant <- also loop target.
3439   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3440     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3441 
3442   // Compare the just read M0 value to all possible Idx values.
3443   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3444     .addReg(CurrentIdxReg)
3445     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3446 
3447   // Update EXEC, save the original EXEC value to VCC.
3448   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3449                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3450           NewExec)
3451     .addReg(CondReg, RegState::Kill);
3452 
3453   MRI.setSimpleHint(NewExec, CondReg);
3454 
3455   if (UseGPRIdxMode) {
3456     unsigned IdxReg;
3457     if (Offset == 0) {
3458       IdxReg = CurrentIdxReg;
3459     } else {
3460       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3461       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3462         .addReg(CurrentIdxReg, RegState::Kill)
3463         .addImm(Offset);
3464     }
3465     unsigned IdxMode = IsIndirectSrc ?
3466       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3467     MachineInstr *SetOn =
3468       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3469       .addReg(IdxReg, RegState::Kill)
3470       .addImm(IdxMode);
3471     SetOn->getOperand(3).setIsUndef();
3472   } else {
3473     // Move index from VCC into M0
3474     if (Offset == 0) {
3475       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3476         .addReg(CurrentIdxReg, RegState::Kill);
3477     } else {
3478       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3479         .addReg(CurrentIdxReg, RegState::Kill)
3480         .addImm(Offset);
3481     }
3482   }
3483 
3484   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3485   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3486   MachineInstr *InsertPt =
3487     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3488                                                   : AMDGPU::S_XOR_B64_term), Exec)
3489       .addReg(Exec)
3490       .addReg(NewExec);
3491 
3492   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3493   // s_cbranch_scc0?
3494 
3495   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3496   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3497     .addMBB(&LoopBB);
3498 
3499   return InsertPt->getIterator();
3500 }
3501 
3502 // This has slightly sub-optimal regalloc when the source vector is killed by
3503 // the read. The register allocator does not understand that the kill is
3504 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3505 // subregister from it, using 1 more VGPR than necessary. This was saved when
3506 // this was expanded after register allocation.
3507 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3508                                                   MachineBasicBlock &MBB,
3509                                                   MachineInstr &MI,
3510                                                   unsigned InitResultReg,
3511                                                   unsigned PhiReg,
3512                                                   int Offset,
3513                                                   bool UseGPRIdxMode,
3514                                                   bool IsIndirectSrc) {
3515   MachineFunction *MF = MBB.getParent();
3516   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3517   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3518   MachineRegisterInfo &MRI = MF->getRegInfo();
3519   const DebugLoc &DL = MI.getDebugLoc();
3520   MachineBasicBlock::iterator I(&MI);
3521 
3522   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3523   Register DstReg = MI.getOperand(0).getReg();
3524   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3525   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3526   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3527   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3528 
3529   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3530 
3531   // Save the EXEC mask
3532   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3533     .addReg(Exec);
3534 
3535   MachineBasicBlock *LoopBB;
3536   MachineBasicBlock *RemainderBB;
3537   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3538 
3539   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3540 
3541   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3542                                       InitResultReg, DstReg, PhiReg, TmpExec,
3543                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3544   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3545   MachineFunction::iterator MBBI(LoopBB);
3546   ++MBBI;
3547   MF->insert(MBBI, LandingPad);
3548   LoopBB->removeSuccessor(RemainderBB);
3549   LandingPad->addSuccessor(RemainderBB);
3550   LoopBB->addSuccessor(LandingPad);
3551   MachineBasicBlock::iterator First = LandingPad->begin();
3552   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3553     .addReg(SaveExec);
3554 
3555   return InsPt;
3556 }
3557 
3558 // Returns subreg index, offset
3559 static std::pair<unsigned, int>
3560 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3561                             const TargetRegisterClass *SuperRC,
3562                             unsigned VecReg,
3563                             int Offset) {
3564   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3565 
3566   // Skip out of bounds offsets, or else we would end up using an undefined
3567   // register.
3568   if (Offset >= NumElts || Offset < 0)
3569     return std::make_pair(AMDGPU::sub0, Offset);
3570 
3571   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3572 }
3573 
3574 // Return true if the index is an SGPR and was set.
3575 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3576                                  MachineRegisterInfo &MRI,
3577                                  MachineInstr &MI,
3578                                  int Offset,
3579                                  bool UseGPRIdxMode,
3580                                  bool IsIndirectSrc) {
3581   MachineBasicBlock *MBB = MI.getParent();
3582   const DebugLoc &DL = MI.getDebugLoc();
3583   MachineBasicBlock::iterator I(&MI);
3584 
3585   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3586   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3587 
3588   assert(Idx->getReg() != AMDGPU::NoRegister);
3589 
3590   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3591     return false;
3592 
3593   if (UseGPRIdxMode) {
3594     unsigned IdxMode = IsIndirectSrc ?
3595       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3596     if (Offset == 0) {
3597       MachineInstr *SetOn =
3598           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3599               .add(*Idx)
3600               .addImm(IdxMode);
3601 
3602       SetOn->getOperand(3).setIsUndef();
3603     } else {
3604       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3605       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3606           .add(*Idx)
3607           .addImm(Offset);
3608       MachineInstr *SetOn =
3609         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3610         .addReg(Tmp, RegState::Kill)
3611         .addImm(IdxMode);
3612 
3613       SetOn->getOperand(3).setIsUndef();
3614     }
3615 
3616     return true;
3617   }
3618 
3619   if (Offset == 0) {
3620     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3621       .add(*Idx);
3622   } else {
3623     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3624       .add(*Idx)
3625       .addImm(Offset);
3626   }
3627 
3628   return true;
3629 }
3630 
3631 // Control flow needs to be inserted if indexing with a VGPR.
3632 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3633                                           MachineBasicBlock &MBB,
3634                                           const GCNSubtarget &ST) {
3635   const SIInstrInfo *TII = ST.getInstrInfo();
3636   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3637   MachineFunction *MF = MBB.getParent();
3638   MachineRegisterInfo &MRI = MF->getRegInfo();
3639 
3640   Register Dst = MI.getOperand(0).getReg();
3641   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3642   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3643 
3644   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3645 
3646   unsigned SubReg;
3647   std::tie(SubReg, Offset)
3648     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3649 
3650   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3651 
3652   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3653     MachineBasicBlock::iterator I(&MI);
3654     const DebugLoc &DL = MI.getDebugLoc();
3655 
3656     if (UseGPRIdxMode) {
3657       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3658       // to avoid interfering with other uses, so probably requires a new
3659       // optimization pass.
3660       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3661         .addReg(SrcReg, 0, SubReg)
3662         .addReg(SrcReg, RegState::Implicit)
3663         .addReg(AMDGPU::M0, RegState::Implicit);
3664       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3665     } else {
3666       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3667         .addReg(SrcReg, 0, SubReg)
3668         .addReg(SrcReg, RegState::Implicit);
3669     }
3670 
3671     MI.eraseFromParent();
3672 
3673     return &MBB;
3674   }
3675 
3676   const DebugLoc &DL = MI.getDebugLoc();
3677   MachineBasicBlock::iterator I(&MI);
3678 
3679   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3680   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3681 
3682   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3683 
3684   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3685                               Offset, UseGPRIdxMode, true);
3686   MachineBasicBlock *LoopBB = InsPt->getParent();
3687 
3688   if (UseGPRIdxMode) {
3689     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3690       .addReg(SrcReg, 0, SubReg)
3691       .addReg(SrcReg, RegState::Implicit)
3692       .addReg(AMDGPU::M0, RegState::Implicit);
3693     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3694   } else {
3695     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3696       .addReg(SrcReg, 0, SubReg)
3697       .addReg(SrcReg, RegState::Implicit);
3698   }
3699 
3700   MI.eraseFromParent();
3701 
3702   return LoopBB;
3703 }
3704 
3705 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3706                                           MachineBasicBlock &MBB,
3707                                           const GCNSubtarget &ST) {
3708   const SIInstrInfo *TII = ST.getInstrInfo();
3709   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3710   MachineFunction *MF = MBB.getParent();
3711   MachineRegisterInfo &MRI = MF->getRegInfo();
3712 
3713   Register Dst = MI.getOperand(0).getReg();
3714   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3715   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3716   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3717   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3718   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3719 
3720   // This can be an immediate, but will be folded later.
3721   assert(Val->getReg());
3722 
3723   unsigned SubReg;
3724   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3725                                                          SrcVec->getReg(),
3726                                                          Offset);
3727   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3728 
3729   if (Idx->getReg() == AMDGPU::NoRegister) {
3730     MachineBasicBlock::iterator I(&MI);
3731     const DebugLoc &DL = MI.getDebugLoc();
3732 
3733     assert(Offset == 0);
3734 
3735     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3736         .add(*SrcVec)
3737         .add(*Val)
3738         .addImm(SubReg);
3739 
3740     MI.eraseFromParent();
3741     return &MBB;
3742   }
3743 
3744   const MCInstrDesc &MovRelDesc
3745     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3746 
3747   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3748     MachineBasicBlock::iterator I(&MI);
3749     const DebugLoc &DL = MI.getDebugLoc();
3750     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3751       .addReg(SrcVec->getReg())
3752       .add(*Val)
3753       .addImm(SubReg);
3754     if (UseGPRIdxMode)
3755       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3756 
3757     MI.eraseFromParent();
3758     return &MBB;
3759   }
3760 
3761   if (Val->isReg())
3762     MRI.clearKillFlags(Val->getReg());
3763 
3764   const DebugLoc &DL = MI.getDebugLoc();
3765 
3766   Register PhiReg = MRI.createVirtualRegister(VecRC);
3767 
3768   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3769                               Offset, UseGPRIdxMode, false);
3770   MachineBasicBlock *LoopBB = InsPt->getParent();
3771 
3772   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3773     .addReg(PhiReg)
3774     .add(*Val)
3775     .addImm(AMDGPU::sub0);
3776   if (UseGPRIdxMode)
3777     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3778 
3779   MI.eraseFromParent();
3780   return LoopBB;
3781 }
3782 
3783 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3784   MachineInstr &MI, MachineBasicBlock *BB) const {
3785 
3786   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3787   MachineFunction *MF = BB->getParent();
3788   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3789 
3790   switch (MI.getOpcode()) {
3791   case AMDGPU::S_UADDO_PSEUDO:
3792   case AMDGPU::S_USUBO_PSEUDO: {
3793     const DebugLoc &DL = MI.getDebugLoc();
3794     MachineOperand &Dest0 = MI.getOperand(0);
3795     MachineOperand &Dest1 = MI.getOperand(1);
3796     MachineOperand &Src0 = MI.getOperand(2);
3797     MachineOperand &Src1 = MI.getOperand(3);
3798 
3799     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3800                        ? AMDGPU::S_ADD_I32
3801                        : AMDGPU::S_SUB_I32;
3802     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3803 
3804     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3805         .addImm(1)
3806         .addImm(0);
3807 
3808     MI.eraseFromParent();
3809     return BB;
3810   }
3811   case AMDGPU::S_ADD_U64_PSEUDO:
3812   case AMDGPU::S_SUB_U64_PSEUDO: {
3813     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3814     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3815     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3816     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3817     const DebugLoc &DL = MI.getDebugLoc();
3818 
3819     MachineOperand &Dest = MI.getOperand(0);
3820     MachineOperand &Src0 = MI.getOperand(1);
3821     MachineOperand &Src1 = MI.getOperand(2);
3822 
3823     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3824     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3825 
3826     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3827         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3828     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3829         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3830 
3831     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3832         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3833     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3834         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3835 
3836     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3837 
3838     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3839     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3840     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3841     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3842     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3843         .addReg(DestSub0)
3844         .addImm(AMDGPU::sub0)
3845         .addReg(DestSub1)
3846         .addImm(AMDGPU::sub1);
3847     MI.eraseFromParent();
3848     return BB;
3849   }
3850   case AMDGPU::V_ADD_U64_PSEUDO:
3851   case AMDGPU::V_SUB_U64_PSEUDO: {
3852     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3853     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3854     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3855     const DebugLoc &DL = MI.getDebugLoc();
3856 
3857     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3858 
3859     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3860 
3861     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3862     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3863 
3864     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3865     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3866 
3867     MachineOperand &Dest = MI.getOperand(0);
3868     MachineOperand &Src0 = MI.getOperand(1);
3869     MachineOperand &Src1 = MI.getOperand(2);
3870 
3871     const TargetRegisterClass *Src0RC = Src0.isReg()
3872                                             ? MRI.getRegClass(Src0.getReg())
3873                                             : &AMDGPU::VReg_64RegClass;
3874     const TargetRegisterClass *Src1RC = Src1.isReg()
3875                                             ? MRI.getRegClass(Src1.getReg())
3876                                             : &AMDGPU::VReg_64RegClass;
3877 
3878     const TargetRegisterClass *Src0SubRC =
3879         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3880     const TargetRegisterClass *Src1SubRC =
3881         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3882 
3883     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3884         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3885     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3886         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3887 
3888     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3889         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3890     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3891         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3892 
3893     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3894     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3895                                .addReg(CarryReg, RegState::Define)
3896                                .add(SrcReg0Sub0)
3897                                .add(SrcReg1Sub0)
3898                                .addImm(0); // clamp bit
3899 
3900     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3901     MachineInstr *HiHalf =
3902         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3903             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3904             .add(SrcReg0Sub1)
3905             .add(SrcReg1Sub1)
3906             .addReg(CarryReg, RegState::Kill)
3907             .addImm(0); // clamp bit
3908 
3909     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3910         .addReg(DestSub0)
3911         .addImm(AMDGPU::sub0)
3912         .addReg(DestSub1)
3913         .addImm(AMDGPU::sub1);
3914     TII->legalizeOperands(*LoHalf);
3915     TII->legalizeOperands(*HiHalf);
3916     MI.eraseFromParent();
3917     return BB;
3918   }
3919   case AMDGPU::S_ADD_CO_PSEUDO:
3920   case AMDGPU::S_SUB_CO_PSEUDO: {
3921     // This pseudo has a chance to be selected
3922     // only from uniform add/subcarry node. All the VGPR operands
3923     // therefore assumed to be splat vectors.
3924     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3925     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3926     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3927     MachineBasicBlock::iterator MII = MI;
3928     const DebugLoc &DL = MI.getDebugLoc();
3929     MachineOperand &Dest = MI.getOperand(0);
3930     MachineOperand &CarryDest = MI.getOperand(1);
3931     MachineOperand &Src0 = MI.getOperand(2);
3932     MachineOperand &Src1 = MI.getOperand(3);
3933     MachineOperand &Src2 = MI.getOperand(4);
3934     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3935                        ? AMDGPU::S_ADDC_U32
3936                        : AMDGPU::S_SUBB_U32;
3937     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3938       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3939       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3940           .addReg(Src0.getReg());
3941       Src0.setReg(RegOp0);
3942     }
3943     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3944       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3945       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3946           .addReg(Src1.getReg());
3947       Src1.setReg(RegOp1);
3948     }
3949     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3950     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3951       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3952           .addReg(Src2.getReg());
3953       Src2.setReg(RegOp2);
3954     }
3955 
3956     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3957       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3958           .addReg(Src2.getReg())
3959           .addImm(0);
3960     } else {
3961       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3962           .addReg(Src2.getReg())
3963           .addImm(0);
3964     }
3965 
3966     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3967 
3968     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
3969       .addReg(AMDGPU::SCC);
3970     MI.eraseFromParent();
3971     return BB;
3972   }
3973   case AMDGPU::SI_INIT_M0: {
3974     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3975             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3976         .add(MI.getOperand(0));
3977     MI.eraseFromParent();
3978     return BB;
3979   }
3980   case AMDGPU::SI_INIT_EXEC:
3981     // This should be before all vector instructions.
3982     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3983             AMDGPU::EXEC)
3984         .addImm(MI.getOperand(0).getImm());
3985     MI.eraseFromParent();
3986     return BB;
3987 
3988   case AMDGPU::SI_INIT_EXEC_LO:
3989     // This should be before all vector instructions.
3990     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3991             AMDGPU::EXEC_LO)
3992         .addImm(MI.getOperand(0).getImm());
3993     MI.eraseFromParent();
3994     return BB;
3995 
3996   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3997     // Extract the thread count from an SGPR input and set EXEC accordingly.
3998     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3999     //
4000     // S_BFE_U32 count, input, {shift, 7}
4001     // S_BFM_B64 exec, count, 0
4002     // S_CMP_EQ_U32 count, 64
4003     // S_CMOV_B64 exec, -1
4004     MachineInstr *FirstMI = &*BB->begin();
4005     MachineRegisterInfo &MRI = MF->getRegInfo();
4006     Register InputReg = MI.getOperand(0).getReg();
4007     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4008     bool Found = false;
4009 
4010     // Move the COPY of the input reg to the beginning, so that we can use it.
4011     for (auto I = BB->begin(); I != &MI; I++) {
4012       if (I->getOpcode() != TargetOpcode::COPY ||
4013           I->getOperand(0).getReg() != InputReg)
4014         continue;
4015 
4016       if (I == FirstMI) {
4017         FirstMI = &*++BB->begin();
4018       } else {
4019         I->removeFromParent();
4020         BB->insert(FirstMI, &*I);
4021       }
4022       Found = true;
4023       break;
4024     }
4025     assert(Found);
4026     (void)Found;
4027 
4028     // This should be before all vector instructions.
4029     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4030     bool isWave32 = getSubtarget()->isWave32();
4031     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4032     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4033         .addReg(InputReg)
4034         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4035     BuildMI(*BB, FirstMI, DebugLoc(),
4036             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4037             Exec)
4038         .addReg(CountReg)
4039         .addImm(0);
4040     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4041         .addReg(CountReg, RegState::Kill)
4042         .addImm(getSubtarget()->getWavefrontSize());
4043     BuildMI(*BB, FirstMI, DebugLoc(),
4044             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4045             Exec)
4046         .addImm(-1);
4047     MI.eraseFromParent();
4048     return BB;
4049   }
4050 
4051   case AMDGPU::GET_GROUPSTATICSIZE: {
4052     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4053            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4054     DebugLoc DL = MI.getDebugLoc();
4055     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4056         .add(MI.getOperand(0))
4057         .addImm(MFI->getLDSSize());
4058     MI.eraseFromParent();
4059     return BB;
4060   }
4061   case AMDGPU::SI_INDIRECT_SRC_V1:
4062   case AMDGPU::SI_INDIRECT_SRC_V2:
4063   case AMDGPU::SI_INDIRECT_SRC_V4:
4064   case AMDGPU::SI_INDIRECT_SRC_V8:
4065   case AMDGPU::SI_INDIRECT_SRC_V16:
4066   case AMDGPU::SI_INDIRECT_SRC_V32:
4067     return emitIndirectSrc(MI, *BB, *getSubtarget());
4068   case AMDGPU::SI_INDIRECT_DST_V1:
4069   case AMDGPU::SI_INDIRECT_DST_V2:
4070   case AMDGPU::SI_INDIRECT_DST_V4:
4071   case AMDGPU::SI_INDIRECT_DST_V8:
4072   case AMDGPU::SI_INDIRECT_DST_V16:
4073   case AMDGPU::SI_INDIRECT_DST_V32:
4074     return emitIndirectDst(MI, *BB, *getSubtarget());
4075   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4076   case AMDGPU::SI_KILL_I1_PSEUDO:
4077     return splitKillBlock(MI, BB);
4078   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4079     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4080     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4081     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4082 
4083     Register Dst = MI.getOperand(0).getReg();
4084     Register Src0 = MI.getOperand(1).getReg();
4085     Register Src1 = MI.getOperand(2).getReg();
4086     const DebugLoc &DL = MI.getDebugLoc();
4087     Register SrcCond = MI.getOperand(3).getReg();
4088 
4089     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4090     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4091     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4092     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4093 
4094     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4095       .addReg(SrcCond);
4096     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4097       .addImm(0)
4098       .addReg(Src0, 0, AMDGPU::sub0)
4099       .addImm(0)
4100       .addReg(Src1, 0, AMDGPU::sub0)
4101       .addReg(SrcCondCopy);
4102     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4103       .addImm(0)
4104       .addReg(Src0, 0, AMDGPU::sub1)
4105       .addImm(0)
4106       .addReg(Src1, 0, AMDGPU::sub1)
4107       .addReg(SrcCondCopy);
4108 
4109     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4110       .addReg(DstLo)
4111       .addImm(AMDGPU::sub0)
4112       .addReg(DstHi)
4113       .addImm(AMDGPU::sub1);
4114     MI.eraseFromParent();
4115     return BB;
4116   }
4117   case AMDGPU::SI_BR_UNDEF: {
4118     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4119     const DebugLoc &DL = MI.getDebugLoc();
4120     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4121                            .add(MI.getOperand(0));
4122     Br->getOperand(1).setIsUndef(true); // read undef SCC
4123     MI.eraseFromParent();
4124     return BB;
4125   }
4126   case AMDGPU::ADJCALLSTACKUP:
4127   case AMDGPU::ADJCALLSTACKDOWN: {
4128     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4129     MachineInstrBuilder MIB(*MF, &MI);
4130 
4131     // Add an implicit use of the frame offset reg to prevent the restore copy
4132     // inserted after the call from being reorderd after stack operations in the
4133     // the caller's frame.
4134     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4135         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4136         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4137     return BB;
4138   }
4139   case AMDGPU::SI_CALL_ISEL: {
4140     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4141     const DebugLoc &DL = MI.getDebugLoc();
4142 
4143     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4144 
4145     MachineInstrBuilder MIB;
4146     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4147 
4148     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4149       MIB.add(MI.getOperand(I));
4150 
4151     MIB.cloneMemRefs(MI);
4152     MI.eraseFromParent();
4153     return BB;
4154   }
4155   case AMDGPU::V_ADD_CO_U32_e32:
4156   case AMDGPU::V_SUB_CO_U32_e32:
4157   case AMDGPU::V_SUBREV_CO_U32_e32: {
4158     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4159     const DebugLoc &DL = MI.getDebugLoc();
4160     unsigned Opc = MI.getOpcode();
4161 
4162     bool NeedClampOperand = false;
4163     if (TII->pseudoToMCOpcode(Opc) == -1) {
4164       Opc = AMDGPU::getVOPe64(Opc);
4165       NeedClampOperand = true;
4166     }
4167 
4168     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4169     if (TII->isVOP3(*I)) {
4170       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4171       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4172       I.addReg(TRI->getVCC(), RegState::Define);
4173     }
4174     I.add(MI.getOperand(1))
4175      .add(MI.getOperand(2));
4176     if (NeedClampOperand)
4177       I.addImm(0); // clamp bit for e64 encoding
4178 
4179     TII->legalizeOperands(*I);
4180 
4181     MI.eraseFromParent();
4182     return BB;
4183   }
4184   case AMDGPU::DS_GWS_INIT:
4185   case AMDGPU::DS_GWS_SEMA_V:
4186   case AMDGPU::DS_GWS_SEMA_BR:
4187   case AMDGPU::DS_GWS_SEMA_P:
4188   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4189   case AMDGPU::DS_GWS_BARRIER:
4190     // A s_waitcnt 0 is required to be the instruction immediately following.
4191     if (getSubtarget()->hasGWSAutoReplay()) {
4192       bundleInstWithWaitcnt(MI);
4193       return BB;
4194     }
4195 
4196     return emitGWSMemViolTestLoop(MI, BB);
4197   case AMDGPU::S_SETREG_B32: {
4198     if (!getSubtarget()->hasDenormModeInst())
4199       return BB;
4200 
4201     // Try to optimize cases that only set the denormal mode or rounding mode.
4202     //
4203     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4204     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4205     // instead.
4206     //
4207     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4208     // allow you to have a no side effect instruction in the output of a
4209     // sideeffecting pattern.
4210 
4211     // TODO: Should also emit a no side effects pseudo if only FP bits are
4212     // touched, even if not all of them or to a variable.
4213     unsigned ID, Offset, Width;
4214     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4215     if (ID != AMDGPU::Hwreg::ID_MODE)
4216       return BB;
4217 
4218     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4219     const unsigned SetMask = WidthMask << Offset;
4220     unsigned SetDenormOp = 0;
4221     unsigned SetRoundOp = 0;
4222 
4223     // The dedicated instructions can only set the whole denorm or round mode at
4224     // once, not a subset of bits in either.
4225     if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4226                                   AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) {
4227       // If this fully sets both the round and denorm mode, emit the two
4228       // dedicated instructions for these.
4229       assert(Offset == 0);
4230       SetRoundOp = AMDGPU::S_ROUND_MODE;
4231       SetDenormOp = AMDGPU::S_DENORM_MODE;
4232     } else if (Width == 4) {
4233       if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) {
4234         SetRoundOp = AMDGPU::S_ROUND_MODE;
4235         assert(Offset == 0);
4236       } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) {
4237         SetDenormOp = AMDGPU::S_DENORM_MODE;
4238         assert(Offset == 4);
4239       }
4240     }
4241 
4242     if (SetRoundOp || SetDenormOp) {
4243       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4244       MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4245       if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4246         unsigned ImmVal = Def->getOperand(1).getImm();
4247         if (SetRoundOp) {
4248           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4249             .addImm(ImmVal & 0xf);
4250 
4251           // If we also have the denorm mode, get just the denorm mode bits.
4252           ImmVal >>= 4;
4253         }
4254 
4255         if (SetDenormOp) {
4256           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4257             .addImm(ImmVal & 0xf);
4258         }
4259 
4260         MI.eraseFromParent();
4261       }
4262     }
4263 
4264     return BB;
4265   }
4266   default:
4267     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4268   }
4269 }
4270 
4271 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4272   return isTypeLegal(VT.getScalarType());
4273 }
4274 
4275 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4276   // This currently forces unfolding various combinations of fsub into fma with
4277   // free fneg'd operands. As long as we have fast FMA (controlled by
4278   // isFMAFasterThanFMulAndFAdd), we should perform these.
4279 
4280   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4281   // most of these combines appear to be cycle neutral but save on instruction
4282   // count / code size.
4283   return true;
4284 }
4285 
4286 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4287                                          EVT VT) const {
4288   if (!VT.isVector()) {
4289     return MVT::i1;
4290   }
4291   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4292 }
4293 
4294 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4295   // TODO: Should i16 be used always if legal? For now it would force VALU
4296   // shifts.
4297   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4298 }
4299 
4300 // Answering this is somewhat tricky and depends on the specific device which
4301 // have different rates for fma or all f64 operations.
4302 //
4303 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4304 // regardless of which device (although the number of cycles differs between
4305 // devices), so it is always profitable for f64.
4306 //
4307 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4308 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4309 // which we can always do even without fused FP ops since it returns the same
4310 // result as the separate operations and since it is always full
4311 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4312 // however does not support denormals, so we do report fma as faster if we have
4313 // a fast fma device and require denormals.
4314 //
4315 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4316                                                   EVT VT) const {
4317   VT = VT.getScalarType();
4318 
4319   switch (VT.getSimpleVT().SimpleTy) {
4320   case MVT::f32: {
4321     // If mad is not available this depends only on if f32 fma is full rate.
4322     if (!Subtarget->hasMadMacF32Insts())
4323       return Subtarget->hasFastFMAF32();
4324 
4325     // Otherwise f32 mad is always full rate and returns the same result as
4326     // the separate operations so should be preferred over fma.
4327     // However does not support denomals.
4328     if (hasFP32Denormals(MF))
4329       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4330 
4331     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4332     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4333   }
4334   case MVT::f64:
4335     return true;
4336   case MVT::f16:
4337     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4338   default:
4339     break;
4340   }
4341 
4342   return false;
4343 }
4344 
4345 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4346                                    const SDNode *N) const {
4347   // TODO: Check future ftz flag
4348   // v_mad_f32/v_mac_f32 do not support denormals.
4349   EVT VT = N->getValueType(0);
4350   if (VT == MVT::f32)
4351     return Subtarget->hasMadMacF32Insts() &&
4352            !hasFP32Denormals(DAG.getMachineFunction());
4353   if (VT == MVT::f16) {
4354     return Subtarget->hasMadF16() &&
4355            !hasFP64FP16Denormals(DAG.getMachineFunction());
4356   }
4357 
4358   return false;
4359 }
4360 
4361 //===----------------------------------------------------------------------===//
4362 // Custom DAG Lowering Operations
4363 //===----------------------------------------------------------------------===//
4364 
4365 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4366 // wider vector type is legal.
4367 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4368                                              SelectionDAG &DAG) const {
4369   unsigned Opc = Op.getOpcode();
4370   EVT VT = Op.getValueType();
4371   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4372 
4373   SDValue Lo, Hi;
4374   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4375 
4376   SDLoc SL(Op);
4377   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4378                              Op->getFlags());
4379   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4380                              Op->getFlags());
4381 
4382   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4383 }
4384 
4385 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4386 // wider vector type is legal.
4387 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4388                                               SelectionDAG &DAG) const {
4389   unsigned Opc = Op.getOpcode();
4390   EVT VT = Op.getValueType();
4391   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4392 
4393   SDValue Lo0, Hi0;
4394   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4395   SDValue Lo1, Hi1;
4396   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4397 
4398   SDLoc SL(Op);
4399 
4400   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4401                              Op->getFlags());
4402   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4403                              Op->getFlags());
4404 
4405   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4406 }
4407 
4408 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4409                                               SelectionDAG &DAG) const {
4410   unsigned Opc = Op.getOpcode();
4411   EVT VT = Op.getValueType();
4412   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4413 
4414   SDValue Lo0, Hi0;
4415   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4416   SDValue Lo1, Hi1;
4417   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4418   SDValue Lo2, Hi2;
4419   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4420 
4421   SDLoc SL(Op);
4422 
4423   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4424                              Op->getFlags());
4425   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4426                              Op->getFlags());
4427 
4428   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4429 }
4430 
4431 
4432 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4433   switch (Op.getOpcode()) {
4434   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4435   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4436   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4437   case ISD::LOAD: {
4438     SDValue Result = LowerLOAD(Op, DAG);
4439     assert((!Result.getNode() ||
4440             Result.getNode()->getNumValues() == 2) &&
4441            "Load should return a value and a chain");
4442     return Result;
4443   }
4444 
4445   case ISD::FSIN:
4446   case ISD::FCOS:
4447     return LowerTrig(Op, DAG);
4448   case ISD::SELECT: return LowerSELECT(Op, DAG);
4449   case ISD::FDIV: return LowerFDIV(Op, DAG);
4450   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4451   case ISD::STORE: return LowerSTORE(Op, DAG);
4452   case ISD::GlobalAddress: {
4453     MachineFunction &MF = DAG.getMachineFunction();
4454     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4455     return LowerGlobalAddress(MFI, Op, DAG);
4456   }
4457   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4458   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4459   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4460   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4461   case ISD::INSERT_SUBVECTOR:
4462     return lowerINSERT_SUBVECTOR(Op, DAG);
4463   case ISD::INSERT_VECTOR_ELT:
4464     return lowerINSERT_VECTOR_ELT(Op, DAG);
4465   case ISD::EXTRACT_VECTOR_ELT:
4466     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4467   case ISD::VECTOR_SHUFFLE:
4468     return lowerVECTOR_SHUFFLE(Op, DAG);
4469   case ISD::BUILD_VECTOR:
4470     return lowerBUILD_VECTOR(Op, DAG);
4471   case ISD::FP_ROUND:
4472     return lowerFP_ROUND(Op, DAG);
4473   case ISD::TRAP:
4474     return lowerTRAP(Op, DAG);
4475   case ISD::DEBUGTRAP:
4476     return lowerDEBUGTRAP(Op, DAG);
4477   case ISD::FABS:
4478   case ISD::FNEG:
4479   case ISD::FCANONICALIZE:
4480   case ISD::BSWAP:
4481     return splitUnaryVectorOp(Op, DAG);
4482   case ISD::FMINNUM:
4483   case ISD::FMAXNUM:
4484     return lowerFMINNUM_FMAXNUM(Op, DAG);
4485   case ISD::FMA:
4486     return splitTernaryVectorOp(Op, DAG);
4487   case ISD::SHL:
4488   case ISD::SRA:
4489   case ISD::SRL:
4490   case ISD::ADD:
4491   case ISD::SUB:
4492   case ISD::MUL:
4493   case ISD::SMIN:
4494   case ISD::SMAX:
4495   case ISD::UMIN:
4496   case ISD::UMAX:
4497   case ISD::FADD:
4498   case ISD::FMUL:
4499   case ISD::FMINNUM_IEEE:
4500   case ISD::FMAXNUM_IEEE:
4501   case ISD::UADDSAT:
4502   case ISD::USUBSAT:
4503   case ISD::SADDSAT:
4504   case ISD::SSUBSAT:
4505     return splitBinaryVectorOp(Op, DAG);
4506   case ISD::SMULO:
4507   case ISD::UMULO:
4508     return lowerXMULO(Op, DAG);
4509   case ISD::DYNAMIC_STACKALLOC:
4510     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4511   }
4512   return SDValue();
4513 }
4514 
4515 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4516                                        const SDLoc &DL,
4517                                        SelectionDAG &DAG, bool Unpacked) {
4518   if (!LoadVT.isVector())
4519     return Result;
4520 
4521   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4522     // Truncate to v2i16/v4i16.
4523     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4524 
4525     // Workaround legalizer not scalarizing truncate after vector op
4526     // legalization but not creating intermediate vector trunc.
4527     SmallVector<SDValue, 4> Elts;
4528     DAG.ExtractVectorElements(Result, Elts);
4529     for (SDValue &Elt : Elts)
4530       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4531 
4532     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4533 
4534     // Bitcast to original type (v2f16/v4f16).
4535     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4536   }
4537 
4538   // Cast back to the original packed type.
4539   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4540 }
4541 
4542 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4543                                               MemSDNode *M,
4544                                               SelectionDAG &DAG,
4545                                               ArrayRef<SDValue> Ops,
4546                                               bool IsIntrinsic) const {
4547   SDLoc DL(M);
4548 
4549   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4550   EVT LoadVT = M->getValueType(0);
4551 
4552   EVT EquivLoadVT = LoadVT;
4553   if (Unpacked && LoadVT.isVector()) {
4554     EquivLoadVT = LoadVT.isVector() ?
4555       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4556                        LoadVT.getVectorNumElements()) : LoadVT;
4557   }
4558 
4559   // Change from v4f16/v2f16 to EquivLoadVT.
4560   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4561 
4562   SDValue Load
4563     = DAG.getMemIntrinsicNode(
4564       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4565       VTList, Ops, M->getMemoryVT(),
4566       M->getMemOperand());
4567   if (!Unpacked) // Just adjusted the opcode.
4568     return Load;
4569 
4570   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4571 
4572   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4573 }
4574 
4575 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4576                                              SelectionDAG &DAG,
4577                                              ArrayRef<SDValue> Ops) const {
4578   SDLoc DL(M);
4579   EVT LoadVT = M->getValueType(0);
4580   EVT EltType = LoadVT.getScalarType();
4581   EVT IntVT = LoadVT.changeTypeToInteger();
4582 
4583   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4584 
4585   unsigned Opc =
4586       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4587 
4588   if (IsD16) {
4589     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4590   }
4591 
4592   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4593   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4594     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4595 
4596   if (isTypeLegal(LoadVT)) {
4597     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4598                                M->getMemOperand(), DAG);
4599   }
4600 
4601   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4602   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4603   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4604                                         M->getMemOperand(), DAG);
4605   return DAG.getMergeValues(
4606       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4607       DL);
4608 }
4609 
4610 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4611                                   SDNode *N, SelectionDAG &DAG) {
4612   EVT VT = N->getValueType(0);
4613   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4614   unsigned CondCode = CD->getZExtValue();
4615   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4616     return DAG.getUNDEF(VT);
4617 
4618   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4619 
4620   SDValue LHS = N->getOperand(1);
4621   SDValue RHS = N->getOperand(2);
4622 
4623   SDLoc DL(N);
4624 
4625   EVT CmpVT = LHS.getValueType();
4626   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4627     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4628       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4629     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4630     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4631   }
4632 
4633   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4634 
4635   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4636   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4637 
4638   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4639                               DAG.getCondCode(CCOpcode));
4640   if (VT.bitsEq(CCVT))
4641     return SetCC;
4642   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4643 }
4644 
4645 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4646                                   SDNode *N, SelectionDAG &DAG) {
4647   EVT VT = N->getValueType(0);
4648   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4649 
4650   unsigned CondCode = CD->getZExtValue();
4651   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4652     return DAG.getUNDEF(VT);
4653 
4654   SDValue Src0 = N->getOperand(1);
4655   SDValue Src1 = N->getOperand(2);
4656   EVT CmpVT = Src0.getValueType();
4657   SDLoc SL(N);
4658 
4659   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4660     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4661     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4662   }
4663 
4664   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4665   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4666   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4667   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4668   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4669                               Src1, DAG.getCondCode(CCOpcode));
4670   if (VT.bitsEq(CCVT))
4671     return SetCC;
4672   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4673 }
4674 
4675 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4676                                     SelectionDAG &DAG) {
4677   EVT VT = N->getValueType(0);
4678   SDValue Src = N->getOperand(1);
4679   SDLoc SL(N);
4680 
4681   if (Src.getOpcode() == ISD::SETCC) {
4682     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4683     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4684                        Src.getOperand(1), Src.getOperand(2));
4685   }
4686   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4687     // (ballot 0) -> 0
4688     if (Arg->isNullValue())
4689       return DAG.getConstant(0, SL, VT);
4690 
4691     // (ballot 1) -> EXEC/EXEC_LO
4692     if (Arg->isOne()) {
4693       Register Exec;
4694       if (VT.getScalarSizeInBits() == 32)
4695         Exec = AMDGPU::EXEC_LO;
4696       else if (VT.getScalarSizeInBits() == 64)
4697         Exec = AMDGPU::EXEC;
4698       else
4699         return SDValue();
4700 
4701       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4702     }
4703   }
4704 
4705   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4706   // ISD::SETNE)
4707   return DAG.getNode(
4708       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4709       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4710 }
4711 
4712 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4713                                           SmallVectorImpl<SDValue> &Results,
4714                                           SelectionDAG &DAG) const {
4715   switch (N->getOpcode()) {
4716   case ISD::INSERT_VECTOR_ELT: {
4717     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4718       Results.push_back(Res);
4719     return;
4720   }
4721   case ISD::EXTRACT_VECTOR_ELT: {
4722     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4723       Results.push_back(Res);
4724     return;
4725   }
4726   case ISD::INTRINSIC_WO_CHAIN: {
4727     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4728     switch (IID) {
4729     case Intrinsic::amdgcn_cvt_pkrtz: {
4730       SDValue Src0 = N->getOperand(1);
4731       SDValue Src1 = N->getOperand(2);
4732       SDLoc SL(N);
4733       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4734                                 Src0, Src1);
4735       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4736       return;
4737     }
4738     case Intrinsic::amdgcn_cvt_pknorm_i16:
4739     case Intrinsic::amdgcn_cvt_pknorm_u16:
4740     case Intrinsic::amdgcn_cvt_pk_i16:
4741     case Intrinsic::amdgcn_cvt_pk_u16: {
4742       SDValue Src0 = N->getOperand(1);
4743       SDValue Src1 = N->getOperand(2);
4744       SDLoc SL(N);
4745       unsigned Opcode;
4746 
4747       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4748         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4749       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4750         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4751       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4752         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4753       else
4754         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4755 
4756       EVT VT = N->getValueType(0);
4757       if (isTypeLegal(VT))
4758         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4759       else {
4760         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4761         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4762       }
4763       return;
4764     }
4765     }
4766     break;
4767   }
4768   case ISD::INTRINSIC_W_CHAIN: {
4769     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4770       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4771         // FIXME: Hacky
4772         Results.push_back(Res.getOperand(0));
4773         Results.push_back(Res.getOperand(1));
4774       } else {
4775         Results.push_back(Res);
4776         Results.push_back(Res.getValue(1));
4777       }
4778       return;
4779     }
4780 
4781     break;
4782   }
4783   case ISD::SELECT: {
4784     SDLoc SL(N);
4785     EVT VT = N->getValueType(0);
4786     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4787     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4788     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4789 
4790     EVT SelectVT = NewVT;
4791     if (NewVT.bitsLT(MVT::i32)) {
4792       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4793       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4794       SelectVT = MVT::i32;
4795     }
4796 
4797     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4798                                     N->getOperand(0), LHS, RHS);
4799 
4800     if (NewVT != SelectVT)
4801       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4802     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4803     return;
4804   }
4805   case ISD::FNEG: {
4806     if (N->getValueType(0) != MVT::v2f16)
4807       break;
4808 
4809     SDLoc SL(N);
4810     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4811 
4812     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4813                              BC,
4814                              DAG.getConstant(0x80008000, SL, MVT::i32));
4815     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4816     return;
4817   }
4818   case ISD::FABS: {
4819     if (N->getValueType(0) != MVT::v2f16)
4820       break;
4821 
4822     SDLoc SL(N);
4823     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4824 
4825     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4826                              BC,
4827                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4828     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4829     return;
4830   }
4831   default:
4832     break;
4833   }
4834 }
4835 
4836 /// Helper function for LowerBRCOND
4837 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4838 
4839   SDNode *Parent = Value.getNode();
4840   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4841        I != E; ++I) {
4842 
4843     if (I.getUse().get() != Value)
4844       continue;
4845 
4846     if (I->getOpcode() == Opcode)
4847       return *I;
4848   }
4849   return nullptr;
4850 }
4851 
4852 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4853   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4854     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4855     case Intrinsic::amdgcn_if:
4856       return AMDGPUISD::IF;
4857     case Intrinsic::amdgcn_else:
4858       return AMDGPUISD::ELSE;
4859     case Intrinsic::amdgcn_loop:
4860       return AMDGPUISD::LOOP;
4861     case Intrinsic::amdgcn_end_cf:
4862       llvm_unreachable("should not occur");
4863     default:
4864       return 0;
4865     }
4866   }
4867 
4868   // break, if_break, else_break are all only used as inputs to loop, not
4869   // directly as branch conditions.
4870   return 0;
4871 }
4872 
4873 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4874   const Triple &TT = getTargetMachine().getTargetTriple();
4875   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4876           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4877          AMDGPU::shouldEmitConstantsToTextSection(TT);
4878 }
4879 
4880 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4881   // FIXME: Either avoid relying on address space here or change the default
4882   // address space for functions to avoid the explicit check.
4883   return (GV->getValueType()->isFunctionTy() ||
4884           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4885          !shouldEmitFixup(GV) &&
4886          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4887 }
4888 
4889 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4890   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4891 }
4892 
4893 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4894   if (!GV->hasExternalLinkage())
4895     return true;
4896 
4897   const auto OS = getTargetMachine().getTargetTriple().getOS();
4898   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4899 }
4900 
4901 /// This transforms the control flow intrinsics to get the branch destination as
4902 /// last parameter, also switches branch target with BR if the need arise
4903 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4904                                       SelectionDAG &DAG) const {
4905   SDLoc DL(BRCOND);
4906 
4907   SDNode *Intr = BRCOND.getOperand(1).getNode();
4908   SDValue Target = BRCOND.getOperand(2);
4909   SDNode *BR = nullptr;
4910   SDNode *SetCC = nullptr;
4911 
4912   if (Intr->getOpcode() == ISD::SETCC) {
4913     // As long as we negate the condition everything is fine
4914     SetCC = Intr;
4915     Intr = SetCC->getOperand(0).getNode();
4916 
4917   } else {
4918     // Get the target from BR if we don't negate the condition
4919     BR = findUser(BRCOND, ISD::BR);
4920     assert(BR && "brcond missing unconditional branch user");
4921     Target = BR->getOperand(1);
4922   }
4923 
4924   unsigned CFNode = isCFIntrinsic(Intr);
4925   if (CFNode == 0) {
4926     // This is a uniform branch so we don't need to legalize.
4927     return BRCOND;
4928   }
4929 
4930   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4931                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4932 
4933   assert(!SetCC ||
4934         (SetCC->getConstantOperandVal(1) == 1 &&
4935          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4936                                                              ISD::SETNE));
4937 
4938   // operands of the new intrinsic call
4939   SmallVector<SDValue, 4> Ops;
4940   if (HaveChain)
4941     Ops.push_back(BRCOND.getOperand(0));
4942 
4943   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4944   Ops.push_back(Target);
4945 
4946   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4947 
4948   // build the new intrinsic call
4949   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4950 
4951   if (!HaveChain) {
4952     SDValue Ops[] =  {
4953       SDValue(Result, 0),
4954       BRCOND.getOperand(0)
4955     };
4956 
4957     Result = DAG.getMergeValues(Ops, DL).getNode();
4958   }
4959 
4960   if (BR) {
4961     // Give the branch instruction our target
4962     SDValue Ops[] = {
4963       BR->getOperand(0),
4964       BRCOND.getOperand(2)
4965     };
4966     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4967     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4968   }
4969 
4970   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4971 
4972   // Copy the intrinsic results to registers
4973   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4974     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4975     if (!CopyToReg)
4976       continue;
4977 
4978     Chain = DAG.getCopyToReg(
4979       Chain, DL,
4980       CopyToReg->getOperand(1),
4981       SDValue(Result, i - 1),
4982       SDValue());
4983 
4984     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4985   }
4986 
4987   // Remove the old intrinsic from the chain
4988   DAG.ReplaceAllUsesOfValueWith(
4989     SDValue(Intr, Intr->getNumValues() - 1),
4990     Intr->getOperand(0));
4991 
4992   return Chain;
4993 }
4994 
4995 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4996                                           SelectionDAG &DAG) const {
4997   MVT VT = Op.getSimpleValueType();
4998   SDLoc DL(Op);
4999   // Checking the depth
5000   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5001     return DAG.getConstant(0, DL, VT);
5002 
5003   MachineFunction &MF = DAG.getMachineFunction();
5004   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5005   // Check for kernel and shader functions
5006   if (Info->isEntryFunction())
5007     return DAG.getConstant(0, DL, VT);
5008 
5009   MachineFrameInfo &MFI = MF.getFrameInfo();
5010   // There is a call to @llvm.returnaddress in this function
5011   MFI.setReturnAddressIsTaken(true);
5012 
5013   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5014   // Get the return address reg and mark it as an implicit live-in
5015   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5016 
5017   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5018 }
5019 
5020 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5021                                             SDValue Op,
5022                                             const SDLoc &DL,
5023                                             EVT VT) const {
5024   return Op.getValueType().bitsLE(VT) ?
5025       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5026     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5027                 DAG.getTargetConstant(0, DL, MVT::i32));
5028 }
5029 
5030 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5031   assert(Op.getValueType() == MVT::f16 &&
5032          "Do not know how to custom lower FP_ROUND for non-f16 type");
5033 
5034   SDValue Src = Op.getOperand(0);
5035   EVT SrcVT = Src.getValueType();
5036   if (SrcVT != MVT::f64)
5037     return Op;
5038 
5039   SDLoc DL(Op);
5040 
5041   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5042   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5043   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5044 }
5045 
5046 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5047                                                SelectionDAG &DAG) const {
5048   EVT VT = Op.getValueType();
5049   const MachineFunction &MF = DAG.getMachineFunction();
5050   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5051   bool IsIEEEMode = Info->getMode().IEEE;
5052 
5053   // FIXME: Assert during selection that this is only selected for
5054   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5055   // mode functions, but this happens to be OK since it's only done in cases
5056   // where there is known no sNaN.
5057   if (IsIEEEMode)
5058     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5059 
5060   if (VT == MVT::v4f16)
5061     return splitBinaryVectorOp(Op, DAG);
5062   return Op;
5063 }
5064 
5065 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5066   EVT VT = Op.getValueType();
5067   SDLoc SL(Op);
5068   SDValue LHS = Op.getOperand(0);
5069   SDValue RHS = Op.getOperand(1);
5070   bool isSigned = Op.getOpcode() == ISD::SMULO;
5071 
5072   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5073     const APInt &C = RHSC->getAPIntValue();
5074     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5075     if (C.isPowerOf2()) {
5076       // smulo(x, signed_min) is same as umulo(x, signed_min).
5077       bool UseArithShift = isSigned && !C.isMinSignedValue();
5078       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5079       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5080       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5081           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5082                       SL, VT, Result, ShiftAmt),
5083           LHS, ISD::SETNE);
5084       return DAG.getMergeValues({ Result, Overflow }, SL);
5085     }
5086   }
5087 
5088   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5089   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5090                             SL, VT, LHS, RHS);
5091 
5092   SDValue Sign = isSigned
5093     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5094                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5095     : DAG.getConstant(0, SL, VT);
5096   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5097 
5098   return DAG.getMergeValues({ Result, Overflow }, SL);
5099 }
5100 
5101 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5102   SDLoc SL(Op);
5103   SDValue Chain = Op.getOperand(0);
5104 
5105   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5106       !Subtarget->isTrapHandlerEnabled())
5107     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5108 
5109   MachineFunction &MF = DAG.getMachineFunction();
5110   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5111   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
5112   assert(UserSGPR != AMDGPU::NoRegister);
5113   SDValue QueuePtr = CreateLiveInRegister(
5114     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5115   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5116   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5117                                    QueuePtr, SDValue());
5118   SDValue Ops[] = {
5119     ToReg,
5120     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5121     SGPR01,
5122     ToReg.getValue(1)
5123   };
5124   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5125 }
5126 
5127 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5128   SDLoc SL(Op);
5129   SDValue Chain = Op.getOperand(0);
5130   MachineFunction &MF = DAG.getMachineFunction();
5131 
5132   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5133       !Subtarget->isTrapHandlerEnabled()) {
5134     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5135                                      "debugtrap handler not supported",
5136                                      Op.getDebugLoc(),
5137                                      DS_Warning);
5138     LLVMContext &Ctx = MF.getFunction().getContext();
5139     Ctx.diagnose(NoTrap);
5140     return Chain;
5141   }
5142 
5143   SDValue Ops[] = {
5144     Chain,
5145     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5146   };
5147   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5148 }
5149 
5150 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5151                                              SelectionDAG &DAG) const {
5152   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5153   if (Subtarget->hasApertureRegs()) {
5154     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5155         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5156         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5157     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5158         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5159         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5160     unsigned Encoding =
5161         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5162         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5163         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5164 
5165     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5166     SDValue ApertureReg = SDValue(
5167         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5168     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5169     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5170   }
5171 
5172   MachineFunction &MF = DAG.getMachineFunction();
5173   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5174   Register UserSGPR = Info->getQueuePtrUserSGPR();
5175   assert(UserSGPR != AMDGPU::NoRegister);
5176 
5177   SDValue QueuePtr = CreateLiveInRegister(
5178     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5179 
5180   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5181   // private_segment_aperture_base_hi.
5182   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5183 
5184   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
5185 
5186   // TODO: Use custom target PseudoSourceValue.
5187   // TODO: We should use the value from the IR intrinsic call, but it might not
5188   // be available and how do we get it?
5189   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5190   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5191                      MinAlign(64, StructOffset),
5192                      MachineMemOperand::MODereferenceable |
5193                          MachineMemOperand::MOInvariant);
5194 }
5195 
5196 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5197                                              SelectionDAG &DAG) const {
5198   SDLoc SL(Op);
5199   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5200 
5201   SDValue Src = ASC->getOperand(0);
5202   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5203 
5204   const AMDGPUTargetMachine &TM =
5205     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5206 
5207   // flat -> local/private
5208   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5209     unsigned DestAS = ASC->getDestAddressSpace();
5210 
5211     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5212         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5213       unsigned NullVal = TM.getNullPointerValue(DestAS);
5214       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5215       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5216       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5217 
5218       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5219                          NonNull, Ptr, SegmentNullPtr);
5220     }
5221   }
5222 
5223   // local/private -> flat
5224   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5225     unsigned SrcAS = ASC->getSrcAddressSpace();
5226 
5227     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5228         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5229       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5230       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5231 
5232       SDValue NonNull
5233         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5234 
5235       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5236       SDValue CvtPtr
5237         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5238 
5239       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5240                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5241                          FlatNullPtr);
5242     }
5243   }
5244 
5245   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5246       Src.getValueType() == MVT::i64)
5247     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5248 
5249   // global <-> flat are no-ops and never emitted.
5250 
5251   const MachineFunction &MF = DAG.getMachineFunction();
5252   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5253     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5254   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5255 
5256   return DAG.getUNDEF(ASC->getValueType(0));
5257 }
5258 
5259 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5260 // the small vector and inserting them into the big vector. That is better than
5261 // the default expansion of doing it via a stack slot. Even though the use of
5262 // the stack slot would be optimized away afterwards, the stack slot itself
5263 // remains.
5264 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5265                                                 SelectionDAG &DAG) const {
5266   SDValue Vec = Op.getOperand(0);
5267   SDValue Ins = Op.getOperand(1);
5268   SDValue Idx = Op.getOperand(2);
5269   EVT VecVT = Vec.getValueType();
5270   EVT InsVT = Ins.getValueType();
5271   EVT EltVT = VecVT.getVectorElementType();
5272   unsigned InsNumElts = InsVT.getVectorNumElements();
5273   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5274   SDLoc SL(Op);
5275 
5276   for (unsigned I = 0; I != InsNumElts; ++I) {
5277     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5278                               DAG.getConstant(I, SL, MVT::i32));
5279     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5280                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5281   }
5282   return Vec;
5283 }
5284 
5285 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5286                                                  SelectionDAG &DAG) const {
5287   SDValue Vec = Op.getOperand(0);
5288   SDValue InsVal = Op.getOperand(1);
5289   SDValue Idx = Op.getOperand(2);
5290   EVT VecVT = Vec.getValueType();
5291   EVT EltVT = VecVT.getVectorElementType();
5292   unsigned VecSize = VecVT.getSizeInBits();
5293   unsigned EltSize = EltVT.getSizeInBits();
5294 
5295 
5296   assert(VecSize <= 64);
5297 
5298   unsigned NumElts = VecVT.getVectorNumElements();
5299   SDLoc SL(Op);
5300   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5301 
5302   if (NumElts == 4 && EltSize == 16 && KIdx) {
5303     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5304 
5305     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5306                                  DAG.getConstant(0, SL, MVT::i32));
5307     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5308                                  DAG.getConstant(1, SL, MVT::i32));
5309 
5310     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5311     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5312 
5313     unsigned Idx = KIdx->getZExtValue();
5314     bool InsertLo = Idx < 2;
5315     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5316       InsertLo ? LoVec : HiVec,
5317       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5318       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5319 
5320     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5321 
5322     SDValue Concat = InsertLo ?
5323       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5324       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5325 
5326     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5327   }
5328 
5329   if (isa<ConstantSDNode>(Idx))
5330     return SDValue();
5331 
5332   MVT IntVT = MVT::getIntegerVT(VecSize);
5333 
5334   // Avoid stack access for dynamic indexing.
5335   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5336 
5337   // Create a congruent vector with the target value in each element so that
5338   // the required element can be masked and ORed into the target vector.
5339   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5340                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5341 
5342   assert(isPowerOf2_32(EltSize));
5343   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5344 
5345   // Convert vector index to bit-index.
5346   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5347 
5348   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5349   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5350                             DAG.getConstant(0xffff, SL, IntVT),
5351                             ScaledIdx);
5352 
5353   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5354   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5355                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5356 
5357   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5358   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5359 }
5360 
5361 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5362                                                   SelectionDAG &DAG) const {
5363   SDLoc SL(Op);
5364 
5365   EVT ResultVT = Op.getValueType();
5366   SDValue Vec = Op.getOperand(0);
5367   SDValue Idx = Op.getOperand(1);
5368   EVT VecVT = Vec.getValueType();
5369   unsigned VecSize = VecVT.getSizeInBits();
5370   EVT EltVT = VecVT.getVectorElementType();
5371   assert(VecSize <= 64);
5372 
5373   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5374 
5375   // Make sure we do any optimizations that will make it easier to fold
5376   // source modifiers before obscuring it with bit operations.
5377 
5378   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5379   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5380     return Combined;
5381 
5382   unsigned EltSize = EltVT.getSizeInBits();
5383   assert(isPowerOf2_32(EltSize));
5384 
5385   MVT IntVT = MVT::getIntegerVT(VecSize);
5386   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5387 
5388   // Convert vector index to bit-index (* EltSize)
5389   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5390 
5391   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5392   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5393 
5394   if (ResultVT == MVT::f16) {
5395     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5396     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5397   }
5398 
5399   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5400 }
5401 
5402 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5403   assert(Elt % 2 == 0);
5404   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5405 }
5406 
5407 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5408                                               SelectionDAG &DAG) const {
5409   SDLoc SL(Op);
5410   EVT ResultVT = Op.getValueType();
5411   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5412 
5413   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5414   EVT EltVT = PackVT.getVectorElementType();
5415   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5416 
5417   // vector_shuffle <0,1,6,7> lhs, rhs
5418   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5419   //
5420   // vector_shuffle <6,7,2,3> lhs, rhs
5421   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5422   //
5423   // vector_shuffle <6,7,0,1> lhs, rhs
5424   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5425 
5426   // Avoid scalarizing when both halves are reading from consecutive elements.
5427   SmallVector<SDValue, 4> Pieces;
5428   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5429     if (elementPairIsContiguous(SVN->getMask(), I)) {
5430       const int Idx = SVN->getMaskElt(I);
5431       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5432       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5433       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5434                                     PackVT, SVN->getOperand(VecIdx),
5435                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5436       Pieces.push_back(SubVec);
5437     } else {
5438       const int Idx0 = SVN->getMaskElt(I);
5439       const int Idx1 = SVN->getMaskElt(I + 1);
5440       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5441       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5442       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5443       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5444 
5445       SDValue Vec0 = SVN->getOperand(VecIdx0);
5446       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5447                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5448 
5449       SDValue Vec1 = SVN->getOperand(VecIdx1);
5450       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5451                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5452       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5453     }
5454   }
5455 
5456   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5457 }
5458 
5459 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5460                                             SelectionDAG &DAG) const {
5461   SDLoc SL(Op);
5462   EVT VT = Op.getValueType();
5463 
5464   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5465     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5466 
5467     // Turn into pair of packed build_vectors.
5468     // TODO: Special case for constants that can be materialized with s_mov_b64.
5469     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5470                                     { Op.getOperand(0), Op.getOperand(1) });
5471     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5472                                     { Op.getOperand(2), Op.getOperand(3) });
5473 
5474     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5475     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5476 
5477     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5478     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5479   }
5480 
5481   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5482   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5483 
5484   SDValue Lo = Op.getOperand(0);
5485   SDValue Hi = Op.getOperand(1);
5486 
5487   // Avoid adding defined bits with the zero_extend.
5488   if (Hi.isUndef()) {
5489     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5490     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5491     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5492   }
5493 
5494   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5495   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5496 
5497   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5498                               DAG.getConstant(16, SL, MVT::i32));
5499   if (Lo.isUndef())
5500     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5501 
5502   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5503   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5504 
5505   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5506   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5507 }
5508 
5509 bool
5510 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5511   // We can fold offsets for anything that doesn't require a GOT relocation.
5512   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5513           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5514           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5515          !shouldEmitGOTReloc(GA->getGlobal());
5516 }
5517 
5518 static SDValue
5519 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5520                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5521                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5522   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5523   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5524   // lowered to the following code sequence:
5525   //
5526   // For constant address space:
5527   //   s_getpc_b64 s[0:1]
5528   //   s_add_u32 s0, s0, $symbol
5529   //   s_addc_u32 s1, s1, 0
5530   //
5531   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5532   //   a fixup or relocation is emitted to replace $symbol with a literal
5533   //   constant, which is a pc-relative offset from the encoding of the $symbol
5534   //   operand to the global variable.
5535   //
5536   // For global address space:
5537   //   s_getpc_b64 s[0:1]
5538   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5539   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5540   //
5541   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5542   //   fixups or relocations are emitted to replace $symbol@*@lo and
5543   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5544   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5545   //   operand to the global variable.
5546   //
5547   // What we want here is an offset from the value returned by s_getpc
5548   // (which is the address of the s_add_u32 instruction) to the global
5549   // variable, but since the encoding of $symbol starts 4 bytes after the start
5550   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5551   // small. This requires us to add 4 to the global variable offset in order to
5552   // compute the correct address.
5553   SDValue PtrLo =
5554       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5555   SDValue PtrHi;
5556   if (GAFlags == SIInstrInfo::MO_NONE) {
5557     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5558   } else {
5559     PtrHi =
5560         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5561   }
5562   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5563 }
5564 
5565 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5566                                              SDValue Op,
5567                                              SelectionDAG &DAG) const {
5568   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5569   const GlobalValue *GV = GSD->getGlobal();
5570   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5571        shouldUseLDSConstAddress(GV)) ||
5572       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5573       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5574     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5575 
5576   SDLoc DL(GSD);
5577   EVT PtrVT = Op.getValueType();
5578 
5579   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5580     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5581                                             SIInstrInfo::MO_ABS32_LO);
5582     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5583   }
5584 
5585   if (shouldEmitFixup(GV))
5586     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5587   else if (shouldEmitPCReloc(GV))
5588     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5589                                    SIInstrInfo::MO_REL32);
5590 
5591   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5592                                             SIInstrInfo::MO_GOTPCREL32);
5593 
5594   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5595   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5596   const DataLayout &DataLayout = DAG.getDataLayout();
5597   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5598   MachinePointerInfo PtrInfo
5599     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5600 
5601   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5602                      MachineMemOperand::MODereferenceable |
5603                          MachineMemOperand::MOInvariant);
5604 }
5605 
5606 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5607                                    const SDLoc &DL, SDValue V) const {
5608   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5609   // the destination register.
5610   //
5611   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5612   // so we will end up with redundant moves to m0.
5613   //
5614   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5615 
5616   // A Null SDValue creates a glue result.
5617   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5618                                   V, Chain);
5619   return SDValue(M0, 0);
5620 }
5621 
5622 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5623                                                  SDValue Op,
5624                                                  MVT VT,
5625                                                  unsigned Offset) const {
5626   SDLoc SL(Op);
5627   SDValue Param = lowerKernargMemParameter(
5628       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5629   // The local size values will have the hi 16-bits as zero.
5630   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5631                      DAG.getValueType(VT));
5632 }
5633 
5634 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5635                                         EVT VT) {
5636   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5637                                       "non-hsa intrinsic with hsa target",
5638                                       DL.getDebugLoc());
5639   DAG.getContext()->diagnose(BadIntrin);
5640   return DAG.getUNDEF(VT);
5641 }
5642 
5643 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5644                                          EVT VT) {
5645   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5646                                       "intrinsic not supported on subtarget",
5647                                       DL.getDebugLoc());
5648   DAG.getContext()->diagnose(BadIntrin);
5649   return DAG.getUNDEF(VT);
5650 }
5651 
5652 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5653                                     ArrayRef<SDValue> Elts) {
5654   assert(!Elts.empty());
5655   MVT Type;
5656   unsigned NumElts;
5657 
5658   if (Elts.size() == 1) {
5659     Type = MVT::f32;
5660     NumElts = 1;
5661   } else if (Elts.size() == 2) {
5662     Type = MVT::v2f32;
5663     NumElts = 2;
5664   } else if (Elts.size() == 3) {
5665     Type = MVT::v3f32;
5666     NumElts = 3;
5667   } else if (Elts.size() <= 4) {
5668     Type = MVT::v4f32;
5669     NumElts = 4;
5670   } else if (Elts.size() <= 8) {
5671     Type = MVT::v8f32;
5672     NumElts = 8;
5673   } else {
5674     assert(Elts.size() <= 16);
5675     Type = MVT::v16f32;
5676     NumElts = 16;
5677   }
5678 
5679   SmallVector<SDValue, 16> VecElts(NumElts);
5680   for (unsigned i = 0; i < Elts.size(); ++i) {
5681     SDValue Elt = Elts[i];
5682     if (Elt.getValueType() != MVT::f32)
5683       Elt = DAG.getBitcast(MVT::f32, Elt);
5684     VecElts[i] = Elt;
5685   }
5686   for (unsigned i = Elts.size(); i < NumElts; ++i)
5687     VecElts[i] = DAG.getUNDEF(MVT::f32);
5688 
5689   if (NumElts == 1)
5690     return VecElts[0];
5691   return DAG.getBuildVector(Type, DL, VecElts);
5692 }
5693 
5694 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5695                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5696   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5697 
5698   uint64_t Value = CachePolicyConst->getZExtValue();
5699   SDLoc DL(CachePolicy);
5700   if (GLC) {
5701     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5702     Value &= ~(uint64_t)0x1;
5703   }
5704   if (SLC) {
5705     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5706     Value &= ~(uint64_t)0x2;
5707   }
5708   if (DLC) {
5709     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5710     Value &= ~(uint64_t)0x4;
5711   }
5712 
5713   return Value == 0;
5714 }
5715 
5716 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5717                               SDValue Src, int ExtraElts) {
5718   EVT SrcVT = Src.getValueType();
5719 
5720   SmallVector<SDValue, 8> Elts;
5721 
5722   if (SrcVT.isVector())
5723     DAG.ExtractVectorElements(Src, Elts);
5724   else
5725     Elts.push_back(Src);
5726 
5727   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5728   while (ExtraElts--)
5729     Elts.push_back(Undef);
5730 
5731   return DAG.getBuildVector(CastVT, DL, Elts);
5732 }
5733 
5734 // Re-construct the required return value for a image load intrinsic.
5735 // This is more complicated due to the optional use TexFailCtrl which means the required
5736 // return type is an aggregate
5737 static SDValue constructRetValue(SelectionDAG &DAG,
5738                                  MachineSDNode *Result,
5739                                  ArrayRef<EVT> ResultTypes,
5740                                  bool IsTexFail, bool Unpacked, bool IsD16,
5741                                  int DMaskPop, int NumVDataDwords,
5742                                  const SDLoc &DL, LLVMContext &Context) {
5743   // Determine the required return type. This is the same regardless of IsTexFail flag
5744   EVT ReqRetVT = ResultTypes[0];
5745   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5746   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5747     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5748 
5749   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5750     DMaskPop : (DMaskPop + 1) / 2;
5751 
5752   MVT DataDwordVT = NumDataDwords == 1 ?
5753     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5754 
5755   MVT MaskPopVT = MaskPopDwords == 1 ?
5756     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5757 
5758   SDValue Data(Result, 0);
5759   SDValue TexFail;
5760 
5761   if (IsTexFail) {
5762     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5763     if (MaskPopVT.isVector()) {
5764       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5765                          SDValue(Result, 0), ZeroIdx);
5766     } else {
5767       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5768                          SDValue(Result, 0), ZeroIdx);
5769     }
5770 
5771     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5772                           SDValue(Result, 0),
5773                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5774   }
5775 
5776   if (DataDwordVT.isVector())
5777     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5778                           NumDataDwords - MaskPopDwords);
5779 
5780   if (IsD16)
5781     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5782 
5783   if (!ReqRetVT.isVector())
5784     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5785 
5786   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5787 
5788   if (TexFail)
5789     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5790 
5791   if (Result->getNumValues() == 1)
5792     return Data;
5793 
5794   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5795 }
5796 
5797 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5798                          SDValue *LWE, bool &IsTexFail) {
5799   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5800 
5801   uint64_t Value = TexFailCtrlConst->getZExtValue();
5802   if (Value) {
5803     IsTexFail = true;
5804   }
5805 
5806   SDLoc DL(TexFailCtrlConst);
5807   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5808   Value &= ~(uint64_t)0x1;
5809   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5810   Value &= ~(uint64_t)0x2;
5811 
5812   return Value == 0;
5813 }
5814 
5815 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5816                                         MVT PackVectorVT,
5817                                         SmallVectorImpl<SDValue> &PackedAddrs,
5818                                         unsigned DimIdx, unsigned EndIdx,
5819                                         unsigned NumGradients) {
5820   SDLoc DL(Op);
5821   for (unsigned I = DimIdx; I < EndIdx; I++) {
5822     SDValue Addr = Op.getOperand(I);
5823 
5824     // Gradients are packed with undef for each coordinate.
5825     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5826     // 1D: undef,dx/dh; undef,dx/dv
5827     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5828     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5829     if (((I + 1) >= EndIdx) ||
5830         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5831                                          I == DimIdx + NumGradients - 1))) {
5832       if (Addr.getValueType() != MVT::i16)
5833         Addr = DAG.getBitcast(MVT::i16, Addr);
5834       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5835     } else {
5836       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5837       I++;
5838     }
5839     Addr = DAG.getBitcast(MVT::f32, Addr);
5840     PackedAddrs.push_back(Addr);
5841   }
5842 }
5843 
5844 SDValue SITargetLowering::lowerImage(SDValue Op,
5845                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5846                                      SelectionDAG &DAG) const {
5847   SDLoc DL(Op);
5848   MachineFunction &MF = DAG.getMachineFunction();
5849   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5850   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5851       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5852   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5853   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5854       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5855   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5856       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5857   unsigned IntrOpcode = Intr->BaseOpcode;
5858   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5859 
5860   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5861   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5862   bool IsD16 = false;
5863   bool IsG16 = false;
5864   bool IsA16 = false;
5865   SDValue VData;
5866   int NumVDataDwords;
5867   bool AdjustRetType = false;
5868 
5869   unsigned AddrIdx; // Index of first address argument
5870   unsigned DMask;
5871   unsigned DMaskLanes = 0;
5872 
5873   if (BaseOpcode->Atomic) {
5874     VData = Op.getOperand(2);
5875 
5876     bool Is64Bit = VData.getValueType() == MVT::i64;
5877     if (BaseOpcode->AtomicX2) {
5878       SDValue VData2 = Op.getOperand(3);
5879       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5880                                  {VData, VData2});
5881       if (Is64Bit)
5882         VData = DAG.getBitcast(MVT::v4i32, VData);
5883 
5884       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5885       DMask = Is64Bit ? 0xf : 0x3;
5886       NumVDataDwords = Is64Bit ? 4 : 2;
5887       AddrIdx = 4;
5888     } else {
5889       DMask = Is64Bit ? 0x3 : 0x1;
5890       NumVDataDwords = Is64Bit ? 2 : 1;
5891       AddrIdx = 3;
5892     }
5893   } else {
5894     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5895     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5896     DMask = DMaskConst->getZExtValue();
5897     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5898 
5899     if (BaseOpcode->Store) {
5900       VData = Op.getOperand(2);
5901 
5902       MVT StoreVT = VData.getSimpleValueType();
5903       if (StoreVT.getScalarType() == MVT::f16) {
5904         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5905           return Op; // D16 is unsupported for this instruction
5906 
5907         IsD16 = true;
5908         VData = handleD16VData(VData, DAG);
5909       }
5910 
5911       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5912     } else {
5913       // Work out the num dwords based on the dmask popcount and underlying type
5914       // and whether packing is supported.
5915       MVT LoadVT = ResultTypes[0].getSimpleVT();
5916       if (LoadVT.getScalarType() == MVT::f16) {
5917         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5918           return Op; // D16 is unsupported for this instruction
5919 
5920         IsD16 = true;
5921       }
5922 
5923       // Confirm that the return type is large enough for the dmask specified
5924       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5925           (!LoadVT.isVector() && DMaskLanes > 1))
5926           return Op;
5927 
5928       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5929         NumVDataDwords = (DMaskLanes + 1) / 2;
5930       else
5931         NumVDataDwords = DMaskLanes;
5932 
5933       AdjustRetType = true;
5934     }
5935 
5936     AddrIdx = DMaskIdx + 1;
5937   }
5938 
5939   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5940   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5941   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5942   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5943                        NumCoords + NumLCM;
5944   unsigned NumMIVAddrs = NumVAddrs;
5945 
5946   SmallVector<SDValue, 4> VAddrs;
5947 
5948   // Optimize _L to _LZ when _L is zero
5949   if (LZMappingInfo) {
5950     if (auto ConstantLod =
5951          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5952       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5953         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5954         NumMIVAddrs--;               // remove 'lod'
5955       }
5956     }
5957   }
5958 
5959   // Optimize _mip away, when 'lod' is zero
5960   if (MIPMappingInfo) {
5961     if (auto ConstantLod =
5962          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5963       if (ConstantLod->isNullValue()) {
5964         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5965         NumMIVAddrs--;               // remove 'lod'
5966       }
5967     }
5968   }
5969 
5970   // Push back extra arguments.
5971   for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++)
5972     VAddrs.push_back(Op.getOperand(AddrIdx + I));
5973 
5974   // Check for 16 bit addresses or derivatives and pack if true.
5975   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5976   unsigned CoordIdx = DimIdx + NumGradients;
5977   unsigned CoordsEnd = AddrIdx + NumMIVAddrs;
5978 
5979   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5980   MVT VAddrScalarVT = VAddrVT.getScalarType();
5981   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5982   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5983 
5984   VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType();
5985   VAddrScalarVT = VAddrVT.getScalarType();
5986   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5987   if (IsA16 || IsG16) {
5988     if (IsA16) {
5989       if (!ST->hasA16()) {
5990         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5991                              "support 16 bit addresses\n");
5992         return Op;
5993       }
5994       if (!IsG16) {
5995         LLVM_DEBUG(
5996             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
5997                       "need 16 bit derivatives but got 32 bit derivatives\n");
5998         return Op;
5999       }
6000     } else if (!ST->hasG16()) {
6001       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6002                            "support 16 bit derivatives\n");
6003       return Op;
6004     }
6005 
6006     if (BaseOpcode->Gradients && !IsA16) {
6007       if (!ST->hasG16()) {
6008         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6009                              "support 16 bit derivatives\n");
6010         return Op;
6011       }
6012       // Activate g16
6013       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6014           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6015       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6016     }
6017 
6018     // Don't compress addresses for G16
6019     const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx;
6020     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx,
6021                                 PackEndIdx, NumGradients);
6022 
6023     if (!IsA16) {
6024       // Add uncompressed address
6025       for (unsigned I = CoordIdx; I < CoordsEnd; I++)
6026         VAddrs.push_back(Op.getOperand(I));
6027     }
6028   } else {
6029     for (unsigned I = DimIdx; I < CoordsEnd; I++)
6030       VAddrs.push_back(Op.getOperand(I));
6031   }
6032 
6033   // If the register allocator cannot place the address registers contiguously
6034   // without introducing moves, then using the non-sequential address encoding
6035   // is always preferable, since it saves VALU instructions and is usually a
6036   // wash in terms of code size or even better.
6037   //
6038   // However, we currently have no way of hinting to the register allocator that
6039   // MIMG addresses should be placed contiguously when it is possible to do so,
6040   // so force non-NSA for the common 2-address case as a heuristic.
6041   //
6042   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6043   // allocation when possible.
6044   bool UseNSA =
6045       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6046   SDValue VAddr;
6047   if (!UseNSA)
6048     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6049 
6050   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6051   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6052   unsigned CtrlIdx; // Index of texfailctrl argument
6053   SDValue Unorm;
6054   if (!BaseOpcode->Sampler) {
6055     Unorm = True;
6056     CtrlIdx = AddrIdx + NumVAddrs + 1;
6057   } else {
6058     auto UnormConst =
6059         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
6060 
6061     Unorm = UnormConst->getZExtValue() ? True : False;
6062     CtrlIdx = AddrIdx + NumVAddrs + 3;
6063   }
6064 
6065   SDValue TFE;
6066   SDValue LWE;
6067   SDValue TexFail = Op.getOperand(CtrlIdx);
6068   bool IsTexFail = false;
6069   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6070     return Op;
6071 
6072   if (IsTexFail) {
6073     if (!DMaskLanes) {
6074       // Expecting to get an error flag since TFC is on - and dmask is 0
6075       // Force dmask to be at least 1 otherwise the instruction will fail
6076       DMask = 0x1;
6077       DMaskLanes = 1;
6078       NumVDataDwords = 1;
6079     }
6080     NumVDataDwords += 1;
6081     AdjustRetType = true;
6082   }
6083 
6084   // Has something earlier tagged that the return type needs adjusting
6085   // This happens if the instruction is a load or has set TexFailCtrl flags
6086   if (AdjustRetType) {
6087     // NumVDataDwords reflects the true number of dwords required in the return type
6088     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6089       // This is a no-op load. This can be eliminated
6090       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6091       if (isa<MemSDNode>(Op))
6092         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6093       return Undef;
6094     }
6095 
6096     EVT NewVT = NumVDataDwords > 1 ?
6097                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6098                 : MVT::i32;
6099 
6100     ResultTypes[0] = NewVT;
6101     if (ResultTypes.size() == 3) {
6102       // Original result was aggregate type used for TexFailCtrl results
6103       // The actual instruction returns as a vector type which has now been
6104       // created. Remove the aggregate result.
6105       ResultTypes.erase(&ResultTypes[1]);
6106     }
6107   }
6108 
6109   SDValue GLC;
6110   SDValue SLC;
6111   SDValue DLC;
6112   if (BaseOpcode->Atomic) {
6113     GLC = True; // TODO no-return optimization
6114     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
6115                           IsGFX10 ? &DLC : nullptr))
6116       return Op;
6117   } else {
6118     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
6119                           IsGFX10 ? &DLC : nullptr))
6120       return Op;
6121   }
6122 
6123   SmallVector<SDValue, 26> Ops;
6124   if (BaseOpcode->Store || BaseOpcode->Atomic)
6125     Ops.push_back(VData); // vdata
6126   if (UseNSA) {
6127     for (const SDValue &Addr : VAddrs)
6128       Ops.push_back(Addr);
6129   } else {
6130     Ops.push_back(VAddr);
6131   }
6132   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
6133   if (BaseOpcode->Sampler)
6134     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
6135   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6136   if (IsGFX10)
6137     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6138   Ops.push_back(Unorm);
6139   if (IsGFX10)
6140     Ops.push_back(DLC);
6141   Ops.push_back(GLC);
6142   Ops.push_back(SLC);
6143   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6144                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6145   if (IsGFX10)
6146     Ops.push_back(IsA16 ? True : False);
6147   Ops.push_back(TFE);
6148   Ops.push_back(LWE);
6149   if (!IsGFX10)
6150     Ops.push_back(DimInfo->DA ? True : False);
6151   if (BaseOpcode->HasD16)
6152     Ops.push_back(IsD16 ? True : False);
6153   if (isa<MemSDNode>(Op))
6154     Ops.push_back(Op.getOperand(0)); // chain
6155 
6156   int NumVAddrDwords =
6157       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6158   int Opcode = -1;
6159 
6160   if (IsGFX10) {
6161     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6162                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6163                                           : AMDGPU::MIMGEncGfx10Default,
6164                                    NumVDataDwords, NumVAddrDwords);
6165   } else {
6166     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6167       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6168                                      NumVDataDwords, NumVAddrDwords);
6169     if (Opcode == -1)
6170       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6171                                      NumVDataDwords, NumVAddrDwords);
6172   }
6173   assert(Opcode != -1);
6174 
6175   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6176   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6177     MachineMemOperand *MemRef = MemOp->getMemOperand();
6178     DAG.setNodeMemRefs(NewNode, {MemRef});
6179   }
6180 
6181   if (BaseOpcode->AtomicX2) {
6182     SmallVector<SDValue, 1> Elt;
6183     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6184     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6185   } else if (!BaseOpcode->Store) {
6186     return constructRetValue(DAG, NewNode,
6187                              OrigResultTypes, IsTexFail,
6188                              Subtarget->hasUnpackedD16VMem(), IsD16,
6189                              DMaskLanes, NumVDataDwords, DL,
6190                              *DAG.getContext());
6191   }
6192 
6193   return SDValue(NewNode, 0);
6194 }
6195 
6196 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6197                                        SDValue Offset, SDValue CachePolicy,
6198                                        SelectionDAG &DAG) const {
6199   MachineFunction &MF = DAG.getMachineFunction();
6200 
6201   const DataLayout &DataLayout = DAG.getDataLayout();
6202   Align Alignment =
6203       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6204 
6205   MachineMemOperand *MMO = MF.getMachineMemOperand(
6206       MachinePointerInfo(),
6207       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6208           MachineMemOperand::MOInvariant,
6209       VT.getStoreSize(), Alignment);
6210 
6211   if (!Offset->isDivergent()) {
6212     SDValue Ops[] = {
6213         Rsrc,
6214         Offset, // Offset
6215         CachePolicy
6216     };
6217 
6218     // Widen vec3 load to vec4.
6219     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6220       EVT WidenedVT =
6221           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6222       auto WidenedOp = DAG.getMemIntrinsicNode(
6223           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6224           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6225       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6226                                    DAG.getVectorIdxConstant(0, DL));
6227       return Subvector;
6228     }
6229 
6230     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6231                                    DAG.getVTList(VT), Ops, VT, MMO);
6232   }
6233 
6234   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6235   // assume that the buffer is unswizzled.
6236   SmallVector<SDValue, 4> Loads;
6237   unsigned NumLoads = 1;
6238   MVT LoadVT = VT.getSimpleVT();
6239   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6240   assert((LoadVT.getScalarType() == MVT::i32 ||
6241           LoadVT.getScalarType() == MVT::f32));
6242 
6243   if (NumElts == 8 || NumElts == 16) {
6244     NumLoads = NumElts / 4;
6245     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6246   }
6247 
6248   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6249   SDValue Ops[] = {
6250       DAG.getEntryNode(),                               // Chain
6251       Rsrc,                                             // rsrc
6252       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6253       {},                                               // voffset
6254       {},                                               // soffset
6255       {},                                               // offset
6256       CachePolicy,                                      // cachepolicy
6257       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6258   };
6259 
6260   // Use the alignment to ensure that the required offsets will fit into the
6261   // immediate offsets.
6262   setBufferOffsets(Offset, DAG, &Ops[3],
6263                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6264 
6265   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6266   for (unsigned i = 0; i < NumLoads; ++i) {
6267     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6268     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6269                                         LoadVT, MMO, DAG));
6270   }
6271 
6272   if (NumElts == 8 || NumElts == 16)
6273     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6274 
6275   return Loads[0];
6276 }
6277 
6278 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6279                                                   SelectionDAG &DAG) const {
6280   MachineFunction &MF = DAG.getMachineFunction();
6281   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6282 
6283   EVT VT = Op.getValueType();
6284   SDLoc DL(Op);
6285   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6286 
6287   // TODO: Should this propagate fast-math-flags?
6288 
6289   switch (IntrinsicID) {
6290   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6291     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6292       return emitNonHSAIntrinsicError(DAG, DL, VT);
6293     return getPreloadedValue(DAG, *MFI, VT,
6294                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6295   }
6296   case Intrinsic::amdgcn_dispatch_ptr:
6297   case Intrinsic::amdgcn_queue_ptr: {
6298     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6299       DiagnosticInfoUnsupported BadIntrin(
6300           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6301           DL.getDebugLoc());
6302       DAG.getContext()->diagnose(BadIntrin);
6303       return DAG.getUNDEF(VT);
6304     }
6305 
6306     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6307       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6308     return getPreloadedValue(DAG, *MFI, VT, RegID);
6309   }
6310   case Intrinsic::amdgcn_implicitarg_ptr: {
6311     if (MFI->isEntryFunction())
6312       return getImplicitArgPtr(DAG, DL);
6313     return getPreloadedValue(DAG, *MFI, VT,
6314                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6315   }
6316   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6317     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6318       // This only makes sense to call in a kernel, so just lower to null.
6319       return DAG.getConstant(0, DL, VT);
6320     }
6321 
6322     return getPreloadedValue(DAG, *MFI, VT,
6323                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6324   }
6325   case Intrinsic::amdgcn_dispatch_id: {
6326     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6327   }
6328   case Intrinsic::amdgcn_rcp:
6329     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6330   case Intrinsic::amdgcn_rsq:
6331     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6332   case Intrinsic::amdgcn_rsq_legacy:
6333     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6334       return emitRemovedIntrinsicError(DAG, DL, VT);
6335     return SDValue();
6336   case Intrinsic::amdgcn_rcp_legacy:
6337     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6338       return emitRemovedIntrinsicError(DAG, DL, VT);
6339     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6340   case Intrinsic::amdgcn_rsq_clamp: {
6341     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6342       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6343 
6344     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6345     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6346     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6347 
6348     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6349     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6350                               DAG.getConstantFP(Max, DL, VT));
6351     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6352                        DAG.getConstantFP(Min, DL, VT));
6353   }
6354   case Intrinsic::r600_read_ngroups_x:
6355     if (Subtarget->isAmdHsaOS())
6356       return emitNonHSAIntrinsicError(DAG, DL, VT);
6357 
6358     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6359                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6360                                     false);
6361   case Intrinsic::r600_read_ngroups_y:
6362     if (Subtarget->isAmdHsaOS())
6363       return emitNonHSAIntrinsicError(DAG, DL, VT);
6364 
6365     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6366                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6367                                     false);
6368   case Intrinsic::r600_read_ngroups_z:
6369     if (Subtarget->isAmdHsaOS())
6370       return emitNonHSAIntrinsicError(DAG, DL, VT);
6371 
6372     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6373                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6374                                     false);
6375   case Intrinsic::r600_read_global_size_x:
6376     if (Subtarget->isAmdHsaOS())
6377       return emitNonHSAIntrinsicError(DAG, DL, VT);
6378 
6379     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6380                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6381                                     Align(4), false);
6382   case Intrinsic::r600_read_global_size_y:
6383     if (Subtarget->isAmdHsaOS())
6384       return emitNonHSAIntrinsicError(DAG, DL, VT);
6385 
6386     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6387                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6388                                     Align(4), false);
6389   case Intrinsic::r600_read_global_size_z:
6390     if (Subtarget->isAmdHsaOS())
6391       return emitNonHSAIntrinsicError(DAG, DL, VT);
6392 
6393     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6394                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6395                                     Align(4), false);
6396   case Intrinsic::r600_read_local_size_x:
6397     if (Subtarget->isAmdHsaOS())
6398       return emitNonHSAIntrinsicError(DAG, DL, VT);
6399 
6400     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6401                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6402   case Intrinsic::r600_read_local_size_y:
6403     if (Subtarget->isAmdHsaOS())
6404       return emitNonHSAIntrinsicError(DAG, DL, VT);
6405 
6406     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6407                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6408   case Intrinsic::r600_read_local_size_z:
6409     if (Subtarget->isAmdHsaOS())
6410       return emitNonHSAIntrinsicError(DAG, DL, VT);
6411 
6412     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6413                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6414   case Intrinsic::amdgcn_workgroup_id_x:
6415     return getPreloadedValue(DAG, *MFI, VT,
6416                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6417   case Intrinsic::amdgcn_workgroup_id_y:
6418     return getPreloadedValue(DAG, *MFI, VT,
6419                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6420   case Intrinsic::amdgcn_workgroup_id_z:
6421     return getPreloadedValue(DAG, *MFI, VT,
6422                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6423   case Intrinsic::amdgcn_workitem_id_x:
6424     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6425                           SDLoc(DAG.getEntryNode()),
6426                           MFI->getArgInfo().WorkItemIDX);
6427   case Intrinsic::amdgcn_workitem_id_y:
6428     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6429                           SDLoc(DAG.getEntryNode()),
6430                           MFI->getArgInfo().WorkItemIDY);
6431   case Intrinsic::amdgcn_workitem_id_z:
6432     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6433                           SDLoc(DAG.getEntryNode()),
6434                           MFI->getArgInfo().WorkItemIDZ);
6435   case Intrinsic::amdgcn_wavefrontsize:
6436     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6437                            SDLoc(Op), MVT::i32);
6438   case Intrinsic::amdgcn_s_buffer_load: {
6439     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6440     SDValue GLC;
6441     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6442     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6443                           IsGFX10 ? &DLC : nullptr))
6444       return Op;
6445     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6446                         DAG);
6447   }
6448   case Intrinsic::amdgcn_fdiv_fast:
6449     return lowerFDIV_FAST(Op, DAG);
6450   case Intrinsic::amdgcn_sin:
6451     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6452 
6453   case Intrinsic::amdgcn_cos:
6454     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6455 
6456   case Intrinsic::amdgcn_mul_u24:
6457     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6458   case Intrinsic::amdgcn_mul_i24:
6459     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6460 
6461   case Intrinsic::amdgcn_log_clamp: {
6462     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6463       return SDValue();
6464 
6465     DiagnosticInfoUnsupported BadIntrin(
6466       MF.getFunction(), "intrinsic not supported on subtarget",
6467       DL.getDebugLoc());
6468       DAG.getContext()->diagnose(BadIntrin);
6469       return DAG.getUNDEF(VT);
6470   }
6471   case Intrinsic::amdgcn_ldexp:
6472     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6473                        Op.getOperand(1), Op.getOperand(2));
6474 
6475   case Intrinsic::amdgcn_fract:
6476     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6477 
6478   case Intrinsic::amdgcn_class:
6479     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6480                        Op.getOperand(1), Op.getOperand(2));
6481   case Intrinsic::amdgcn_div_fmas:
6482     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6483                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6484                        Op.getOperand(4));
6485 
6486   case Intrinsic::amdgcn_div_fixup:
6487     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6488                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6489 
6490   case Intrinsic::amdgcn_div_scale: {
6491     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6492 
6493     // Translate to the operands expected by the machine instruction. The
6494     // first parameter must be the same as the first instruction.
6495     SDValue Numerator = Op.getOperand(1);
6496     SDValue Denominator = Op.getOperand(2);
6497 
6498     // Note this order is opposite of the machine instruction's operations,
6499     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6500     // intrinsic has the numerator as the first operand to match a normal
6501     // division operation.
6502 
6503     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6504 
6505     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6506                        Denominator, Numerator);
6507   }
6508   case Intrinsic::amdgcn_icmp: {
6509     // There is a Pat that handles this variant, so return it as-is.
6510     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6511         Op.getConstantOperandVal(2) == 0 &&
6512         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6513       return Op;
6514     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6515   }
6516   case Intrinsic::amdgcn_fcmp: {
6517     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6518   }
6519   case Intrinsic::amdgcn_ballot:
6520     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6521   case Intrinsic::amdgcn_fmed3:
6522     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6523                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6524   case Intrinsic::amdgcn_fdot2:
6525     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6526                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6527                        Op.getOperand(4));
6528   case Intrinsic::amdgcn_fmul_legacy:
6529     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6530                        Op.getOperand(1), Op.getOperand(2));
6531   case Intrinsic::amdgcn_sffbh:
6532     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6533   case Intrinsic::amdgcn_sbfe:
6534     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6535                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6536   case Intrinsic::amdgcn_ubfe:
6537     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6538                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6539   case Intrinsic::amdgcn_cvt_pkrtz:
6540   case Intrinsic::amdgcn_cvt_pknorm_i16:
6541   case Intrinsic::amdgcn_cvt_pknorm_u16:
6542   case Intrinsic::amdgcn_cvt_pk_i16:
6543   case Intrinsic::amdgcn_cvt_pk_u16: {
6544     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6545     EVT VT = Op.getValueType();
6546     unsigned Opcode;
6547 
6548     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6549       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6550     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6551       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6552     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6553       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6554     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6555       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6556     else
6557       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6558 
6559     if (isTypeLegal(VT))
6560       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6561 
6562     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6563                                Op.getOperand(1), Op.getOperand(2));
6564     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6565   }
6566   case Intrinsic::amdgcn_fmad_ftz:
6567     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6568                        Op.getOperand(2), Op.getOperand(3));
6569 
6570   case Intrinsic::amdgcn_if_break:
6571     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6572                                       Op->getOperand(1), Op->getOperand(2)), 0);
6573 
6574   case Intrinsic::amdgcn_groupstaticsize: {
6575     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6576     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6577       return Op;
6578 
6579     const Module *M = MF.getFunction().getParent();
6580     const GlobalValue *GV =
6581         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6582     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6583                                             SIInstrInfo::MO_ABS32_LO);
6584     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6585   }
6586   case Intrinsic::amdgcn_is_shared:
6587   case Intrinsic::amdgcn_is_private: {
6588     SDLoc SL(Op);
6589     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6590       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6591     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6592     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6593                                  Op.getOperand(1));
6594 
6595     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6596                                 DAG.getConstant(1, SL, MVT::i32));
6597     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6598   }
6599   case Intrinsic::amdgcn_alignbit:
6600     return DAG.getNode(ISD::FSHR, DL, VT,
6601                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6602   case Intrinsic::amdgcn_reloc_constant: {
6603     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6604     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6605     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6606     auto RelocSymbol = cast<GlobalVariable>(
6607         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6608     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6609                                             SIInstrInfo::MO_ABS32_LO);
6610     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6611   }
6612   default:
6613     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6614             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6615       return lowerImage(Op, ImageDimIntr, DAG);
6616 
6617     return Op;
6618   }
6619 }
6620 
6621 // This function computes an appropriate offset to pass to
6622 // MachineMemOperand::setOffset() based on the offset inputs to
6623 // an intrinsic.  If any of the offsets are non-contstant or
6624 // if VIndex is non-zero then this function returns 0.  Otherwise,
6625 // it returns the sum of VOffset, SOffset, and Offset.
6626 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6627                                       SDValue SOffset,
6628                                       SDValue Offset,
6629                                       SDValue VIndex = SDValue()) {
6630 
6631   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6632       !isa<ConstantSDNode>(Offset))
6633     return 0;
6634 
6635   if (VIndex) {
6636     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6637       return 0;
6638   }
6639 
6640   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6641          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6642          cast<ConstantSDNode>(Offset)->getSExtValue();
6643 }
6644 
6645 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6646                                                      SelectionDAG &DAG,
6647                                                      unsigned NewOpcode) const {
6648   SDLoc DL(Op);
6649 
6650   SDValue VData = Op.getOperand(2);
6651   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6652   SDValue Ops[] = {
6653     Op.getOperand(0), // Chain
6654     VData,            // vdata
6655     Op.getOperand(3), // rsrc
6656     DAG.getConstant(0, DL, MVT::i32), // vindex
6657     Offsets.first,    // voffset
6658     Op.getOperand(5), // soffset
6659     Offsets.second,   // offset
6660     Op.getOperand(6), // cachepolicy
6661     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6662   };
6663 
6664   auto *M = cast<MemSDNode>(Op);
6665   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6666 
6667   EVT MemVT = VData.getValueType();
6668   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6669                                  M->getMemOperand());
6670 }
6671 
6672 SDValue
6673 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6674                                                 unsigned NewOpcode) const {
6675   SDLoc DL(Op);
6676 
6677   SDValue VData = Op.getOperand(2);
6678   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6679   SDValue Ops[] = {
6680     Op.getOperand(0), // Chain
6681     VData,            // vdata
6682     Op.getOperand(3), // rsrc
6683     Op.getOperand(4), // vindex
6684     Offsets.first,    // voffset
6685     Op.getOperand(6), // soffset
6686     Offsets.second,   // offset
6687     Op.getOperand(7), // cachepolicy
6688     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6689   };
6690 
6691   auto *M = cast<MemSDNode>(Op);
6692   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6693                                                       Ops[3]));
6694 
6695   EVT MemVT = VData.getValueType();
6696   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6697                                  M->getMemOperand());
6698 }
6699 
6700 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6701                                                  SelectionDAG &DAG) const {
6702   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6703   SDLoc DL(Op);
6704 
6705   switch (IntrID) {
6706   case Intrinsic::amdgcn_ds_ordered_add:
6707   case Intrinsic::amdgcn_ds_ordered_swap: {
6708     MemSDNode *M = cast<MemSDNode>(Op);
6709     SDValue Chain = M->getOperand(0);
6710     SDValue M0 = M->getOperand(2);
6711     SDValue Value = M->getOperand(3);
6712     unsigned IndexOperand = M->getConstantOperandVal(7);
6713     unsigned WaveRelease = M->getConstantOperandVal(8);
6714     unsigned WaveDone = M->getConstantOperandVal(9);
6715 
6716     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6717     IndexOperand &= ~0x3f;
6718     unsigned CountDw = 0;
6719 
6720     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6721       CountDw = (IndexOperand >> 24) & 0xf;
6722       IndexOperand &= ~(0xf << 24);
6723 
6724       if (CountDw < 1 || CountDw > 4) {
6725         report_fatal_error(
6726             "ds_ordered_count: dword count must be between 1 and 4");
6727       }
6728     }
6729 
6730     if (IndexOperand)
6731       report_fatal_error("ds_ordered_count: bad index operand");
6732 
6733     if (WaveDone && !WaveRelease)
6734       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6735 
6736     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6737     unsigned ShaderType =
6738         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6739     unsigned Offset0 = OrderedCountIndex << 2;
6740     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6741                        (Instruction << 4);
6742 
6743     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6744       Offset1 |= (CountDw - 1) << 6;
6745 
6746     unsigned Offset = Offset0 | (Offset1 << 8);
6747 
6748     SDValue Ops[] = {
6749       Chain,
6750       Value,
6751       DAG.getTargetConstant(Offset, DL, MVT::i16),
6752       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6753     };
6754     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6755                                    M->getVTList(), Ops, M->getMemoryVT(),
6756                                    M->getMemOperand());
6757   }
6758   case Intrinsic::amdgcn_ds_fadd: {
6759     MemSDNode *M = cast<MemSDNode>(Op);
6760     unsigned Opc;
6761     switch (IntrID) {
6762     case Intrinsic::amdgcn_ds_fadd:
6763       Opc = ISD::ATOMIC_LOAD_FADD;
6764       break;
6765     }
6766 
6767     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6768                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6769                          M->getMemOperand());
6770   }
6771   case Intrinsic::amdgcn_atomic_inc:
6772   case Intrinsic::amdgcn_atomic_dec:
6773   case Intrinsic::amdgcn_ds_fmin:
6774   case Intrinsic::amdgcn_ds_fmax: {
6775     MemSDNode *M = cast<MemSDNode>(Op);
6776     unsigned Opc;
6777     switch (IntrID) {
6778     case Intrinsic::amdgcn_atomic_inc:
6779       Opc = AMDGPUISD::ATOMIC_INC;
6780       break;
6781     case Intrinsic::amdgcn_atomic_dec:
6782       Opc = AMDGPUISD::ATOMIC_DEC;
6783       break;
6784     case Intrinsic::amdgcn_ds_fmin:
6785       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6786       break;
6787     case Intrinsic::amdgcn_ds_fmax:
6788       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6789       break;
6790     default:
6791       llvm_unreachable("Unknown intrinsic!");
6792     }
6793     SDValue Ops[] = {
6794       M->getOperand(0), // Chain
6795       M->getOperand(2), // Ptr
6796       M->getOperand(3)  // Value
6797     };
6798 
6799     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6800                                    M->getMemoryVT(), M->getMemOperand());
6801   }
6802   case Intrinsic::amdgcn_buffer_load:
6803   case Intrinsic::amdgcn_buffer_load_format: {
6804     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6805     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6806     unsigned IdxEn = 1;
6807     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6808       IdxEn = Idx->getZExtValue() != 0;
6809     SDValue Ops[] = {
6810       Op.getOperand(0), // Chain
6811       Op.getOperand(2), // rsrc
6812       Op.getOperand(3), // vindex
6813       SDValue(),        // voffset -- will be set by setBufferOffsets
6814       SDValue(),        // soffset -- will be set by setBufferOffsets
6815       SDValue(),        // offset -- will be set by setBufferOffsets
6816       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6817       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6818     };
6819 
6820     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6821     // We don't know the offset if vindex is non-zero, so clear it.
6822     if (IdxEn)
6823       Offset = 0;
6824 
6825     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6826         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6827 
6828     EVT VT = Op.getValueType();
6829     EVT IntVT = VT.changeTypeToInteger();
6830     auto *M = cast<MemSDNode>(Op);
6831     M->getMemOperand()->setOffset(Offset);
6832     EVT LoadVT = Op.getValueType();
6833 
6834     if (LoadVT.getScalarType() == MVT::f16)
6835       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6836                                  M, DAG, Ops);
6837 
6838     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6839     if (LoadVT.getScalarType() == MVT::i8 ||
6840         LoadVT.getScalarType() == MVT::i16)
6841       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6842 
6843     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6844                                M->getMemOperand(), DAG);
6845   }
6846   case Intrinsic::amdgcn_raw_buffer_load:
6847   case Intrinsic::amdgcn_raw_buffer_load_format: {
6848     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6849 
6850     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6851     SDValue Ops[] = {
6852       Op.getOperand(0), // Chain
6853       Op.getOperand(2), // rsrc
6854       DAG.getConstant(0, DL, MVT::i32), // vindex
6855       Offsets.first,    // voffset
6856       Op.getOperand(4), // soffset
6857       Offsets.second,   // offset
6858       Op.getOperand(5), // cachepolicy, swizzled buffer
6859       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6860     };
6861 
6862     auto *M = cast<MemSDNode>(Op);
6863     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6864     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6865   }
6866   case Intrinsic::amdgcn_struct_buffer_load:
6867   case Intrinsic::amdgcn_struct_buffer_load_format: {
6868     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6869 
6870     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6871     SDValue Ops[] = {
6872       Op.getOperand(0), // Chain
6873       Op.getOperand(2), // rsrc
6874       Op.getOperand(3), // vindex
6875       Offsets.first,    // voffset
6876       Op.getOperand(5), // soffset
6877       Offsets.second,   // offset
6878       Op.getOperand(6), // cachepolicy, swizzled buffer
6879       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6880     };
6881 
6882     auto *M = cast<MemSDNode>(Op);
6883     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6884                                                         Ops[2]));
6885     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6886   }
6887   case Intrinsic::amdgcn_tbuffer_load: {
6888     MemSDNode *M = cast<MemSDNode>(Op);
6889     EVT LoadVT = Op.getValueType();
6890 
6891     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6892     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6893     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6894     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6895     unsigned IdxEn = 1;
6896     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6897       IdxEn = Idx->getZExtValue() != 0;
6898     SDValue Ops[] = {
6899       Op.getOperand(0),  // Chain
6900       Op.getOperand(2),  // rsrc
6901       Op.getOperand(3),  // vindex
6902       Op.getOperand(4),  // voffset
6903       Op.getOperand(5),  // soffset
6904       Op.getOperand(6),  // offset
6905       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6906       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6907       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6908     };
6909 
6910     if (LoadVT.getScalarType() == MVT::f16)
6911       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6912                                  M, DAG, Ops);
6913     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6914                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6915                                DAG);
6916   }
6917   case Intrinsic::amdgcn_raw_tbuffer_load: {
6918     MemSDNode *M = cast<MemSDNode>(Op);
6919     EVT LoadVT = Op.getValueType();
6920     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6921 
6922     SDValue Ops[] = {
6923       Op.getOperand(0),  // Chain
6924       Op.getOperand(2),  // rsrc
6925       DAG.getConstant(0, DL, MVT::i32), // vindex
6926       Offsets.first,     // voffset
6927       Op.getOperand(4),  // soffset
6928       Offsets.second,    // offset
6929       Op.getOperand(5),  // format
6930       Op.getOperand(6),  // cachepolicy, swizzled buffer
6931       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6932     };
6933 
6934     if (LoadVT.getScalarType() == MVT::f16)
6935       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6936                                  M, DAG, Ops);
6937     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6938                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6939                                DAG);
6940   }
6941   case Intrinsic::amdgcn_struct_tbuffer_load: {
6942     MemSDNode *M = cast<MemSDNode>(Op);
6943     EVT LoadVT = Op.getValueType();
6944     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6945 
6946     SDValue Ops[] = {
6947       Op.getOperand(0),  // Chain
6948       Op.getOperand(2),  // rsrc
6949       Op.getOperand(3),  // vindex
6950       Offsets.first,     // voffset
6951       Op.getOperand(5),  // soffset
6952       Offsets.second,    // offset
6953       Op.getOperand(6),  // format
6954       Op.getOperand(7),  // cachepolicy, swizzled buffer
6955       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6956     };
6957 
6958     if (LoadVT.getScalarType() == MVT::f16)
6959       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6960                                  M, DAG, Ops);
6961     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6962                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6963                                DAG);
6964   }
6965   case Intrinsic::amdgcn_buffer_atomic_swap:
6966   case Intrinsic::amdgcn_buffer_atomic_add:
6967   case Intrinsic::amdgcn_buffer_atomic_sub:
6968   case Intrinsic::amdgcn_buffer_atomic_csub:
6969   case Intrinsic::amdgcn_buffer_atomic_smin:
6970   case Intrinsic::amdgcn_buffer_atomic_umin:
6971   case Intrinsic::amdgcn_buffer_atomic_smax:
6972   case Intrinsic::amdgcn_buffer_atomic_umax:
6973   case Intrinsic::amdgcn_buffer_atomic_and:
6974   case Intrinsic::amdgcn_buffer_atomic_or:
6975   case Intrinsic::amdgcn_buffer_atomic_xor: {
6976     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6977     unsigned IdxEn = 1;
6978     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6979       IdxEn = Idx->getZExtValue() != 0;
6980     SDValue Ops[] = {
6981       Op.getOperand(0), // Chain
6982       Op.getOperand(2), // vdata
6983       Op.getOperand(3), // rsrc
6984       Op.getOperand(4), // vindex
6985       SDValue(),        // voffset -- will be set by setBufferOffsets
6986       SDValue(),        // soffset -- will be set by setBufferOffsets
6987       SDValue(),        // offset -- will be set by setBufferOffsets
6988       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6989       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6990     };
6991     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6992     // We don't know the offset if vindex is non-zero, so clear it.
6993     if (IdxEn)
6994       Offset = 0;
6995     EVT VT = Op.getValueType();
6996 
6997     auto *M = cast<MemSDNode>(Op);
6998     M->getMemOperand()->setOffset(Offset);
6999     unsigned Opcode = 0;
7000 
7001     switch (IntrID) {
7002     case Intrinsic::amdgcn_buffer_atomic_swap:
7003       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7004       break;
7005     case Intrinsic::amdgcn_buffer_atomic_add:
7006       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7007       break;
7008     case Intrinsic::amdgcn_buffer_atomic_sub:
7009       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7010       break;
7011     case Intrinsic::amdgcn_buffer_atomic_csub:
7012       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7013       break;
7014     case Intrinsic::amdgcn_buffer_atomic_smin:
7015       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7016       break;
7017     case Intrinsic::amdgcn_buffer_atomic_umin:
7018       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7019       break;
7020     case Intrinsic::amdgcn_buffer_atomic_smax:
7021       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7022       break;
7023     case Intrinsic::amdgcn_buffer_atomic_umax:
7024       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7025       break;
7026     case Intrinsic::amdgcn_buffer_atomic_and:
7027       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7028       break;
7029     case Intrinsic::amdgcn_buffer_atomic_or:
7030       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7031       break;
7032     case Intrinsic::amdgcn_buffer_atomic_xor:
7033       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7034       break;
7035     default:
7036       llvm_unreachable("unhandled atomic opcode");
7037     }
7038 
7039     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7040                                    M->getMemOperand());
7041   }
7042   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7043     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7044   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7045     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7046   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7047     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7048   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7049     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7050   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7051     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7052   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7053     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7054   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7055     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7056   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7057     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7058   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7059     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7060   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7061     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7062   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7063     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7064   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7065     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7066   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7067     return lowerStructBufferAtomicIntrin(Op, DAG,
7068                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7069   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7070     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7071   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7072     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7073   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7074     return lowerStructBufferAtomicIntrin(Op, DAG,
7075                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7076   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7077     return lowerStructBufferAtomicIntrin(Op, DAG,
7078                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7079   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7080     return lowerStructBufferAtomicIntrin(Op, DAG,
7081                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7082   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7083     return lowerStructBufferAtomicIntrin(Op, DAG,
7084                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7085   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7086     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7087   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7088     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7089   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7090     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7091   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7092     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7093   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7094     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7095 
7096   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7097     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7098     unsigned IdxEn = 1;
7099     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7100       IdxEn = Idx->getZExtValue() != 0;
7101     SDValue Ops[] = {
7102       Op.getOperand(0), // Chain
7103       Op.getOperand(2), // src
7104       Op.getOperand(3), // cmp
7105       Op.getOperand(4), // rsrc
7106       Op.getOperand(5), // vindex
7107       SDValue(),        // voffset -- will be set by setBufferOffsets
7108       SDValue(),        // soffset -- will be set by setBufferOffsets
7109       SDValue(),        // offset -- will be set by setBufferOffsets
7110       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7111       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7112     };
7113     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7114     // We don't know the offset if vindex is non-zero, so clear it.
7115     if (IdxEn)
7116       Offset = 0;
7117     EVT VT = Op.getValueType();
7118     auto *M = cast<MemSDNode>(Op);
7119     M->getMemOperand()->setOffset(Offset);
7120 
7121     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7122                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7123   }
7124   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7125     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7126     SDValue Ops[] = {
7127       Op.getOperand(0), // Chain
7128       Op.getOperand(2), // src
7129       Op.getOperand(3), // cmp
7130       Op.getOperand(4), // rsrc
7131       DAG.getConstant(0, DL, MVT::i32), // vindex
7132       Offsets.first,    // voffset
7133       Op.getOperand(6), // soffset
7134       Offsets.second,   // offset
7135       Op.getOperand(7), // cachepolicy
7136       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7137     };
7138     EVT VT = Op.getValueType();
7139     auto *M = cast<MemSDNode>(Op);
7140     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7141 
7142     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7143                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7144   }
7145   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7146     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7147     SDValue Ops[] = {
7148       Op.getOperand(0), // Chain
7149       Op.getOperand(2), // src
7150       Op.getOperand(3), // cmp
7151       Op.getOperand(4), // rsrc
7152       Op.getOperand(5), // vindex
7153       Offsets.first,    // voffset
7154       Op.getOperand(7), // soffset
7155       Offsets.second,   // offset
7156       Op.getOperand(8), // cachepolicy
7157       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7158     };
7159     EVT VT = Op.getValueType();
7160     auto *M = cast<MemSDNode>(Op);
7161     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7162                                                         Ops[4]));
7163 
7164     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7165                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7166   }
7167   default:
7168     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7169             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7170       return lowerImage(Op, ImageDimIntr, DAG);
7171 
7172     return SDValue();
7173   }
7174 }
7175 
7176 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7177 // dwordx4 if on SI.
7178 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7179                                               SDVTList VTList,
7180                                               ArrayRef<SDValue> Ops, EVT MemVT,
7181                                               MachineMemOperand *MMO,
7182                                               SelectionDAG &DAG) const {
7183   EVT VT = VTList.VTs[0];
7184   EVT WidenedVT = VT;
7185   EVT WidenedMemVT = MemVT;
7186   if (!Subtarget->hasDwordx3LoadStores() &&
7187       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7188     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7189                                  WidenedVT.getVectorElementType(), 4);
7190     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7191                                     WidenedMemVT.getVectorElementType(), 4);
7192     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7193   }
7194 
7195   assert(VTList.NumVTs == 2);
7196   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7197 
7198   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7199                                        WidenedMemVT, MMO);
7200   if (WidenedVT != VT) {
7201     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7202                                DAG.getVectorIdxConstant(0, DL));
7203     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7204   }
7205   return NewOp;
7206 }
7207 
7208 SDValue SITargetLowering::handleD16VData(SDValue VData,
7209                                          SelectionDAG &DAG) const {
7210   EVT StoreVT = VData.getValueType();
7211 
7212   // No change for f16 and legal vector D16 types.
7213   if (!StoreVT.isVector())
7214     return VData;
7215 
7216   SDLoc DL(VData);
7217   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
7218 
7219   if (Subtarget->hasUnpackedD16VMem()) {
7220     // We need to unpack the packed data to store.
7221     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7222     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7223 
7224     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
7225                                         StoreVT.getVectorNumElements());
7226     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7227     return DAG.UnrollVectorOp(ZExt.getNode());
7228   }
7229 
7230   assert(isTypeLegal(StoreVT));
7231   return VData;
7232 }
7233 
7234 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7235                                               SelectionDAG &DAG) const {
7236   SDLoc DL(Op);
7237   SDValue Chain = Op.getOperand(0);
7238   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7239   MachineFunction &MF = DAG.getMachineFunction();
7240 
7241   switch (IntrinsicID) {
7242   case Intrinsic::amdgcn_exp_compr: {
7243     SDValue Src0 = Op.getOperand(4);
7244     SDValue Src1 = Op.getOperand(5);
7245     // Hack around illegal type on SI by directly selecting it.
7246     if (isTypeLegal(Src0.getValueType()))
7247       return SDValue();
7248 
7249     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7250     SDValue Undef = DAG.getUNDEF(MVT::f32);
7251     const SDValue Ops[] = {
7252       Op.getOperand(2), // tgt
7253       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7254       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7255       Undef, // src2
7256       Undef, // src3
7257       Op.getOperand(7), // vm
7258       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7259       Op.getOperand(3), // en
7260       Op.getOperand(0) // Chain
7261     };
7262 
7263     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7264     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7265   }
7266   case Intrinsic::amdgcn_s_barrier: {
7267     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7268       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7269       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7270       if (WGSize <= ST.getWavefrontSize())
7271         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7272                                           Op.getOperand(0)), 0);
7273     }
7274     return SDValue();
7275   };
7276   case Intrinsic::amdgcn_tbuffer_store: {
7277     SDValue VData = Op.getOperand(2);
7278     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7279     if (IsD16)
7280       VData = handleD16VData(VData, DAG);
7281     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7282     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7283     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7284     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7285     unsigned IdxEn = 1;
7286     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7287       IdxEn = Idx->getZExtValue() != 0;
7288     SDValue Ops[] = {
7289       Chain,
7290       VData,             // vdata
7291       Op.getOperand(3),  // rsrc
7292       Op.getOperand(4),  // vindex
7293       Op.getOperand(5),  // voffset
7294       Op.getOperand(6),  // soffset
7295       Op.getOperand(7),  // offset
7296       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7297       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7298       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7299     };
7300     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7301                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7302     MemSDNode *M = cast<MemSDNode>(Op);
7303     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7304                                    M->getMemoryVT(), M->getMemOperand());
7305   }
7306 
7307   case Intrinsic::amdgcn_struct_tbuffer_store: {
7308     SDValue VData = Op.getOperand(2);
7309     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7310     if (IsD16)
7311       VData = handleD16VData(VData, DAG);
7312     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7313     SDValue Ops[] = {
7314       Chain,
7315       VData,             // vdata
7316       Op.getOperand(3),  // rsrc
7317       Op.getOperand(4),  // vindex
7318       Offsets.first,     // voffset
7319       Op.getOperand(6),  // soffset
7320       Offsets.second,    // offset
7321       Op.getOperand(7),  // format
7322       Op.getOperand(8),  // cachepolicy, swizzled buffer
7323       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7324     };
7325     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7326                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7327     MemSDNode *M = cast<MemSDNode>(Op);
7328     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7329                                    M->getMemoryVT(), M->getMemOperand());
7330   }
7331 
7332   case Intrinsic::amdgcn_raw_tbuffer_store: {
7333     SDValue VData = Op.getOperand(2);
7334     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7335     if (IsD16)
7336       VData = handleD16VData(VData, DAG);
7337     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7338     SDValue Ops[] = {
7339       Chain,
7340       VData,             // vdata
7341       Op.getOperand(3),  // rsrc
7342       DAG.getConstant(0, DL, MVT::i32), // vindex
7343       Offsets.first,     // voffset
7344       Op.getOperand(5),  // soffset
7345       Offsets.second,    // offset
7346       Op.getOperand(6),  // format
7347       Op.getOperand(7),  // cachepolicy, swizzled buffer
7348       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7349     };
7350     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7351                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7352     MemSDNode *M = cast<MemSDNode>(Op);
7353     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7354                                    M->getMemoryVT(), M->getMemOperand());
7355   }
7356 
7357   case Intrinsic::amdgcn_buffer_store:
7358   case Intrinsic::amdgcn_buffer_store_format: {
7359     SDValue VData = Op.getOperand(2);
7360     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7361     if (IsD16)
7362       VData = handleD16VData(VData, DAG);
7363     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7364     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7365     unsigned IdxEn = 1;
7366     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7367       IdxEn = Idx->getZExtValue() != 0;
7368     SDValue Ops[] = {
7369       Chain,
7370       VData,
7371       Op.getOperand(3), // rsrc
7372       Op.getOperand(4), // vindex
7373       SDValue(), // voffset -- will be set by setBufferOffsets
7374       SDValue(), // soffset -- will be set by setBufferOffsets
7375       SDValue(), // offset -- will be set by setBufferOffsets
7376       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7377       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7378     };
7379     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7380     // We don't know the offset if vindex is non-zero, so clear it.
7381     if (IdxEn)
7382       Offset = 0;
7383     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7384                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7385     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7386     MemSDNode *M = cast<MemSDNode>(Op);
7387     M->getMemOperand()->setOffset(Offset);
7388 
7389     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7390     EVT VDataType = VData.getValueType().getScalarType();
7391     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7392       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7393 
7394     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7395                                    M->getMemoryVT(), M->getMemOperand());
7396   }
7397 
7398   case Intrinsic::amdgcn_raw_buffer_store:
7399   case Intrinsic::amdgcn_raw_buffer_store_format: {
7400     const bool IsFormat =
7401         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7402 
7403     SDValue VData = Op.getOperand(2);
7404     EVT VDataVT = VData.getValueType();
7405     EVT EltType = VDataVT.getScalarType();
7406     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7407     if (IsD16)
7408       VData = handleD16VData(VData, DAG);
7409 
7410     if (!isTypeLegal(VDataVT)) {
7411       VData =
7412           DAG.getNode(ISD::BITCAST, DL,
7413                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7414     }
7415 
7416     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7417     SDValue Ops[] = {
7418       Chain,
7419       VData,
7420       Op.getOperand(3), // rsrc
7421       DAG.getConstant(0, DL, MVT::i32), // vindex
7422       Offsets.first,    // voffset
7423       Op.getOperand(5), // soffset
7424       Offsets.second,   // offset
7425       Op.getOperand(6), // cachepolicy, swizzled buffer
7426       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7427     };
7428     unsigned Opc =
7429         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7430     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7431     MemSDNode *M = cast<MemSDNode>(Op);
7432     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7433 
7434     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7435     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7436       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7437 
7438     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7439                                    M->getMemoryVT(), M->getMemOperand());
7440   }
7441 
7442   case Intrinsic::amdgcn_struct_buffer_store:
7443   case Intrinsic::amdgcn_struct_buffer_store_format: {
7444     const bool IsFormat =
7445         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7446 
7447     SDValue VData = Op.getOperand(2);
7448     EVT VDataVT = VData.getValueType();
7449     EVT EltType = VDataVT.getScalarType();
7450     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7451 
7452     if (IsD16)
7453       VData = handleD16VData(VData, DAG);
7454 
7455     if (!isTypeLegal(VDataVT)) {
7456       VData =
7457           DAG.getNode(ISD::BITCAST, DL,
7458                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7459     }
7460 
7461     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7462     SDValue Ops[] = {
7463       Chain,
7464       VData,
7465       Op.getOperand(3), // rsrc
7466       Op.getOperand(4), // vindex
7467       Offsets.first,    // voffset
7468       Op.getOperand(6), // soffset
7469       Offsets.second,   // offset
7470       Op.getOperand(7), // cachepolicy, swizzled buffer
7471       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7472     };
7473     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7474                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7475     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7476     MemSDNode *M = cast<MemSDNode>(Op);
7477     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7478                                                         Ops[3]));
7479 
7480     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7481     EVT VDataType = VData.getValueType().getScalarType();
7482     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7483       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7484 
7485     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7486                                    M->getMemoryVT(), M->getMemOperand());
7487   }
7488   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7489     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7490   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7491     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7492   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7493     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7494     unsigned IdxEn = 1;
7495     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7496       IdxEn = Idx->getZExtValue() != 0;
7497     SDValue Ops[] = {
7498       Chain,
7499       Op.getOperand(2), // vdata
7500       Op.getOperand(3), // rsrc
7501       Op.getOperand(4), // vindex
7502       SDValue(),        // voffset -- will be set by setBufferOffsets
7503       SDValue(),        // soffset -- will be set by setBufferOffsets
7504       SDValue(),        // offset -- will be set by setBufferOffsets
7505       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7506       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7507     };
7508     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7509     // We don't know the offset if vindex is non-zero, so clear it.
7510     if (IdxEn)
7511       Offset = 0;
7512     EVT VT = Op.getOperand(2).getValueType();
7513 
7514     auto *M = cast<MemSDNode>(Op);
7515     M->getMemOperand()->setOffset(Offset);
7516 
7517     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_FADD, DL,
7518                                    Op->getVTList(), Ops, VT,
7519                                    M->getMemOperand());
7520   }
7521 
7522   case Intrinsic::amdgcn_global_atomic_fadd: {
7523     SDValue Ops[] = {
7524       Chain,
7525       Op.getOperand(2), // ptr
7526       Op.getOperand(3)  // vdata
7527     };
7528 
7529     EVT VT = Op.getOperand(3).getValueType();
7530     auto *M = cast<MemSDNode>(Op);
7531 
7532     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7533                          DAG.getVTList(VT, MVT::Other), Ops,
7534                          M->getMemOperand()).getValue(1);
7535   }
7536   case Intrinsic::amdgcn_end_cf:
7537     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7538                                       Op->getOperand(2), Chain), 0);
7539 
7540   default: {
7541     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7542             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7543       return lowerImage(Op, ImageDimIntr, DAG);
7544 
7545     return Op;
7546   }
7547   }
7548 }
7549 
7550 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7551 // offset (the offset that is included in bounds checking and swizzling, to be
7552 // split between the instruction's voffset and immoffset fields) and soffset
7553 // (the offset that is excluded from bounds checking and swizzling, to go in
7554 // the instruction's soffset field).  This function takes the first kind of
7555 // offset and figures out how to split it between voffset and immoffset.
7556 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7557     SDValue Offset, SelectionDAG &DAG) const {
7558   SDLoc DL(Offset);
7559   const unsigned MaxImm = 4095;
7560   SDValue N0 = Offset;
7561   ConstantSDNode *C1 = nullptr;
7562 
7563   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7564     N0 = SDValue();
7565   else if (DAG.isBaseWithConstantOffset(N0)) {
7566     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7567     N0 = N0.getOperand(0);
7568   }
7569 
7570   if (C1) {
7571     unsigned ImmOffset = C1->getZExtValue();
7572     // If the immediate value is too big for the immoffset field, put the value
7573     // and -4096 into the immoffset field so that the value that is copied/added
7574     // for the voffset field is a multiple of 4096, and it stands more chance
7575     // of being CSEd with the copy/add for another similar load/store.
7576     // However, do not do that rounding down to a multiple of 4096 if that is a
7577     // negative number, as it appears to be illegal to have a negative offset
7578     // in the vgpr, even if adding the immediate offset makes it positive.
7579     unsigned Overflow = ImmOffset & ~MaxImm;
7580     ImmOffset -= Overflow;
7581     if ((int32_t)Overflow < 0) {
7582       Overflow += ImmOffset;
7583       ImmOffset = 0;
7584     }
7585     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7586     if (Overflow) {
7587       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7588       if (!N0)
7589         N0 = OverflowVal;
7590       else {
7591         SDValue Ops[] = { N0, OverflowVal };
7592         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7593       }
7594     }
7595   }
7596   if (!N0)
7597     N0 = DAG.getConstant(0, DL, MVT::i32);
7598   if (!C1)
7599     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7600   return {N0, SDValue(C1, 0)};
7601 }
7602 
7603 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7604 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7605 // pointed to by Offsets.
7606 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7607                                             SelectionDAG &DAG, SDValue *Offsets,
7608                                             Align Alignment) const {
7609   SDLoc DL(CombinedOffset);
7610   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7611     uint32_t Imm = C->getZExtValue();
7612     uint32_t SOffset, ImmOffset;
7613     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7614                                  Alignment)) {
7615       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7616       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7617       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7618       return SOffset + ImmOffset;
7619     }
7620   }
7621   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7622     SDValue N0 = CombinedOffset.getOperand(0);
7623     SDValue N1 = CombinedOffset.getOperand(1);
7624     uint32_t SOffset, ImmOffset;
7625     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7626     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7627                                                 Subtarget, Alignment)) {
7628       Offsets[0] = N0;
7629       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7630       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7631       return 0;
7632     }
7633   }
7634   Offsets[0] = CombinedOffset;
7635   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7636   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7637   return 0;
7638 }
7639 
7640 // Handle 8 bit and 16 bit buffer loads
7641 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7642                                                      EVT LoadVT, SDLoc DL,
7643                                                      ArrayRef<SDValue> Ops,
7644                                                      MemSDNode *M) const {
7645   EVT IntVT = LoadVT.changeTypeToInteger();
7646   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7647          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7648 
7649   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7650   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7651                                                Ops, IntVT,
7652                                                M->getMemOperand());
7653   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7654   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7655 
7656   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7657 }
7658 
7659 // Handle 8 bit and 16 bit buffer stores
7660 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7661                                                       EVT VDataType, SDLoc DL,
7662                                                       SDValue Ops[],
7663                                                       MemSDNode *M) const {
7664   if (VDataType == MVT::f16)
7665     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7666 
7667   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7668   Ops[1] = BufferStoreExt;
7669   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7670                                  AMDGPUISD::BUFFER_STORE_SHORT;
7671   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7672   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7673                                      M->getMemOperand());
7674 }
7675 
7676 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7677                                  ISD::LoadExtType ExtType, SDValue Op,
7678                                  const SDLoc &SL, EVT VT) {
7679   if (VT.bitsLT(Op.getValueType()))
7680     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7681 
7682   switch (ExtType) {
7683   case ISD::SEXTLOAD:
7684     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7685   case ISD::ZEXTLOAD:
7686     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7687   case ISD::EXTLOAD:
7688     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7689   case ISD::NON_EXTLOAD:
7690     return Op;
7691   }
7692 
7693   llvm_unreachable("invalid ext type");
7694 }
7695 
7696 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7697   SelectionDAG &DAG = DCI.DAG;
7698   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7699     return SDValue();
7700 
7701   // FIXME: Constant loads should all be marked invariant.
7702   unsigned AS = Ld->getAddressSpace();
7703   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7704       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7705       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7706     return SDValue();
7707 
7708   // Don't do this early, since it may interfere with adjacent load merging for
7709   // illegal types. We can avoid losing alignment information for exotic types
7710   // pre-legalize.
7711   EVT MemVT = Ld->getMemoryVT();
7712   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7713       MemVT.getSizeInBits() >= 32)
7714     return SDValue();
7715 
7716   SDLoc SL(Ld);
7717 
7718   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7719          "unexpected vector extload");
7720 
7721   // TODO: Drop only high part of range.
7722   SDValue Ptr = Ld->getBasePtr();
7723   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7724                                 MVT::i32, SL, Ld->getChain(), Ptr,
7725                                 Ld->getOffset(),
7726                                 Ld->getPointerInfo(), MVT::i32,
7727                                 Ld->getAlignment(),
7728                                 Ld->getMemOperand()->getFlags(),
7729                                 Ld->getAAInfo(),
7730                                 nullptr); // Drop ranges
7731 
7732   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7733   if (MemVT.isFloatingPoint()) {
7734     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7735            "unexpected fp extload");
7736     TruncVT = MemVT.changeTypeToInteger();
7737   }
7738 
7739   SDValue Cvt = NewLoad;
7740   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7741     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7742                       DAG.getValueType(TruncVT));
7743   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7744              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7745     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7746   } else {
7747     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7748   }
7749 
7750   EVT VT = Ld->getValueType(0);
7751   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7752 
7753   DCI.AddToWorklist(Cvt.getNode());
7754 
7755   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7756   // the appropriate extension from the 32-bit load.
7757   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7758   DCI.AddToWorklist(Cvt.getNode());
7759 
7760   // Handle conversion back to floating point if necessary.
7761   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7762 
7763   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7764 }
7765 
7766 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7767   SDLoc DL(Op);
7768   LoadSDNode *Load = cast<LoadSDNode>(Op);
7769   ISD::LoadExtType ExtType = Load->getExtensionType();
7770   EVT MemVT = Load->getMemoryVT();
7771 
7772   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7773     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7774       return SDValue();
7775 
7776     // FIXME: Copied from PPC
7777     // First, load into 32 bits, then truncate to 1 bit.
7778 
7779     SDValue Chain = Load->getChain();
7780     SDValue BasePtr = Load->getBasePtr();
7781     MachineMemOperand *MMO = Load->getMemOperand();
7782 
7783     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7784 
7785     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7786                                    BasePtr, RealMemVT, MMO);
7787 
7788     if (!MemVT.isVector()) {
7789       SDValue Ops[] = {
7790         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7791         NewLD.getValue(1)
7792       };
7793 
7794       return DAG.getMergeValues(Ops, DL);
7795     }
7796 
7797     SmallVector<SDValue, 3> Elts;
7798     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7799       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7800                                 DAG.getConstant(I, DL, MVT::i32));
7801 
7802       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7803     }
7804 
7805     SDValue Ops[] = {
7806       DAG.getBuildVector(MemVT, DL, Elts),
7807       NewLD.getValue(1)
7808     };
7809 
7810     return DAG.getMergeValues(Ops, DL);
7811   }
7812 
7813   if (!MemVT.isVector())
7814     return SDValue();
7815 
7816   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7817          "Custom lowering for non-i32 vectors hasn't been implemented.");
7818 
7819   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7820                                       MemVT, *Load->getMemOperand())) {
7821     SDValue Ops[2];
7822     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7823     return DAG.getMergeValues(Ops, DL);
7824   }
7825 
7826   unsigned Alignment = Load->getAlignment();
7827   unsigned AS = Load->getAddressSpace();
7828   if (Subtarget->hasLDSMisalignedBug() &&
7829       AS == AMDGPUAS::FLAT_ADDRESS &&
7830       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7831     return SplitVectorLoad(Op, DAG);
7832   }
7833 
7834   MachineFunction &MF = DAG.getMachineFunction();
7835   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7836   // If there is a possibilty that flat instruction access scratch memory
7837   // then we need to use the same legalization rules we use for private.
7838   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7839       !Subtarget->hasMultiDwordFlatScratchAddressing())
7840     AS = MFI->hasFlatScratchInit() ?
7841          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7842 
7843   unsigned NumElements = MemVT.getVectorNumElements();
7844 
7845   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7846       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7847     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7848       if (MemVT.isPow2VectorType())
7849         return SDValue();
7850       if (NumElements == 3)
7851         return WidenVectorLoad(Op, DAG);
7852       return SplitVectorLoad(Op, DAG);
7853     }
7854     // Non-uniform loads will be selected to MUBUF instructions, so they
7855     // have the same legalization requirements as global and private
7856     // loads.
7857     //
7858   }
7859 
7860   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7861       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7862       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7863     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7864         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7865         Alignment >= 4 && NumElements < 32) {
7866       if (MemVT.isPow2VectorType())
7867         return SDValue();
7868       if (NumElements == 3)
7869         return WidenVectorLoad(Op, DAG);
7870       return SplitVectorLoad(Op, DAG);
7871     }
7872     // Non-uniform loads will be selected to MUBUF instructions, so they
7873     // have the same legalization requirements as global and private
7874     // loads.
7875     //
7876   }
7877   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7878       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7879       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7880       AS == AMDGPUAS::FLAT_ADDRESS) {
7881     if (NumElements > 4)
7882       return SplitVectorLoad(Op, DAG);
7883     // v3 loads not supported on SI.
7884     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7885       return WidenVectorLoad(Op, DAG);
7886     // v3 and v4 loads are supported for private and global memory.
7887     return SDValue();
7888   }
7889   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7890     // Depending on the setting of the private_element_size field in the
7891     // resource descriptor, we can only make private accesses up to a certain
7892     // size.
7893     switch (Subtarget->getMaxPrivateElementSize()) {
7894     case 4: {
7895       SDValue Ops[2];
7896       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7897       return DAG.getMergeValues(Ops, DL);
7898     }
7899     case 8:
7900       if (NumElements > 2)
7901         return SplitVectorLoad(Op, DAG);
7902       return SDValue();
7903     case 16:
7904       // Same as global/flat
7905       if (NumElements > 4)
7906         return SplitVectorLoad(Op, DAG);
7907       // v3 loads not supported on SI.
7908       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7909         return WidenVectorLoad(Op, DAG);
7910       return SDValue();
7911     default:
7912       llvm_unreachable("unsupported private_element_size");
7913     }
7914   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7915     // Use ds_read_b128 if possible.
7916     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7917         MemVT.getStoreSize() == 16)
7918       return SDValue();
7919 
7920     if (NumElements > 2)
7921       return SplitVectorLoad(Op, DAG);
7922 
7923     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7924     // address is negative, then the instruction is incorrectly treated as
7925     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7926     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7927     // load later in the SILoadStoreOptimizer.
7928     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7929         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7930         Load->getAlignment() < 8) {
7931       return SplitVectorLoad(Op, DAG);
7932     }
7933   }
7934   return SDValue();
7935 }
7936 
7937 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7938   EVT VT = Op.getValueType();
7939   assert(VT.getSizeInBits() == 64);
7940 
7941   SDLoc DL(Op);
7942   SDValue Cond = Op.getOperand(0);
7943 
7944   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7945   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7946 
7947   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7948   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7949 
7950   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7951   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7952 
7953   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7954 
7955   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7956   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7957 
7958   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7959 
7960   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7961   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7962 }
7963 
7964 // Catch division cases where we can use shortcuts with rcp and rsq
7965 // instructions.
7966 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7967                                               SelectionDAG &DAG) const {
7968   SDLoc SL(Op);
7969   SDValue LHS = Op.getOperand(0);
7970   SDValue RHS = Op.getOperand(1);
7971   EVT VT = Op.getValueType();
7972   const SDNodeFlags Flags = Op->getFlags();
7973 
7974   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7975                             Flags.hasApproximateFuncs();
7976 
7977   // Without !fpmath accuracy information, we can't do more because we don't
7978   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7979   if (!AllowInaccurateRcp)
7980     return SDValue();
7981 
7982   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7983     if (CLHS->isExactlyValue(1.0)) {
7984       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7985       // the CI documentation has a worst case error of 1 ulp.
7986       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7987       // use it as long as we aren't trying to use denormals.
7988       //
7989       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7990 
7991       // 1.0 / sqrt(x) -> rsq(x)
7992 
7993       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7994       // error seems really high at 2^29 ULP.
7995       if (RHS.getOpcode() == ISD::FSQRT)
7996         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7997 
7998       // 1.0 / x -> rcp(x)
7999       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8000     }
8001 
8002     // Same as for 1.0, but expand the sign out of the constant.
8003     if (CLHS->isExactlyValue(-1.0)) {
8004       // -1.0 / x -> rcp (fneg x)
8005       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8006       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8007     }
8008   }
8009 
8010   // Turn into multiply by the reciprocal.
8011   // x / y -> x * (1.0 / y)
8012   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8013   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8014 }
8015 
8016 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8017                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8018                           SDNodeFlags Flags) {
8019   if (GlueChain->getNumValues() <= 1) {
8020     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8021   }
8022 
8023   assert(GlueChain->getNumValues() == 3);
8024 
8025   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8026   switch (Opcode) {
8027   default: llvm_unreachable("no chain equivalent for opcode");
8028   case ISD::FMUL:
8029     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8030     break;
8031   }
8032 
8033   return DAG.getNode(Opcode, SL, VTList,
8034                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8035                      Flags);
8036 }
8037 
8038 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8039                            EVT VT, SDValue A, SDValue B, SDValue C,
8040                            SDValue GlueChain, SDNodeFlags Flags) {
8041   if (GlueChain->getNumValues() <= 1) {
8042     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8043   }
8044 
8045   assert(GlueChain->getNumValues() == 3);
8046 
8047   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8048   switch (Opcode) {
8049   default: llvm_unreachable("no chain equivalent for opcode");
8050   case ISD::FMA:
8051     Opcode = AMDGPUISD::FMA_W_CHAIN;
8052     break;
8053   }
8054 
8055   return DAG.getNode(Opcode, SL, VTList,
8056                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8057                      Flags);
8058 }
8059 
8060 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8061   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8062     return FastLowered;
8063 
8064   SDLoc SL(Op);
8065   SDValue Src0 = Op.getOperand(0);
8066   SDValue Src1 = Op.getOperand(1);
8067 
8068   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8069   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8070 
8071   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8072   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8073 
8074   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8075   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8076 
8077   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8078 }
8079 
8080 // Faster 2.5 ULP division that does not support denormals.
8081 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8082   SDLoc SL(Op);
8083   SDValue LHS = Op.getOperand(1);
8084   SDValue RHS = Op.getOperand(2);
8085 
8086   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8087 
8088   const APFloat K0Val(BitsToFloat(0x6f800000));
8089   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8090 
8091   const APFloat K1Val(BitsToFloat(0x2f800000));
8092   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8093 
8094   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8095 
8096   EVT SetCCVT =
8097     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8098 
8099   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8100 
8101   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8102 
8103   // TODO: Should this propagate fast-math-flags?
8104   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8105 
8106   // rcp does not support denormals.
8107   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8108 
8109   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8110 
8111   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8112 }
8113 
8114 // Returns immediate value for setting the F32 denorm mode when using the
8115 // S_DENORM_MODE instruction.
8116 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8117                                           const SDLoc &SL, const GCNSubtarget *ST) {
8118   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8119   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8120                                 ? FP_DENORM_FLUSH_NONE
8121                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8122 
8123   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8124   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8125 }
8126 
8127 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8128   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8129     return FastLowered;
8130 
8131   // The selection matcher assumes anything with a chain selecting to a
8132   // mayRaiseFPException machine instruction. Since we're introducing a chain
8133   // here, we need to explicitly report nofpexcept for the regular fdiv
8134   // lowering.
8135   SDNodeFlags Flags = Op->getFlags();
8136   Flags.setNoFPExcept(true);
8137 
8138   SDLoc SL(Op);
8139   SDValue LHS = Op.getOperand(0);
8140   SDValue RHS = Op.getOperand(1);
8141 
8142   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8143 
8144   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8145 
8146   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8147                                           {RHS, RHS, LHS}, Flags);
8148   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8149                                         {LHS, RHS, LHS}, Flags);
8150 
8151   // Denominator is scaled to not be denormal, so using rcp is ok.
8152   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8153                                   DenominatorScaled, Flags);
8154   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8155                                      DenominatorScaled, Flags);
8156 
8157   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8158                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8159                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8160   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8161 
8162   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8163 
8164   if (!HasFP32Denormals) {
8165     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8166     // lowering. The chain dependence is insufficient, and we need glue. We do
8167     // not need the glue variants in a strictfp function.
8168 
8169     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8170 
8171     SDNode *EnableDenorm;
8172     if (Subtarget->hasDenormModeInst()) {
8173       const SDValue EnableDenormValue =
8174           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8175 
8176       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8177                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8178     } else {
8179       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8180                                                         SL, MVT::i32);
8181       EnableDenorm =
8182           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8183                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8184     }
8185 
8186     SDValue Ops[3] = {
8187       NegDivScale0,
8188       SDValue(EnableDenorm, 0),
8189       SDValue(EnableDenorm, 1)
8190     };
8191 
8192     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8193   }
8194 
8195   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8196                              ApproxRcp, One, NegDivScale0, Flags);
8197 
8198   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8199                              ApproxRcp, Fma0, Flags);
8200 
8201   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8202                            Fma1, Fma1, Flags);
8203 
8204   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8205                              NumeratorScaled, Mul, Flags);
8206 
8207   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8208                              Fma2, Fma1, Mul, Fma2, Flags);
8209 
8210   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8211                              NumeratorScaled, Fma3, Flags);
8212 
8213   if (!HasFP32Denormals) {
8214     SDNode *DisableDenorm;
8215     if (Subtarget->hasDenormModeInst()) {
8216       const SDValue DisableDenormValue =
8217           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8218 
8219       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8220                                   Fma4.getValue(1), DisableDenormValue,
8221                                   Fma4.getValue(2)).getNode();
8222     } else {
8223       const SDValue DisableDenormValue =
8224           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8225 
8226       DisableDenorm = DAG.getMachineNode(
8227           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8228           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8229     }
8230 
8231     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8232                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8233     DAG.setRoot(OutputChain);
8234   }
8235 
8236   SDValue Scale = NumeratorScaled.getValue(1);
8237   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8238                              {Fma4, Fma1, Fma3, Scale}, Flags);
8239 
8240   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8241 }
8242 
8243 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8244   if (DAG.getTarget().Options.UnsafeFPMath)
8245     return lowerFastUnsafeFDIV(Op, DAG);
8246 
8247   SDLoc SL(Op);
8248   SDValue X = Op.getOperand(0);
8249   SDValue Y = Op.getOperand(1);
8250 
8251   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8252 
8253   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8254 
8255   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8256 
8257   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8258 
8259   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8260 
8261   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8262 
8263   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8264 
8265   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8266 
8267   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8268 
8269   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8270   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8271 
8272   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8273                              NegDivScale0, Mul, DivScale1);
8274 
8275   SDValue Scale;
8276 
8277   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8278     // Workaround a hardware bug on SI where the condition output from div_scale
8279     // is not usable.
8280 
8281     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8282 
8283     // Figure out if the scale to use for div_fmas.
8284     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8285     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8286     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8287     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8288 
8289     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8290     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8291 
8292     SDValue Scale0Hi
8293       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8294     SDValue Scale1Hi
8295       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8296 
8297     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8298     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8299     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8300   } else {
8301     Scale = DivScale1.getValue(1);
8302   }
8303 
8304   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8305                              Fma4, Fma3, Mul, Scale);
8306 
8307   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8308 }
8309 
8310 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8311   EVT VT = Op.getValueType();
8312 
8313   if (VT == MVT::f32)
8314     return LowerFDIV32(Op, DAG);
8315 
8316   if (VT == MVT::f64)
8317     return LowerFDIV64(Op, DAG);
8318 
8319   if (VT == MVT::f16)
8320     return LowerFDIV16(Op, DAG);
8321 
8322   llvm_unreachable("Unexpected type for fdiv");
8323 }
8324 
8325 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8326   SDLoc DL(Op);
8327   StoreSDNode *Store = cast<StoreSDNode>(Op);
8328   EVT VT = Store->getMemoryVT();
8329 
8330   if (VT == MVT::i1) {
8331     return DAG.getTruncStore(Store->getChain(), DL,
8332        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8333        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8334   }
8335 
8336   assert(VT.isVector() &&
8337          Store->getValue().getValueType().getScalarType() == MVT::i32);
8338 
8339   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8340                                       VT, *Store->getMemOperand())) {
8341     return expandUnalignedStore(Store, DAG);
8342   }
8343 
8344   unsigned AS = Store->getAddressSpace();
8345   if (Subtarget->hasLDSMisalignedBug() &&
8346       AS == AMDGPUAS::FLAT_ADDRESS &&
8347       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8348     return SplitVectorStore(Op, DAG);
8349   }
8350 
8351   MachineFunction &MF = DAG.getMachineFunction();
8352   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8353   // If there is a possibilty that flat instruction access scratch memory
8354   // then we need to use the same legalization rules we use for private.
8355   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8356       !Subtarget->hasMultiDwordFlatScratchAddressing())
8357     AS = MFI->hasFlatScratchInit() ?
8358          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8359 
8360   unsigned NumElements = VT.getVectorNumElements();
8361   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8362       AS == AMDGPUAS::FLAT_ADDRESS) {
8363     if (NumElements > 4)
8364       return SplitVectorStore(Op, DAG);
8365     // v3 stores not supported on SI.
8366     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8367       return SplitVectorStore(Op, DAG);
8368     return SDValue();
8369   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8370     switch (Subtarget->getMaxPrivateElementSize()) {
8371     case 4:
8372       return scalarizeVectorStore(Store, DAG);
8373     case 8:
8374       if (NumElements > 2)
8375         return SplitVectorStore(Op, DAG);
8376       return SDValue();
8377     case 16:
8378       if (NumElements > 4 || NumElements == 3)
8379         return SplitVectorStore(Op, DAG);
8380       return SDValue();
8381     default:
8382       llvm_unreachable("unsupported private_element_size");
8383     }
8384   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8385     // Use ds_write_b128 if possible.
8386     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8387         VT.getStoreSize() == 16 && NumElements != 3)
8388       return SDValue();
8389 
8390     if (NumElements > 2)
8391       return SplitVectorStore(Op, DAG);
8392 
8393     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8394     // address is negative, then the instruction is incorrectly treated as
8395     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8396     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8397     // store later in the SILoadStoreOptimizer.
8398     if (!Subtarget->hasUsableDSOffset() &&
8399         NumElements == 2 && VT.getStoreSize() == 8 &&
8400         Store->getAlignment() < 8) {
8401       return SplitVectorStore(Op, DAG);
8402     }
8403 
8404     return SDValue();
8405   } else {
8406     llvm_unreachable("unhandled address space");
8407   }
8408 }
8409 
8410 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8411   SDLoc DL(Op);
8412   EVT VT = Op.getValueType();
8413   SDValue Arg = Op.getOperand(0);
8414   SDValue TrigVal;
8415 
8416   // Propagate fast-math flags so that the multiply we introduce can be folded
8417   // if Arg is already the result of a multiply by constant.
8418   auto Flags = Op->getFlags();
8419 
8420   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8421 
8422   if (Subtarget->hasTrigReducedRange()) {
8423     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8424     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8425   } else {
8426     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8427   }
8428 
8429   switch (Op.getOpcode()) {
8430   case ISD::FCOS:
8431     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8432   case ISD::FSIN:
8433     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8434   default:
8435     llvm_unreachable("Wrong trig opcode");
8436   }
8437 }
8438 
8439 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8440   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8441   assert(AtomicNode->isCompareAndSwap());
8442   unsigned AS = AtomicNode->getAddressSpace();
8443 
8444   // No custom lowering required for local address space
8445   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8446     return Op;
8447 
8448   // Non-local address space requires custom lowering for atomic compare
8449   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8450   SDLoc DL(Op);
8451   SDValue ChainIn = Op.getOperand(0);
8452   SDValue Addr = Op.getOperand(1);
8453   SDValue Old = Op.getOperand(2);
8454   SDValue New = Op.getOperand(3);
8455   EVT VT = Op.getValueType();
8456   MVT SimpleVT = VT.getSimpleVT();
8457   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8458 
8459   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8460   SDValue Ops[] = { ChainIn, Addr, NewOld };
8461 
8462   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8463                                  Ops, VT, AtomicNode->getMemOperand());
8464 }
8465 
8466 //===----------------------------------------------------------------------===//
8467 // Custom DAG optimizations
8468 //===----------------------------------------------------------------------===//
8469 
8470 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8471                                                      DAGCombinerInfo &DCI) const {
8472   EVT VT = N->getValueType(0);
8473   EVT ScalarVT = VT.getScalarType();
8474   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8475     return SDValue();
8476 
8477   SelectionDAG &DAG = DCI.DAG;
8478   SDLoc DL(N);
8479 
8480   SDValue Src = N->getOperand(0);
8481   EVT SrcVT = Src.getValueType();
8482 
8483   // TODO: We could try to match extracting the higher bytes, which would be
8484   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8485   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8486   // about in practice.
8487   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8488     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8489       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8490       DCI.AddToWorklist(Cvt.getNode());
8491 
8492       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8493       if (ScalarVT != MVT::f32) {
8494         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8495                           DAG.getTargetConstant(0, DL, MVT::i32));
8496       }
8497       return Cvt;
8498     }
8499   }
8500 
8501   return SDValue();
8502 }
8503 
8504 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8505 
8506 // This is a variant of
8507 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8508 //
8509 // The normal DAG combiner will do this, but only if the add has one use since
8510 // that would increase the number of instructions.
8511 //
8512 // This prevents us from seeing a constant offset that can be folded into a
8513 // memory instruction's addressing mode. If we know the resulting add offset of
8514 // a pointer can be folded into an addressing offset, we can replace the pointer
8515 // operand with the add of new constant offset. This eliminates one of the uses,
8516 // and may allow the remaining use to also be simplified.
8517 //
8518 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8519                                                unsigned AddrSpace,
8520                                                EVT MemVT,
8521                                                DAGCombinerInfo &DCI) const {
8522   SDValue N0 = N->getOperand(0);
8523   SDValue N1 = N->getOperand(1);
8524 
8525   // We only do this to handle cases where it's profitable when there are
8526   // multiple uses of the add, so defer to the standard combine.
8527   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8528       N0->hasOneUse())
8529     return SDValue();
8530 
8531   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8532   if (!CN1)
8533     return SDValue();
8534 
8535   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8536   if (!CAdd)
8537     return SDValue();
8538 
8539   // If the resulting offset is too large, we can't fold it into the addressing
8540   // mode offset.
8541   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8542   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8543 
8544   AddrMode AM;
8545   AM.HasBaseReg = true;
8546   AM.BaseOffs = Offset.getSExtValue();
8547   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8548     return SDValue();
8549 
8550   SelectionDAG &DAG = DCI.DAG;
8551   SDLoc SL(N);
8552   EVT VT = N->getValueType(0);
8553 
8554   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8555   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8556 
8557   SDNodeFlags Flags;
8558   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8559                           (N0.getOpcode() == ISD::OR ||
8560                            N0->getFlags().hasNoUnsignedWrap()));
8561 
8562   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8563 }
8564 
8565 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8566                                                   DAGCombinerInfo &DCI) const {
8567   // FIXME: getBasePtr does not work correctly for intrinsic nodes and will find
8568   // the intrinsic ID, not the pointer.
8569   SDValue Ptr = N->getBasePtr();
8570   SelectionDAG &DAG = DCI.DAG;
8571   SDLoc SL(N);
8572 
8573   // TODO: We could also do this for multiplies.
8574   if (Ptr.getOpcode() == ISD::SHL) {
8575     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8576                                           N->getMemoryVT(), DCI);
8577     if (NewPtr) {
8578       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8579 
8580       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8581       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8582     }
8583   }
8584 
8585   return SDValue();
8586 }
8587 
8588 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8589   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8590          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8591          (Opc == ISD::XOR && Val == 0);
8592 }
8593 
8594 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8595 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8596 // integer combine opportunities since most 64-bit operations are decomposed
8597 // this way.  TODO: We won't want this for SALU especially if it is an inline
8598 // immediate.
8599 SDValue SITargetLowering::splitBinaryBitConstantOp(
8600   DAGCombinerInfo &DCI,
8601   const SDLoc &SL,
8602   unsigned Opc, SDValue LHS,
8603   const ConstantSDNode *CRHS) const {
8604   uint64_t Val = CRHS->getZExtValue();
8605   uint32_t ValLo = Lo_32(Val);
8606   uint32_t ValHi = Hi_32(Val);
8607   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8608 
8609     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8610          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8611         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8612     // If we need to materialize a 64-bit immediate, it will be split up later
8613     // anyway. Avoid creating the harder to understand 64-bit immediate
8614     // materialization.
8615     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8616   }
8617 
8618   return SDValue();
8619 }
8620 
8621 // Returns true if argument is a boolean value which is not serialized into
8622 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8623 static bool isBoolSGPR(SDValue V) {
8624   if (V.getValueType() != MVT::i1)
8625     return false;
8626   switch (V.getOpcode()) {
8627   default: break;
8628   case ISD::SETCC:
8629   case ISD::AND:
8630   case ISD::OR:
8631   case ISD::XOR:
8632   case AMDGPUISD::FP_CLASS:
8633     return true;
8634   }
8635   return false;
8636 }
8637 
8638 // If a constant has all zeroes or all ones within each byte return it.
8639 // Otherwise return 0.
8640 static uint32_t getConstantPermuteMask(uint32_t C) {
8641   // 0xff for any zero byte in the mask
8642   uint32_t ZeroByteMask = 0;
8643   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8644   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8645   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8646   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8647   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8648   if ((NonZeroByteMask & C) != NonZeroByteMask)
8649     return 0; // Partial bytes selected.
8650   return C;
8651 }
8652 
8653 // Check if a node selects whole bytes from its operand 0 starting at a byte
8654 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8655 // or -1 if not succeeded.
8656 // Note byte select encoding:
8657 // value 0-3 selects corresponding source byte;
8658 // value 0xc selects zero;
8659 // value 0xff selects 0xff.
8660 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8661   assert(V.getValueSizeInBits() == 32);
8662 
8663   if (V.getNumOperands() != 2)
8664     return ~0;
8665 
8666   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8667   if (!N1)
8668     return ~0;
8669 
8670   uint32_t C = N1->getZExtValue();
8671 
8672   switch (V.getOpcode()) {
8673   default:
8674     break;
8675   case ISD::AND:
8676     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8677       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8678     }
8679     break;
8680 
8681   case ISD::OR:
8682     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8683       return (0x03020100 & ~ConstMask) | ConstMask;
8684     }
8685     break;
8686 
8687   case ISD::SHL:
8688     if (C % 8)
8689       return ~0;
8690 
8691     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8692 
8693   case ISD::SRL:
8694     if (C % 8)
8695       return ~0;
8696 
8697     return uint32_t(0x0c0c0c0c03020100ull >> C);
8698   }
8699 
8700   return ~0;
8701 }
8702 
8703 SDValue SITargetLowering::performAndCombine(SDNode *N,
8704                                             DAGCombinerInfo &DCI) const {
8705   if (DCI.isBeforeLegalize())
8706     return SDValue();
8707 
8708   SelectionDAG &DAG = DCI.DAG;
8709   EVT VT = N->getValueType(0);
8710   SDValue LHS = N->getOperand(0);
8711   SDValue RHS = N->getOperand(1);
8712 
8713 
8714   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8715   if (VT == MVT::i64 && CRHS) {
8716     if (SDValue Split
8717         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8718       return Split;
8719   }
8720 
8721   if (CRHS && VT == MVT::i32) {
8722     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8723     // nb = number of trailing zeroes in mask
8724     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8725     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8726     uint64_t Mask = CRHS->getZExtValue();
8727     unsigned Bits = countPopulation(Mask);
8728     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8729         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8730       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8731         unsigned Shift = CShift->getZExtValue();
8732         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8733         unsigned Offset = NB + Shift;
8734         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8735           SDLoc SL(N);
8736           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8737                                     LHS->getOperand(0),
8738                                     DAG.getConstant(Offset, SL, MVT::i32),
8739                                     DAG.getConstant(Bits, SL, MVT::i32));
8740           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8741           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8742                                     DAG.getValueType(NarrowVT));
8743           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8744                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8745           return Shl;
8746         }
8747       }
8748     }
8749 
8750     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8751     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8752         isa<ConstantSDNode>(LHS.getOperand(2))) {
8753       uint32_t Sel = getConstantPermuteMask(Mask);
8754       if (!Sel)
8755         return SDValue();
8756 
8757       // Select 0xc for all zero bytes
8758       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8759       SDLoc DL(N);
8760       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8761                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8762     }
8763   }
8764 
8765   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8766   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8767   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8768     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8769     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8770 
8771     SDValue X = LHS.getOperand(0);
8772     SDValue Y = RHS.getOperand(0);
8773     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8774       return SDValue();
8775 
8776     if (LCC == ISD::SETO) {
8777       if (X != LHS.getOperand(1))
8778         return SDValue();
8779 
8780       if (RCC == ISD::SETUNE) {
8781         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8782         if (!C1 || !C1->isInfinity() || C1->isNegative())
8783           return SDValue();
8784 
8785         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8786                               SIInstrFlags::N_SUBNORMAL |
8787                               SIInstrFlags::N_ZERO |
8788                               SIInstrFlags::P_ZERO |
8789                               SIInstrFlags::P_SUBNORMAL |
8790                               SIInstrFlags::P_NORMAL;
8791 
8792         static_assert(((~(SIInstrFlags::S_NAN |
8793                           SIInstrFlags::Q_NAN |
8794                           SIInstrFlags::N_INFINITY |
8795                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8796                       "mask not equal");
8797 
8798         SDLoc DL(N);
8799         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8800                            X, DAG.getConstant(Mask, DL, MVT::i32));
8801       }
8802     }
8803   }
8804 
8805   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8806     std::swap(LHS, RHS);
8807 
8808   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8809       RHS.hasOneUse()) {
8810     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8811     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8812     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8813     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8814     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8815         (RHS.getOperand(0) == LHS.getOperand(0) &&
8816          LHS.getOperand(0) == LHS.getOperand(1))) {
8817       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8818       unsigned NewMask = LCC == ISD::SETO ?
8819         Mask->getZExtValue() & ~OrdMask :
8820         Mask->getZExtValue() & OrdMask;
8821 
8822       SDLoc DL(N);
8823       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8824                          DAG.getConstant(NewMask, DL, MVT::i32));
8825     }
8826   }
8827 
8828   if (VT == MVT::i32 &&
8829       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8830     // and x, (sext cc from i1) => select cc, x, 0
8831     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8832       std::swap(LHS, RHS);
8833     if (isBoolSGPR(RHS.getOperand(0)))
8834       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8835                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8836   }
8837 
8838   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8839   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8840   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8841       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8842     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8843     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8844     if (LHSMask != ~0u && RHSMask != ~0u) {
8845       // Canonicalize the expression in an attempt to have fewer unique masks
8846       // and therefore fewer registers used to hold the masks.
8847       if (LHSMask > RHSMask) {
8848         std::swap(LHSMask, RHSMask);
8849         std::swap(LHS, RHS);
8850       }
8851 
8852       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8853       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8854       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8855       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8856 
8857       // Check of we need to combine values from two sources within a byte.
8858       if (!(LHSUsedLanes & RHSUsedLanes) &&
8859           // If we select high and lower word keep it for SDWA.
8860           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8861           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8862         // Each byte in each mask is either selector mask 0-3, or has higher
8863         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8864         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8865         // mask which is not 0xff wins. By anding both masks we have a correct
8866         // result except that 0x0c shall be corrected to give 0x0c only.
8867         uint32_t Mask = LHSMask & RHSMask;
8868         for (unsigned I = 0; I < 32; I += 8) {
8869           uint32_t ByteSel = 0xff << I;
8870           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8871             Mask &= (0x0c << I) & 0xffffffff;
8872         }
8873 
8874         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8875         // or 0x0c.
8876         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8877         SDLoc DL(N);
8878 
8879         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8880                            LHS.getOperand(0), RHS.getOperand(0),
8881                            DAG.getConstant(Sel, DL, MVT::i32));
8882       }
8883     }
8884   }
8885 
8886   return SDValue();
8887 }
8888 
8889 SDValue SITargetLowering::performOrCombine(SDNode *N,
8890                                            DAGCombinerInfo &DCI) const {
8891   SelectionDAG &DAG = DCI.DAG;
8892   SDValue LHS = N->getOperand(0);
8893   SDValue RHS = N->getOperand(1);
8894 
8895   EVT VT = N->getValueType(0);
8896   if (VT == MVT::i1) {
8897     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8898     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8899         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8900       SDValue Src = LHS.getOperand(0);
8901       if (Src != RHS.getOperand(0))
8902         return SDValue();
8903 
8904       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8905       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8906       if (!CLHS || !CRHS)
8907         return SDValue();
8908 
8909       // Only 10 bits are used.
8910       static const uint32_t MaxMask = 0x3ff;
8911 
8912       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8913       SDLoc DL(N);
8914       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8915                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8916     }
8917 
8918     return SDValue();
8919   }
8920 
8921   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8922   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8923       LHS.getOpcode() == AMDGPUISD::PERM &&
8924       isa<ConstantSDNode>(LHS.getOperand(2))) {
8925     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8926     if (!Sel)
8927       return SDValue();
8928 
8929     Sel |= LHS.getConstantOperandVal(2);
8930     SDLoc DL(N);
8931     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8932                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8933   }
8934 
8935   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8936   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8937   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8938       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8939     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8940     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8941     if (LHSMask != ~0u && RHSMask != ~0u) {
8942       // Canonicalize the expression in an attempt to have fewer unique masks
8943       // and therefore fewer registers used to hold the masks.
8944       if (LHSMask > RHSMask) {
8945         std::swap(LHSMask, RHSMask);
8946         std::swap(LHS, RHS);
8947       }
8948 
8949       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8950       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8951       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8952       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8953 
8954       // Check of we need to combine values from two sources within a byte.
8955       if (!(LHSUsedLanes & RHSUsedLanes) &&
8956           // If we select high and lower word keep it for SDWA.
8957           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8958           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8959         // Kill zero bytes selected by other mask. Zero value is 0xc.
8960         LHSMask &= ~RHSUsedLanes;
8961         RHSMask &= ~LHSUsedLanes;
8962         // Add 4 to each active LHS lane
8963         LHSMask |= LHSUsedLanes & 0x04040404;
8964         // Combine masks
8965         uint32_t Sel = LHSMask | RHSMask;
8966         SDLoc DL(N);
8967 
8968         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8969                            LHS.getOperand(0), RHS.getOperand(0),
8970                            DAG.getConstant(Sel, DL, MVT::i32));
8971       }
8972     }
8973   }
8974 
8975   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
8976     return SDValue();
8977 
8978   // TODO: This could be a generic combine with a predicate for extracting the
8979   // high half of an integer being free.
8980 
8981   // (or i64:x, (zero_extend i32:y)) ->
8982   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8983   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8984       RHS.getOpcode() != ISD::ZERO_EXTEND)
8985     std::swap(LHS, RHS);
8986 
8987   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8988     SDValue ExtSrc = RHS.getOperand(0);
8989     EVT SrcVT = ExtSrc.getValueType();
8990     if (SrcVT == MVT::i32) {
8991       SDLoc SL(N);
8992       SDValue LowLHS, HiBits;
8993       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8994       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8995 
8996       DCI.AddToWorklist(LowOr.getNode());
8997       DCI.AddToWorklist(HiBits.getNode());
8998 
8999       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9000                                 LowOr, HiBits);
9001       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9002     }
9003   }
9004 
9005   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9006   if (CRHS) {
9007     if (SDValue Split
9008           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9009       return Split;
9010   }
9011 
9012   return SDValue();
9013 }
9014 
9015 SDValue SITargetLowering::performXorCombine(SDNode *N,
9016                                             DAGCombinerInfo &DCI) const {
9017   EVT VT = N->getValueType(0);
9018   if (VT != MVT::i64)
9019     return SDValue();
9020 
9021   SDValue LHS = N->getOperand(0);
9022   SDValue RHS = N->getOperand(1);
9023 
9024   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9025   if (CRHS) {
9026     if (SDValue Split
9027           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9028       return Split;
9029   }
9030 
9031   return SDValue();
9032 }
9033 
9034 // Instructions that will be lowered with a final instruction that zeros the
9035 // high result bits.
9036 // XXX - probably only need to list legal operations.
9037 static bool fp16SrcZerosHighBits(unsigned Opc) {
9038   switch (Opc) {
9039   case ISD::FADD:
9040   case ISD::FSUB:
9041   case ISD::FMUL:
9042   case ISD::FDIV:
9043   case ISD::FREM:
9044   case ISD::FMA:
9045   case ISD::FMAD:
9046   case ISD::FCANONICALIZE:
9047   case ISD::FP_ROUND:
9048   case ISD::UINT_TO_FP:
9049   case ISD::SINT_TO_FP:
9050   case ISD::FABS:
9051     // Fabs is lowered to a bit operation, but it's an and which will clear the
9052     // high bits anyway.
9053   case ISD::FSQRT:
9054   case ISD::FSIN:
9055   case ISD::FCOS:
9056   case ISD::FPOWI:
9057   case ISD::FPOW:
9058   case ISD::FLOG:
9059   case ISD::FLOG2:
9060   case ISD::FLOG10:
9061   case ISD::FEXP:
9062   case ISD::FEXP2:
9063   case ISD::FCEIL:
9064   case ISD::FTRUNC:
9065   case ISD::FRINT:
9066   case ISD::FNEARBYINT:
9067   case ISD::FROUND:
9068   case ISD::FFLOOR:
9069   case ISD::FMINNUM:
9070   case ISD::FMAXNUM:
9071   case AMDGPUISD::FRACT:
9072   case AMDGPUISD::CLAMP:
9073   case AMDGPUISD::COS_HW:
9074   case AMDGPUISD::SIN_HW:
9075   case AMDGPUISD::FMIN3:
9076   case AMDGPUISD::FMAX3:
9077   case AMDGPUISD::FMED3:
9078   case AMDGPUISD::FMAD_FTZ:
9079   case AMDGPUISD::RCP:
9080   case AMDGPUISD::RSQ:
9081   case AMDGPUISD::RCP_IFLAG:
9082   case AMDGPUISD::LDEXP:
9083     return true;
9084   default:
9085     // fcopysign, select and others may be lowered to 32-bit bit operations
9086     // which don't zero the high bits.
9087     return false;
9088   }
9089 }
9090 
9091 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9092                                                    DAGCombinerInfo &DCI) const {
9093   if (!Subtarget->has16BitInsts() ||
9094       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9095     return SDValue();
9096 
9097   EVT VT = N->getValueType(0);
9098   if (VT != MVT::i32)
9099     return SDValue();
9100 
9101   SDValue Src = N->getOperand(0);
9102   if (Src.getValueType() != MVT::i16)
9103     return SDValue();
9104 
9105   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9106   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9107   if (Src.getOpcode() == ISD::BITCAST) {
9108     SDValue BCSrc = Src.getOperand(0);
9109     if (BCSrc.getValueType() == MVT::f16 &&
9110         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9111       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9112   }
9113 
9114   return SDValue();
9115 }
9116 
9117 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9118                                                         DAGCombinerInfo &DCI)
9119                                                         const {
9120   SDValue Src = N->getOperand(0);
9121   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9122 
9123   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9124       VTSign->getVT() == MVT::i8) ||
9125       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9126       VTSign->getVT() == MVT::i16)) &&
9127       Src.hasOneUse()) {
9128     auto *M = cast<MemSDNode>(Src);
9129     SDValue Ops[] = {
9130       Src.getOperand(0), // Chain
9131       Src.getOperand(1), // rsrc
9132       Src.getOperand(2), // vindex
9133       Src.getOperand(3), // voffset
9134       Src.getOperand(4), // soffset
9135       Src.getOperand(5), // offset
9136       Src.getOperand(6),
9137       Src.getOperand(7)
9138     };
9139     // replace with BUFFER_LOAD_BYTE/SHORT
9140     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9141                                          Src.getOperand(0).getValueType());
9142     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9143                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9144     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9145                                                           ResList,
9146                                                           Ops, M->getMemoryVT(),
9147                                                           M->getMemOperand());
9148     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9149                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9150   }
9151   return SDValue();
9152 }
9153 
9154 SDValue SITargetLowering::performClassCombine(SDNode *N,
9155                                               DAGCombinerInfo &DCI) const {
9156   SelectionDAG &DAG = DCI.DAG;
9157   SDValue Mask = N->getOperand(1);
9158 
9159   // fp_class x, 0 -> false
9160   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9161     if (CMask->isNullValue())
9162       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9163   }
9164 
9165   if (N->getOperand(0).isUndef())
9166     return DAG.getUNDEF(MVT::i1);
9167 
9168   return SDValue();
9169 }
9170 
9171 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9172                                             DAGCombinerInfo &DCI) const {
9173   EVT VT = N->getValueType(0);
9174   SDValue N0 = N->getOperand(0);
9175 
9176   if (N0.isUndef())
9177     return N0;
9178 
9179   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9180                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9181     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9182                            N->getFlags());
9183   }
9184 
9185   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9186     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9187                            N0.getOperand(0), N->getFlags());
9188   }
9189 
9190   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9191 }
9192 
9193 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9194                                        unsigned MaxDepth) const {
9195   unsigned Opcode = Op.getOpcode();
9196   if (Opcode == ISD::FCANONICALIZE)
9197     return true;
9198 
9199   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9200     auto F = CFP->getValueAPF();
9201     if (F.isNaN() && F.isSignaling())
9202       return false;
9203     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9204   }
9205 
9206   // If source is a result of another standard FP operation it is already in
9207   // canonical form.
9208   if (MaxDepth == 0)
9209     return false;
9210 
9211   switch (Opcode) {
9212   // These will flush denorms if required.
9213   case ISD::FADD:
9214   case ISD::FSUB:
9215   case ISD::FMUL:
9216   case ISD::FCEIL:
9217   case ISD::FFLOOR:
9218   case ISD::FMA:
9219   case ISD::FMAD:
9220   case ISD::FSQRT:
9221   case ISD::FDIV:
9222   case ISD::FREM:
9223   case ISD::FP_ROUND:
9224   case ISD::FP_EXTEND:
9225   case AMDGPUISD::FMUL_LEGACY:
9226   case AMDGPUISD::FMAD_FTZ:
9227   case AMDGPUISD::RCP:
9228   case AMDGPUISD::RSQ:
9229   case AMDGPUISD::RSQ_CLAMP:
9230   case AMDGPUISD::RCP_LEGACY:
9231   case AMDGPUISD::RCP_IFLAG:
9232   case AMDGPUISD::DIV_SCALE:
9233   case AMDGPUISD::DIV_FMAS:
9234   case AMDGPUISD::DIV_FIXUP:
9235   case AMDGPUISD::FRACT:
9236   case AMDGPUISD::LDEXP:
9237   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9238   case AMDGPUISD::CVT_F32_UBYTE0:
9239   case AMDGPUISD::CVT_F32_UBYTE1:
9240   case AMDGPUISD::CVT_F32_UBYTE2:
9241   case AMDGPUISD::CVT_F32_UBYTE3:
9242     return true;
9243 
9244   // It can/will be lowered or combined as a bit operation.
9245   // Need to check their input recursively to handle.
9246   case ISD::FNEG:
9247   case ISD::FABS:
9248   case ISD::FCOPYSIGN:
9249     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9250 
9251   case ISD::FSIN:
9252   case ISD::FCOS:
9253   case ISD::FSINCOS:
9254     return Op.getValueType().getScalarType() != MVT::f16;
9255 
9256   case ISD::FMINNUM:
9257   case ISD::FMAXNUM:
9258   case ISD::FMINNUM_IEEE:
9259   case ISD::FMAXNUM_IEEE:
9260   case AMDGPUISD::CLAMP:
9261   case AMDGPUISD::FMED3:
9262   case AMDGPUISD::FMAX3:
9263   case AMDGPUISD::FMIN3: {
9264     // FIXME: Shouldn't treat the generic operations different based these.
9265     // However, we aren't really required to flush the result from
9266     // minnum/maxnum..
9267 
9268     // snans will be quieted, so we only need to worry about denormals.
9269     if (Subtarget->supportsMinMaxDenormModes() ||
9270         denormalsEnabledForType(DAG, Op.getValueType()))
9271       return true;
9272 
9273     // Flushing may be required.
9274     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9275     // targets need to check their input recursively.
9276 
9277     // FIXME: Does this apply with clamp? It's implemented with max.
9278     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9279       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9280         return false;
9281     }
9282 
9283     return true;
9284   }
9285   case ISD::SELECT: {
9286     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9287            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9288   }
9289   case ISD::BUILD_VECTOR: {
9290     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9291       SDValue SrcOp = Op.getOperand(i);
9292       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9293         return false;
9294     }
9295 
9296     return true;
9297   }
9298   case ISD::EXTRACT_VECTOR_ELT:
9299   case ISD::EXTRACT_SUBVECTOR: {
9300     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9301   }
9302   case ISD::INSERT_VECTOR_ELT: {
9303     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9304            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9305   }
9306   case ISD::UNDEF:
9307     // Could be anything.
9308     return false;
9309 
9310   case ISD::BITCAST: {
9311     // Hack round the mess we make when legalizing extract_vector_elt
9312     SDValue Src = Op.getOperand(0);
9313     if (Src.getValueType() == MVT::i16 &&
9314         Src.getOpcode() == ISD::TRUNCATE) {
9315       SDValue TruncSrc = Src.getOperand(0);
9316       if (TruncSrc.getValueType() == MVT::i32 &&
9317           TruncSrc.getOpcode() == ISD::BITCAST &&
9318           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9319         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9320       }
9321     }
9322 
9323     return false;
9324   }
9325   case ISD::INTRINSIC_WO_CHAIN: {
9326     unsigned IntrinsicID
9327       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9328     // TODO: Handle more intrinsics
9329     switch (IntrinsicID) {
9330     case Intrinsic::amdgcn_cvt_pkrtz:
9331     case Intrinsic::amdgcn_cubeid:
9332     case Intrinsic::amdgcn_frexp_mant:
9333     case Intrinsic::amdgcn_fdot2:
9334     case Intrinsic::amdgcn_rcp:
9335     case Intrinsic::amdgcn_rsq:
9336     case Intrinsic::amdgcn_rsq_clamp:
9337     case Intrinsic::amdgcn_rcp_legacy:
9338     case Intrinsic::amdgcn_rsq_legacy:
9339     case Intrinsic::amdgcn_trig_preop:
9340       return true;
9341     default:
9342       break;
9343     }
9344 
9345     LLVM_FALLTHROUGH;
9346   }
9347   default:
9348     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9349            DAG.isKnownNeverSNaN(Op);
9350   }
9351 
9352   llvm_unreachable("invalid operation");
9353 }
9354 
9355 // Constant fold canonicalize.
9356 SDValue SITargetLowering::getCanonicalConstantFP(
9357   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9358   // Flush denormals to 0 if not enabled.
9359   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9360     return DAG.getConstantFP(0.0, SL, VT);
9361 
9362   if (C.isNaN()) {
9363     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9364     if (C.isSignaling()) {
9365       // Quiet a signaling NaN.
9366       // FIXME: Is this supposed to preserve payload bits?
9367       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9368     }
9369 
9370     // Make sure it is the canonical NaN bitpattern.
9371     //
9372     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9373     // immediate?
9374     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9375       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9376   }
9377 
9378   // Already canonical.
9379   return DAG.getConstantFP(C, SL, VT);
9380 }
9381 
9382 static bool vectorEltWillFoldAway(SDValue Op) {
9383   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9384 }
9385 
9386 SDValue SITargetLowering::performFCanonicalizeCombine(
9387   SDNode *N,
9388   DAGCombinerInfo &DCI) const {
9389   SelectionDAG &DAG = DCI.DAG;
9390   SDValue N0 = N->getOperand(0);
9391   EVT VT = N->getValueType(0);
9392 
9393   // fcanonicalize undef -> qnan
9394   if (N0.isUndef()) {
9395     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9396     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9397   }
9398 
9399   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9400     EVT VT = N->getValueType(0);
9401     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9402   }
9403 
9404   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9405   //                                                   (fcanonicalize k)
9406   //
9407   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9408 
9409   // TODO: This could be better with wider vectors that will be split to v2f16,
9410   // and to consider uses since there aren't that many packed operations.
9411   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9412       isTypeLegal(MVT::v2f16)) {
9413     SDLoc SL(N);
9414     SDValue NewElts[2];
9415     SDValue Lo = N0.getOperand(0);
9416     SDValue Hi = N0.getOperand(1);
9417     EVT EltVT = Lo.getValueType();
9418 
9419     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9420       for (unsigned I = 0; I != 2; ++I) {
9421         SDValue Op = N0.getOperand(I);
9422         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9423           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9424                                               CFP->getValueAPF());
9425         } else if (Op.isUndef()) {
9426           // Handled below based on what the other operand is.
9427           NewElts[I] = Op;
9428         } else {
9429           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9430         }
9431       }
9432 
9433       // If one half is undef, and one is constant, perfer a splat vector rather
9434       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9435       // cheaper to use and may be free with a packed operation.
9436       if (NewElts[0].isUndef()) {
9437         if (isa<ConstantFPSDNode>(NewElts[1]))
9438           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9439             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9440       }
9441 
9442       if (NewElts[1].isUndef()) {
9443         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9444           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9445       }
9446 
9447       return DAG.getBuildVector(VT, SL, NewElts);
9448     }
9449   }
9450 
9451   unsigned SrcOpc = N0.getOpcode();
9452 
9453   // If it's free to do so, push canonicalizes further up the source, which may
9454   // find a canonical source.
9455   //
9456   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9457   // sNaNs.
9458   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9459     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9460     if (CRHS && N0.hasOneUse()) {
9461       SDLoc SL(N);
9462       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9463                                    N0.getOperand(0));
9464       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9465       DCI.AddToWorklist(Canon0.getNode());
9466 
9467       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9468     }
9469   }
9470 
9471   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9472 }
9473 
9474 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9475   switch (Opc) {
9476   case ISD::FMAXNUM:
9477   case ISD::FMAXNUM_IEEE:
9478     return AMDGPUISD::FMAX3;
9479   case ISD::SMAX:
9480     return AMDGPUISD::SMAX3;
9481   case ISD::UMAX:
9482     return AMDGPUISD::UMAX3;
9483   case ISD::FMINNUM:
9484   case ISD::FMINNUM_IEEE:
9485     return AMDGPUISD::FMIN3;
9486   case ISD::SMIN:
9487     return AMDGPUISD::SMIN3;
9488   case ISD::UMIN:
9489     return AMDGPUISD::UMIN3;
9490   default:
9491     llvm_unreachable("Not a min/max opcode");
9492   }
9493 }
9494 
9495 SDValue SITargetLowering::performIntMed3ImmCombine(
9496   SelectionDAG &DAG, const SDLoc &SL,
9497   SDValue Op0, SDValue Op1, bool Signed) const {
9498   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9499   if (!K1)
9500     return SDValue();
9501 
9502   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9503   if (!K0)
9504     return SDValue();
9505 
9506   if (Signed) {
9507     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9508       return SDValue();
9509   } else {
9510     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9511       return SDValue();
9512   }
9513 
9514   EVT VT = K0->getValueType(0);
9515   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9516   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9517     return DAG.getNode(Med3Opc, SL, VT,
9518                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9519   }
9520 
9521   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9522   MVT NVT = MVT::i32;
9523   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9524 
9525   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9526   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9527   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9528 
9529   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9530   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9531 }
9532 
9533 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9534   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9535     return C;
9536 
9537   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9538     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9539       return C;
9540   }
9541 
9542   return nullptr;
9543 }
9544 
9545 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9546                                                   const SDLoc &SL,
9547                                                   SDValue Op0,
9548                                                   SDValue Op1) const {
9549   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9550   if (!K1)
9551     return SDValue();
9552 
9553   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9554   if (!K0)
9555     return SDValue();
9556 
9557   // Ordered >= (although NaN inputs should have folded away by now).
9558   if (K0->getValueAPF() > K1->getValueAPF())
9559     return SDValue();
9560 
9561   const MachineFunction &MF = DAG.getMachineFunction();
9562   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9563 
9564   // TODO: Check IEEE bit enabled?
9565   EVT VT = Op0.getValueType();
9566   if (Info->getMode().DX10Clamp) {
9567     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9568     // hardware fmed3 behavior converting to a min.
9569     // FIXME: Should this be allowing -0.0?
9570     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9571       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9572   }
9573 
9574   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9575   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9576     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9577     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9578     // then give the other result, which is different from med3 with a NaN
9579     // input.
9580     SDValue Var = Op0.getOperand(0);
9581     if (!DAG.isKnownNeverSNaN(Var))
9582       return SDValue();
9583 
9584     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9585 
9586     if ((!K0->hasOneUse() ||
9587          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9588         (!K1->hasOneUse() ||
9589          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9590       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9591                          Var, SDValue(K0, 0), SDValue(K1, 0));
9592     }
9593   }
9594 
9595   return SDValue();
9596 }
9597 
9598 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9599                                                DAGCombinerInfo &DCI) const {
9600   SelectionDAG &DAG = DCI.DAG;
9601 
9602   EVT VT = N->getValueType(0);
9603   unsigned Opc = N->getOpcode();
9604   SDValue Op0 = N->getOperand(0);
9605   SDValue Op1 = N->getOperand(1);
9606 
9607   // Only do this if the inner op has one use since this will just increases
9608   // register pressure for no benefit.
9609 
9610   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9611       !VT.isVector() &&
9612       (VT == MVT::i32 || VT == MVT::f32 ||
9613        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9614     // max(max(a, b), c) -> max3(a, b, c)
9615     // min(min(a, b), c) -> min3(a, b, c)
9616     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9617       SDLoc DL(N);
9618       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9619                          DL,
9620                          N->getValueType(0),
9621                          Op0.getOperand(0),
9622                          Op0.getOperand(1),
9623                          Op1);
9624     }
9625 
9626     // Try commuted.
9627     // max(a, max(b, c)) -> max3(a, b, c)
9628     // min(a, min(b, c)) -> min3(a, b, c)
9629     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9630       SDLoc DL(N);
9631       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9632                          DL,
9633                          N->getValueType(0),
9634                          Op0,
9635                          Op1.getOperand(0),
9636                          Op1.getOperand(1));
9637     }
9638   }
9639 
9640   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9641   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9642     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9643       return Med3;
9644   }
9645 
9646   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9647     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9648       return Med3;
9649   }
9650 
9651   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9652   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9653        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9654        (Opc == AMDGPUISD::FMIN_LEGACY &&
9655         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9656       (VT == MVT::f32 || VT == MVT::f64 ||
9657        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9658        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9659       Op0.hasOneUse()) {
9660     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9661       return Res;
9662   }
9663 
9664   return SDValue();
9665 }
9666 
9667 static bool isClampZeroToOne(SDValue A, SDValue B) {
9668   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9669     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9670       // FIXME: Should this be allowing -0.0?
9671       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9672              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9673     }
9674   }
9675 
9676   return false;
9677 }
9678 
9679 // FIXME: Should only worry about snans for version with chain.
9680 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9681                                               DAGCombinerInfo &DCI) const {
9682   EVT VT = N->getValueType(0);
9683   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9684   // NaNs. With a NaN input, the order of the operands may change the result.
9685 
9686   SelectionDAG &DAG = DCI.DAG;
9687   SDLoc SL(N);
9688 
9689   SDValue Src0 = N->getOperand(0);
9690   SDValue Src1 = N->getOperand(1);
9691   SDValue Src2 = N->getOperand(2);
9692 
9693   if (isClampZeroToOne(Src0, Src1)) {
9694     // const_a, const_b, x -> clamp is safe in all cases including signaling
9695     // nans.
9696     // FIXME: Should this be allowing -0.0?
9697     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9698   }
9699 
9700   const MachineFunction &MF = DAG.getMachineFunction();
9701   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9702 
9703   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9704   // handling no dx10-clamp?
9705   if (Info->getMode().DX10Clamp) {
9706     // If NaNs is clamped to 0, we are free to reorder the inputs.
9707 
9708     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9709       std::swap(Src0, Src1);
9710 
9711     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9712       std::swap(Src1, Src2);
9713 
9714     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9715       std::swap(Src0, Src1);
9716 
9717     if (isClampZeroToOne(Src1, Src2))
9718       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9719   }
9720 
9721   return SDValue();
9722 }
9723 
9724 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9725                                                  DAGCombinerInfo &DCI) const {
9726   SDValue Src0 = N->getOperand(0);
9727   SDValue Src1 = N->getOperand(1);
9728   if (Src0.isUndef() && Src1.isUndef())
9729     return DCI.DAG.getUNDEF(N->getValueType(0));
9730   return SDValue();
9731 }
9732 
9733 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9734 // expanded into a set of cmp/select instructions.
9735 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9736                                                 unsigned NumElem,
9737                                                 bool IsDivergentIdx) {
9738   if (UseDivergentRegisterIndexing)
9739     return false;
9740 
9741   unsigned VecSize = EltSize * NumElem;
9742 
9743   // Sub-dword vectors of size 2 dword or less have better implementation.
9744   if (VecSize <= 64 && EltSize < 32)
9745     return false;
9746 
9747   // Always expand the rest of sub-dword instructions, otherwise it will be
9748   // lowered via memory.
9749   if (EltSize < 32)
9750     return true;
9751 
9752   // Always do this if var-idx is divergent, otherwise it will become a loop.
9753   if (IsDivergentIdx)
9754     return true;
9755 
9756   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9757   unsigned NumInsts = NumElem /* Number of compares */ +
9758                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9759   return NumInsts <= 16;
9760 }
9761 
9762 static bool shouldExpandVectorDynExt(SDNode *N) {
9763   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9764   if (isa<ConstantSDNode>(Idx))
9765     return false;
9766 
9767   SDValue Vec = N->getOperand(0);
9768   EVT VecVT = Vec.getValueType();
9769   EVT EltVT = VecVT.getVectorElementType();
9770   unsigned EltSize = EltVT.getSizeInBits();
9771   unsigned NumElem = VecVT.getVectorNumElements();
9772 
9773   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9774                                                     Idx->isDivergent());
9775 }
9776 
9777 SDValue SITargetLowering::performExtractVectorEltCombine(
9778   SDNode *N, DAGCombinerInfo &DCI) const {
9779   SDValue Vec = N->getOperand(0);
9780   SelectionDAG &DAG = DCI.DAG;
9781 
9782   EVT VecVT = Vec.getValueType();
9783   EVT EltVT = VecVT.getVectorElementType();
9784 
9785   if ((Vec.getOpcode() == ISD::FNEG ||
9786        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9787     SDLoc SL(N);
9788     EVT EltVT = N->getValueType(0);
9789     SDValue Idx = N->getOperand(1);
9790     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9791                               Vec.getOperand(0), Idx);
9792     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9793   }
9794 
9795   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9796   //    =>
9797   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9798   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9799   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9800   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9801     SDLoc SL(N);
9802     EVT EltVT = N->getValueType(0);
9803     SDValue Idx = N->getOperand(1);
9804     unsigned Opc = Vec.getOpcode();
9805 
9806     switch(Opc) {
9807     default:
9808       break;
9809       // TODO: Support other binary operations.
9810     case ISD::FADD:
9811     case ISD::FSUB:
9812     case ISD::FMUL:
9813     case ISD::ADD:
9814     case ISD::UMIN:
9815     case ISD::UMAX:
9816     case ISD::SMIN:
9817     case ISD::SMAX:
9818     case ISD::FMAXNUM:
9819     case ISD::FMINNUM:
9820     case ISD::FMAXNUM_IEEE:
9821     case ISD::FMINNUM_IEEE: {
9822       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9823                                  Vec.getOperand(0), Idx);
9824       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9825                                  Vec.getOperand(1), Idx);
9826 
9827       DCI.AddToWorklist(Elt0.getNode());
9828       DCI.AddToWorklist(Elt1.getNode());
9829       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9830     }
9831     }
9832   }
9833 
9834   unsigned VecSize = VecVT.getSizeInBits();
9835   unsigned EltSize = EltVT.getSizeInBits();
9836 
9837   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9838   if (::shouldExpandVectorDynExt(N)) {
9839     SDLoc SL(N);
9840     SDValue Idx = N->getOperand(1);
9841     SDValue V;
9842     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9843       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9844       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9845       if (I == 0)
9846         V = Elt;
9847       else
9848         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9849     }
9850     return V;
9851   }
9852 
9853   if (!DCI.isBeforeLegalize())
9854     return SDValue();
9855 
9856   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9857   // elements. This exposes more load reduction opportunities by replacing
9858   // multiple small extract_vector_elements with a single 32-bit extract.
9859   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9860   if (isa<MemSDNode>(Vec) &&
9861       EltSize <= 16 &&
9862       EltVT.isByteSized() &&
9863       VecSize > 32 &&
9864       VecSize % 32 == 0 &&
9865       Idx) {
9866     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9867 
9868     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9869     unsigned EltIdx = BitIndex / 32;
9870     unsigned LeftoverBitIdx = BitIndex % 32;
9871     SDLoc SL(N);
9872 
9873     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9874     DCI.AddToWorklist(Cast.getNode());
9875 
9876     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9877                               DAG.getConstant(EltIdx, SL, MVT::i32));
9878     DCI.AddToWorklist(Elt.getNode());
9879     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9880                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9881     DCI.AddToWorklist(Srl.getNode());
9882 
9883     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9884     DCI.AddToWorklist(Trunc.getNode());
9885     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9886   }
9887 
9888   return SDValue();
9889 }
9890 
9891 SDValue
9892 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9893                                                 DAGCombinerInfo &DCI) const {
9894   SDValue Vec = N->getOperand(0);
9895   SDValue Idx = N->getOperand(2);
9896   EVT VecVT = Vec.getValueType();
9897   EVT EltVT = VecVT.getVectorElementType();
9898 
9899   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9900   // => BUILD_VECTOR n x select (e, const-idx)
9901   if (!::shouldExpandVectorDynExt(N))
9902     return SDValue();
9903 
9904   SelectionDAG &DAG = DCI.DAG;
9905   SDLoc SL(N);
9906   SDValue Ins = N->getOperand(1);
9907   EVT IdxVT = Idx.getValueType();
9908 
9909   SmallVector<SDValue, 16> Ops;
9910   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9911     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9912     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9913     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9914     Ops.push_back(V);
9915   }
9916 
9917   return DAG.getBuildVector(VecVT, SL, Ops);
9918 }
9919 
9920 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9921                                           const SDNode *N0,
9922                                           const SDNode *N1) const {
9923   EVT VT = N0->getValueType(0);
9924 
9925   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9926   // support denormals ever.
9927   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9928        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9929         getSubtarget()->hasMadF16())) &&
9930        isOperationLegal(ISD::FMAD, VT))
9931     return ISD::FMAD;
9932 
9933   const TargetOptions &Options = DAG.getTarget().Options;
9934   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9935        (N0->getFlags().hasAllowContract() &&
9936         N1->getFlags().hasAllowContract())) &&
9937       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9938     return ISD::FMA;
9939   }
9940 
9941   return 0;
9942 }
9943 
9944 // For a reassociatable opcode perform:
9945 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9946 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9947                                                SelectionDAG &DAG) const {
9948   EVT VT = N->getValueType(0);
9949   if (VT != MVT::i32 && VT != MVT::i64)
9950     return SDValue();
9951 
9952   unsigned Opc = N->getOpcode();
9953   SDValue Op0 = N->getOperand(0);
9954   SDValue Op1 = N->getOperand(1);
9955 
9956   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9957     return SDValue();
9958 
9959   if (Op0->isDivergent())
9960     std::swap(Op0, Op1);
9961 
9962   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9963     return SDValue();
9964 
9965   SDValue Op2 = Op1.getOperand(1);
9966   Op1 = Op1.getOperand(0);
9967   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9968     return SDValue();
9969 
9970   if (Op1->isDivergent())
9971     std::swap(Op1, Op2);
9972 
9973   // If either operand is constant this will conflict with
9974   // DAGCombiner::ReassociateOps().
9975   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9976       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9977     return SDValue();
9978 
9979   SDLoc SL(N);
9980   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9981   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9982 }
9983 
9984 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9985                            EVT VT,
9986                            SDValue N0, SDValue N1, SDValue N2,
9987                            bool Signed) {
9988   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9989   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9990   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9991   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9992 }
9993 
9994 SDValue SITargetLowering::performAddCombine(SDNode *N,
9995                                             DAGCombinerInfo &DCI) const {
9996   SelectionDAG &DAG = DCI.DAG;
9997   EVT VT = N->getValueType(0);
9998   SDLoc SL(N);
9999   SDValue LHS = N->getOperand(0);
10000   SDValue RHS = N->getOperand(1);
10001 
10002   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10003       && Subtarget->hasMad64_32() &&
10004       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10005       VT.getScalarSizeInBits() <= 64) {
10006     if (LHS.getOpcode() != ISD::MUL)
10007       std::swap(LHS, RHS);
10008 
10009     SDValue MulLHS = LHS.getOperand(0);
10010     SDValue MulRHS = LHS.getOperand(1);
10011     SDValue AddRHS = RHS;
10012 
10013     // TODO: Maybe restrict if SGPR inputs.
10014     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10015         numBitsUnsigned(MulRHS, DAG) <= 32) {
10016       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10017       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10018       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10019       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10020     }
10021 
10022     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10023       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10024       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10025       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10026       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10027     }
10028 
10029     return SDValue();
10030   }
10031 
10032   if (SDValue V = reassociateScalarOps(N, DAG)) {
10033     return V;
10034   }
10035 
10036   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10037     return SDValue();
10038 
10039   // add x, zext (setcc) => addcarry x, 0, setcc
10040   // add x, sext (setcc) => subcarry x, 0, setcc
10041   unsigned Opc = LHS.getOpcode();
10042   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10043       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10044     std::swap(RHS, LHS);
10045 
10046   Opc = RHS.getOpcode();
10047   switch (Opc) {
10048   default: break;
10049   case ISD::ZERO_EXTEND:
10050   case ISD::SIGN_EXTEND:
10051   case ISD::ANY_EXTEND: {
10052     auto Cond = RHS.getOperand(0);
10053     // If this won't be a real VOPC output, we would still need to insert an
10054     // extra instruction anyway.
10055     if (!isBoolSGPR(Cond))
10056       break;
10057     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10058     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10059     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10060     return DAG.getNode(Opc, SL, VTList, Args);
10061   }
10062   case ISD::ADDCARRY: {
10063     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10064     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10065     if (!C || C->getZExtValue() != 0) break;
10066     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10067     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10068   }
10069   }
10070   return SDValue();
10071 }
10072 
10073 SDValue SITargetLowering::performSubCombine(SDNode *N,
10074                                             DAGCombinerInfo &DCI) const {
10075   SelectionDAG &DAG = DCI.DAG;
10076   EVT VT = N->getValueType(0);
10077 
10078   if (VT != MVT::i32)
10079     return SDValue();
10080 
10081   SDLoc SL(N);
10082   SDValue LHS = N->getOperand(0);
10083   SDValue RHS = N->getOperand(1);
10084 
10085   // sub x, zext (setcc) => subcarry x, 0, setcc
10086   // sub x, sext (setcc) => addcarry x, 0, setcc
10087   unsigned Opc = RHS.getOpcode();
10088   switch (Opc) {
10089   default: break;
10090   case ISD::ZERO_EXTEND:
10091   case ISD::SIGN_EXTEND:
10092   case ISD::ANY_EXTEND: {
10093     auto Cond = RHS.getOperand(0);
10094     // If this won't be a real VOPC output, we would still need to insert an
10095     // extra instruction anyway.
10096     if (!isBoolSGPR(Cond))
10097       break;
10098     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10099     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10100     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10101     return DAG.getNode(Opc, SL, VTList, Args);
10102   }
10103   }
10104 
10105   if (LHS.getOpcode() == ISD::SUBCARRY) {
10106     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10107     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10108     if (!C || !C->isNullValue())
10109       return SDValue();
10110     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10111     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10112   }
10113   return SDValue();
10114 }
10115 
10116 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10117   DAGCombinerInfo &DCI) const {
10118 
10119   if (N->getValueType(0) != MVT::i32)
10120     return SDValue();
10121 
10122   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10123   if (!C || C->getZExtValue() != 0)
10124     return SDValue();
10125 
10126   SelectionDAG &DAG = DCI.DAG;
10127   SDValue LHS = N->getOperand(0);
10128 
10129   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10130   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10131   unsigned LHSOpc = LHS.getOpcode();
10132   unsigned Opc = N->getOpcode();
10133   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10134       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10135     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10136     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10137   }
10138   return SDValue();
10139 }
10140 
10141 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10142                                              DAGCombinerInfo &DCI) const {
10143   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10144     return SDValue();
10145 
10146   SelectionDAG &DAG = DCI.DAG;
10147   EVT VT = N->getValueType(0);
10148 
10149   SDLoc SL(N);
10150   SDValue LHS = N->getOperand(0);
10151   SDValue RHS = N->getOperand(1);
10152 
10153   // These should really be instruction patterns, but writing patterns with
10154   // source modiifiers is a pain.
10155 
10156   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10157   if (LHS.getOpcode() == ISD::FADD) {
10158     SDValue A = LHS.getOperand(0);
10159     if (A == LHS.getOperand(1)) {
10160       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10161       if (FusedOp != 0) {
10162         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10163         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10164       }
10165     }
10166   }
10167 
10168   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10169   if (RHS.getOpcode() == ISD::FADD) {
10170     SDValue A = RHS.getOperand(0);
10171     if (A == RHS.getOperand(1)) {
10172       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10173       if (FusedOp != 0) {
10174         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10175         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10176       }
10177     }
10178   }
10179 
10180   return SDValue();
10181 }
10182 
10183 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10184                                              DAGCombinerInfo &DCI) const {
10185   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10186     return SDValue();
10187 
10188   SelectionDAG &DAG = DCI.DAG;
10189   SDLoc SL(N);
10190   EVT VT = N->getValueType(0);
10191   assert(!VT.isVector());
10192 
10193   // Try to get the fneg to fold into the source modifier. This undoes generic
10194   // DAG combines and folds them into the mad.
10195   //
10196   // Only do this if we are not trying to support denormals. v_mad_f32 does
10197   // not support denormals ever.
10198   SDValue LHS = N->getOperand(0);
10199   SDValue RHS = N->getOperand(1);
10200   if (LHS.getOpcode() == ISD::FADD) {
10201     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10202     SDValue A = LHS.getOperand(0);
10203     if (A == LHS.getOperand(1)) {
10204       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10205       if (FusedOp != 0){
10206         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10207         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10208 
10209         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10210       }
10211     }
10212   }
10213 
10214   if (RHS.getOpcode() == ISD::FADD) {
10215     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10216 
10217     SDValue A = RHS.getOperand(0);
10218     if (A == RHS.getOperand(1)) {
10219       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10220       if (FusedOp != 0){
10221         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10222         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10223       }
10224     }
10225   }
10226 
10227   return SDValue();
10228 }
10229 
10230 SDValue SITargetLowering::performFMACombine(SDNode *N,
10231                                             DAGCombinerInfo &DCI) const {
10232   SelectionDAG &DAG = DCI.DAG;
10233   EVT VT = N->getValueType(0);
10234   SDLoc SL(N);
10235 
10236   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10237     return SDValue();
10238 
10239   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10240   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10241   SDValue Op1 = N->getOperand(0);
10242   SDValue Op2 = N->getOperand(1);
10243   SDValue FMA = N->getOperand(2);
10244 
10245   if (FMA.getOpcode() != ISD::FMA ||
10246       Op1.getOpcode() != ISD::FP_EXTEND ||
10247       Op2.getOpcode() != ISD::FP_EXTEND)
10248     return SDValue();
10249 
10250   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10251   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10252   // is sufficient to allow generaing fdot2.
10253   const TargetOptions &Options = DAG.getTarget().Options;
10254   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10255       (N->getFlags().hasAllowContract() &&
10256        FMA->getFlags().hasAllowContract())) {
10257     Op1 = Op1.getOperand(0);
10258     Op2 = Op2.getOperand(0);
10259     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10260         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10261       return SDValue();
10262 
10263     SDValue Vec1 = Op1.getOperand(0);
10264     SDValue Idx1 = Op1.getOperand(1);
10265     SDValue Vec2 = Op2.getOperand(0);
10266 
10267     SDValue FMAOp1 = FMA.getOperand(0);
10268     SDValue FMAOp2 = FMA.getOperand(1);
10269     SDValue FMAAcc = FMA.getOperand(2);
10270 
10271     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10272         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10273       return SDValue();
10274 
10275     FMAOp1 = FMAOp1.getOperand(0);
10276     FMAOp2 = FMAOp2.getOperand(0);
10277     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10278         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10279       return SDValue();
10280 
10281     SDValue Vec3 = FMAOp1.getOperand(0);
10282     SDValue Vec4 = FMAOp2.getOperand(0);
10283     SDValue Idx2 = FMAOp1.getOperand(1);
10284 
10285     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10286         // Idx1 and Idx2 cannot be the same.
10287         Idx1 == Idx2)
10288       return SDValue();
10289 
10290     if (Vec1 == Vec2 || Vec3 == Vec4)
10291       return SDValue();
10292 
10293     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10294       return SDValue();
10295 
10296     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10297         (Vec1 == Vec4 && Vec2 == Vec3)) {
10298       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10299                          DAG.getTargetConstant(0, SL, MVT::i1));
10300     }
10301   }
10302   return SDValue();
10303 }
10304 
10305 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10306                                               DAGCombinerInfo &DCI) const {
10307   SelectionDAG &DAG = DCI.DAG;
10308   SDLoc SL(N);
10309 
10310   SDValue LHS = N->getOperand(0);
10311   SDValue RHS = N->getOperand(1);
10312   EVT VT = LHS.getValueType();
10313   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10314 
10315   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10316   if (!CRHS) {
10317     CRHS = dyn_cast<ConstantSDNode>(LHS);
10318     if (CRHS) {
10319       std::swap(LHS, RHS);
10320       CC = getSetCCSwappedOperands(CC);
10321     }
10322   }
10323 
10324   if (CRHS) {
10325     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10326         isBoolSGPR(LHS.getOperand(0))) {
10327       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10328       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10329       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10330       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10331       if ((CRHS->isAllOnesValue() &&
10332            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10333           (CRHS->isNullValue() &&
10334            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10335         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10336                            DAG.getConstant(-1, SL, MVT::i1));
10337       if ((CRHS->isAllOnesValue() &&
10338            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10339           (CRHS->isNullValue() &&
10340            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10341         return LHS.getOperand(0);
10342     }
10343 
10344     uint64_t CRHSVal = CRHS->getZExtValue();
10345     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10346         LHS.getOpcode() == ISD::SELECT &&
10347         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10348         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10349         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10350         isBoolSGPR(LHS.getOperand(0))) {
10351       // Given CT != FT:
10352       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10353       // setcc (select cc, CT, CF), CF, ne => cc
10354       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10355       // setcc (select cc, CT, CF), CT, eq => cc
10356       uint64_t CT = LHS.getConstantOperandVal(1);
10357       uint64_t CF = LHS.getConstantOperandVal(2);
10358 
10359       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10360           (CT == CRHSVal && CC == ISD::SETNE))
10361         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10362                            DAG.getConstant(-1, SL, MVT::i1));
10363       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10364           (CT == CRHSVal && CC == ISD::SETEQ))
10365         return LHS.getOperand(0);
10366     }
10367   }
10368 
10369   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10370                                            VT != MVT::f16))
10371     return SDValue();
10372 
10373   // Match isinf/isfinite pattern
10374   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10375   // (fcmp one (fabs x), inf) -> (fp_class x,
10376   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10377   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10378     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10379     if (!CRHS)
10380       return SDValue();
10381 
10382     const APFloat &APF = CRHS->getValueAPF();
10383     if (APF.isInfinity() && !APF.isNegative()) {
10384       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10385                                  SIInstrFlags::N_INFINITY;
10386       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10387                                     SIInstrFlags::P_ZERO |
10388                                     SIInstrFlags::N_NORMAL |
10389                                     SIInstrFlags::P_NORMAL |
10390                                     SIInstrFlags::N_SUBNORMAL |
10391                                     SIInstrFlags::P_SUBNORMAL;
10392       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10393       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10394                          DAG.getConstant(Mask, SL, MVT::i32));
10395     }
10396   }
10397 
10398   return SDValue();
10399 }
10400 
10401 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10402                                                      DAGCombinerInfo &DCI) const {
10403   SelectionDAG &DAG = DCI.DAG;
10404   SDLoc SL(N);
10405   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10406 
10407   SDValue Src = N->getOperand(0);
10408   SDValue Shift = N->getOperand(0);
10409 
10410   // TODO: Extend type shouldn't matter (assuming legal types).
10411   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10412     Shift = Shift.getOperand(0);
10413 
10414   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10415     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10416     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10417     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10418     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10419     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10420     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10421       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10422                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10423 
10424       unsigned ShiftOffset = 8 * Offset;
10425       if (Shift.getOpcode() == ISD::SHL)
10426         ShiftOffset -= C->getZExtValue();
10427       else
10428         ShiftOffset += C->getZExtValue();
10429 
10430       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10431         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10432                            MVT::f32, Shift);
10433       }
10434     }
10435   }
10436 
10437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10438   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10439   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10440     // We simplified Src. If this node is not dead, visit it again so it is
10441     // folded properly.
10442     if (N->getOpcode() != ISD::DELETED_NODE)
10443       DCI.AddToWorklist(N);
10444     return SDValue(N, 0);
10445   }
10446 
10447   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10448   if (SDValue DemandedSrc =
10449           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10450     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10451 
10452   return SDValue();
10453 }
10454 
10455 SDValue SITargetLowering::performClampCombine(SDNode *N,
10456                                               DAGCombinerInfo &DCI) const {
10457   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10458   if (!CSrc)
10459     return SDValue();
10460 
10461   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10462   const APFloat &F = CSrc->getValueAPF();
10463   APFloat Zero = APFloat::getZero(F.getSemantics());
10464   if (F < Zero ||
10465       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10466     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10467   }
10468 
10469   APFloat One(F.getSemantics(), "1.0");
10470   if (F > One)
10471     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10472 
10473   return SDValue(CSrc, 0);
10474 }
10475 
10476 
10477 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10478                                             DAGCombinerInfo &DCI) const {
10479   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10480     return SDValue();
10481   switch (N->getOpcode()) {
10482   case ISD::ADD:
10483     return performAddCombine(N, DCI);
10484   case ISD::SUB:
10485     return performSubCombine(N, DCI);
10486   case ISD::ADDCARRY:
10487   case ISD::SUBCARRY:
10488     return performAddCarrySubCarryCombine(N, DCI);
10489   case ISD::FADD:
10490     return performFAddCombine(N, DCI);
10491   case ISD::FSUB:
10492     return performFSubCombine(N, DCI);
10493   case ISD::SETCC:
10494     return performSetCCCombine(N, DCI);
10495   case ISD::FMAXNUM:
10496   case ISD::FMINNUM:
10497   case ISD::FMAXNUM_IEEE:
10498   case ISD::FMINNUM_IEEE:
10499   case ISD::SMAX:
10500   case ISD::SMIN:
10501   case ISD::UMAX:
10502   case ISD::UMIN:
10503   case AMDGPUISD::FMIN_LEGACY:
10504   case AMDGPUISD::FMAX_LEGACY:
10505     return performMinMaxCombine(N, DCI);
10506   case ISD::FMA:
10507     return performFMACombine(N, DCI);
10508   case ISD::AND:
10509     return performAndCombine(N, DCI);
10510   case ISD::OR:
10511     return performOrCombine(N, DCI);
10512   case ISD::XOR:
10513     return performXorCombine(N, DCI);
10514   case ISD::ZERO_EXTEND:
10515     return performZeroExtendCombine(N, DCI);
10516   case ISD::SIGN_EXTEND_INREG:
10517     return performSignExtendInRegCombine(N , DCI);
10518   case AMDGPUISD::FP_CLASS:
10519     return performClassCombine(N, DCI);
10520   case ISD::FCANONICALIZE:
10521     return performFCanonicalizeCombine(N, DCI);
10522   case AMDGPUISD::RCP:
10523     return performRcpCombine(N, DCI);
10524   case AMDGPUISD::FRACT:
10525   case AMDGPUISD::RSQ:
10526   case AMDGPUISD::RCP_LEGACY:
10527   case AMDGPUISD::RCP_IFLAG:
10528   case AMDGPUISD::RSQ_CLAMP:
10529   case AMDGPUISD::LDEXP: {
10530     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10531     SDValue Src = N->getOperand(0);
10532     if (Src.isUndef())
10533       return Src;
10534     break;
10535   }
10536   case ISD::SINT_TO_FP:
10537   case ISD::UINT_TO_FP:
10538     return performUCharToFloatCombine(N, DCI);
10539   case AMDGPUISD::CVT_F32_UBYTE0:
10540   case AMDGPUISD::CVT_F32_UBYTE1:
10541   case AMDGPUISD::CVT_F32_UBYTE2:
10542   case AMDGPUISD::CVT_F32_UBYTE3:
10543     return performCvtF32UByteNCombine(N, DCI);
10544   case AMDGPUISD::FMED3:
10545     return performFMed3Combine(N, DCI);
10546   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10547     return performCvtPkRTZCombine(N, DCI);
10548   case AMDGPUISD::CLAMP:
10549     return performClampCombine(N, DCI);
10550   case ISD::SCALAR_TO_VECTOR: {
10551     SelectionDAG &DAG = DCI.DAG;
10552     EVT VT = N->getValueType(0);
10553 
10554     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10555     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10556       SDLoc SL(N);
10557       SDValue Src = N->getOperand(0);
10558       EVT EltVT = Src.getValueType();
10559       if (EltVT == MVT::f16)
10560         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10561 
10562       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10563       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10564     }
10565 
10566     break;
10567   }
10568   case ISD::EXTRACT_VECTOR_ELT:
10569     return performExtractVectorEltCombine(N, DCI);
10570   case ISD::INSERT_VECTOR_ELT:
10571     return performInsertVectorEltCombine(N, DCI);
10572   case ISD::LOAD: {
10573     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10574       return Widended;
10575     LLVM_FALLTHROUGH;
10576   }
10577   default: {
10578     if (!DCI.isBeforeLegalize()) {
10579       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10580         return performMemSDNodeCombine(MemNode, DCI);
10581     }
10582 
10583     break;
10584   }
10585   }
10586 
10587   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10588 }
10589 
10590 /// Helper function for adjustWritemask
10591 static unsigned SubIdx2Lane(unsigned Idx) {
10592   switch (Idx) {
10593   default: return 0;
10594   case AMDGPU::sub0: return 0;
10595   case AMDGPU::sub1: return 1;
10596   case AMDGPU::sub2: return 2;
10597   case AMDGPU::sub3: return 3;
10598   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10599   }
10600 }
10601 
10602 /// Adjust the writemask of MIMG instructions
10603 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10604                                           SelectionDAG &DAG) const {
10605   unsigned Opcode = Node->getMachineOpcode();
10606 
10607   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10608   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10609   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10610     return Node; // not implemented for D16
10611 
10612   SDNode *Users[5] = { nullptr };
10613   unsigned Lane = 0;
10614   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10615   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10616   unsigned NewDmask = 0;
10617   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10618   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10619   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10620                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10621   unsigned TFCLane = 0;
10622   bool HasChain = Node->getNumValues() > 1;
10623 
10624   if (OldDmask == 0) {
10625     // These are folded out, but on the chance it happens don't assert.
10626     return Node;
10627   }
10628 
10629   unsigned OldBitsSet = countPopulation(OldDmask);
10630   // Work out which is the TFE/LWE lane if that is enabled.
10631   if (UsesTFC) {
10632     TFCLane = OldBitsSet;
10633   }
10634 
10635   // Try to figure out the used register components
10636   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10637        I != E; ++I) {
10638 
10639     // Don't look at users of the chain.
10640     if (I.getUse().getResNo() != 0)
10641       continue;
10642 
10643     // Abort if we can't understand the usage
10644     if (!I->isMachineOpcode() ||
10645         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10646       return Node;
10647 
10648     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10649     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10650     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10651     // set, etc.
10652     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10653 
10654     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10655     if (UsesTFC && Lane == TFCLane) {
10656       Users[Lane] = *I;
10657     } else {
10658       // Set which texture component corresponds to the lane.
10659       unsigned Comp;
10660       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10661         Comp = countTrailingZeros(Dmask);
10662         Dmask &= ~(1 << Comp);
10663       }
10664 
10665       // Abort if we have more than one user per component.
10666       if (Users[Lane])
10667         return Node;
10668 
10669       Users[Lane] = *I;
10670       NewDmask |= 1 << Comp;
10671     }
10672   }
10673 
10674   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10675   bool NoChannels = !NewDmask;
10676   if (NoChannels) {
10677     if (!UsesTFC) {
10678       // No uses of the result and not using TFC. Then do nothing.
10679       return Node;
10680     }
10681     // If the original dmask has one channel - then nothing to do
10682     if (OldBitsSet == 1)
10683       return Node;
10684     // Use an arbitrary dmask - required for the instruction to work
10685     NewDmask = 1;
10686   }
10687   // Abort if there's no change
10688   if (NewDmask == OldDmask)
10689     return Node;
10690 
10691   unsigned BitsSet = countPopulation(NewDmask);
10692 
10693   // Check for TFE or LWE - increase the number of channels by one to account
10694   // for the extra return value
10695   // This will need adjustment for D16 if this is also included in
10696   // adjustWriteMask (this function) but at present D16 are excluded.
10697   unsigned NewChannels = BitsSet + UsesTFC;
10698 
10699   int NewOpcode =
10700       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10701   assert(NewOpcode != -1 &&
10702          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10703          "failed to find equivalent MIMG op");
10704 
10705   // Adjust the writemask in the node
10706   SmallVector<SDValue, 12> Ops;
10707   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10708   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10709   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10710 
10711   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10712 
10713   MVT ResultVT = NewChannels == 1 ?
10714     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10715                            NewChannels == 5 ? 8 : NewChannels);
10716   SDVTList NewVTList = HasChain ?
10717     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10718 
10719 
10720   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10721                                               NewVTList, Ops);
10722 
10723   if (HasChain) {
10724     // Update chain.
10725     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10726     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10727   }
10728 
10729   if (NewChannels == 1) {
10730     assert(Node->hasNUsesOfValue(1, 0));
10731     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10732                                       SDLoc(Node), Users[Lane]->getValueType(0),
10733                                       SDValue(NewNode, 0));
10734     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10735     return nullptr;
10736   }
10737 
10738   // Update the users of the node with the new indices
10739   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10740     SDNode *User = Users[i];
10741     if (!User) {
10742       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10743       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10744       if (i || !NoChannels)
10745         continue;
10746     } else {
10747       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10748       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10749     }
10750 
10751     switch (Idx) {
10752     default: break;
10753     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10754     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10755     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10756     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10757     }
10758   }
10759 
10760   DAG.RemoveDeadNode(Node);
10761   return nullptr;
10762 }
10763 
10764 static bool isFrameIndexOp(SDValue Op) {
10765   if (Op.getOpcode() == ISD::AssertZext)
10766     Op = Op.getOperand(0);
10767 
10768   return isa<FrameIndexSDNode>(Op);
10769 }
10770 
10771 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10772 /// with frame index operands.
10773 /// LLVM assumes that inputs are to these instructions are registers.
10774 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10775                                                         SelectionDAG &DAG) const {
10776   if (Node->getOpcode() == ISD::CopyToReg) {
10777     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10778     SDValue SrcVal = Node->getOperand(2);
10779 
10780     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10781     // to try understanding copies to physical registers.
10782     if (SrcVal.getValueType() == MVT::i1 &&
10783         Register::isPhysicalRegister(DestReg->getReg())) {
10784       SDLoc SL(Node);
10785       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10786       SDValue VReg = DAG.getRegister(
10787         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10788 
10789       SDNode *Glued = Node->getGluedNode();
10790       SDValue ToVReg
10791         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10792                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10793       SDValue ToResultReg
10794         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10795                            VReg, ToVReg.getValue(1));
10796       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10797       DAG.RemoveDeadNode(Node);
10798       return ToResultReg.getNode();
10799     }
10800   }
10801 
10802   SmallVector<SDValue, 8> Ops;
10803   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10804     if (!isFrameIndexOp(Node->getOperand(i))) {
10805       Ops.push_back(Node->getOperand(i));
10806       continue;
10807     }
10808 
10809     SDLoc DL(Node);
10810     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10811                                      Node->getOperand(i).getValueType(),
10812                                      Node->getOperand(i)), 0));
10813   }
10814 
10815   return DAG.UpdateNodeOperands(Node, Ops);
10816 }
10817 
10818 /// Fold the instructions after selecting them.
10819 /// Returns null if users were already updated.
10820 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10821                                           SelectionDAG &DAG) const {
10822   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10823   unsigned Opcode = Node->getMachineOpcode();
10824 
10825   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10826       !TII->isGather4(Opcode)) {
10827     return adjustWritemask(Node, DAG);
10828   }
10829 
10830   if (Opcode == AMDGPU::INSERT_SUBREG ||
10831       Opcode == AMDGPU::REG_SEQUENCE) {
10832     legalizeTargetIndependentNode(Node, DAG);
10833     return Node;
10834   }
10835 
10836   switch (Opcode) {
10837   case AMDGPU::V_DIV_SCALE_F32:
10838   case AMDGPU::V_DIV_SCALE_F64: {
10839     // Satisfy the operand register constraint when one of the inputs is
10840     // undefined. Ordinarily each undef value will have its own implicit_def of
10841     // a vreg, so force these to use a single register.
10842     SDValue Src0 = Node->getOperand(0);
10843     SDValue Src1 = Node->getOperand(1);
10844     SDValue Src2 = Node->getOperand(2);
10845 
10846     if ((Src0.isMachineOpcode() &&
10847          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10848         (Src0 == Src1 || Src0 == Src2))
10849       break;
10850 
10851     MVT VT = Src0.getValueType().getSimpleVT();
10852     const TargetRegisterClass *RC =
10853         getRegClassFor(VT, Src0.getNode()->isDivergent());
10854 
10855     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10856     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10857 
10858     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10859                                       UndefReg, Src0, SDValue());
10860 
10861     // src0 must be the same register as src1 or src2, even if the value is
10862     // undefined, so make sure we don't violate this constraint.
10863     if (Src0.isMachineOpcode() &&
10864         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10865       if (Src1.isMachineOpcode() &&
10866           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10867         Src0 = Src1;
10868       else if (Src2.isMachineOpcode() &&
10869                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10870         Src0 = Src2;
10871       else {
10872         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10873         Src0 = UndefReg;
10874         Src1 = UndefReg;
10875       }
10876     } else
10877       break;
10878 
10879     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10880     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10881       Ops.push_back(Node->getOperand(I));
10882 
10883     Ops.push_back(ImpDef.getValue(1));
10884     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10885   }
10886   default:
10887     break;
10888   }
10889 
10890   return Node;
10891 }
10892 
10893 /// Assign the register class depending on the number of
10894 /// bits set in the writemask
10895 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10896                                                      SDNode *Node) const {
10897   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10898 
10899   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10900 
10901   if (TII->isVOP3(MI.getOpcode())) {
10902     // Make sure constant bus requirements are respected.
10903     TII->legalizeOperandsVOP3(MRI, MI);
10904 
10905     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10906     // This saves a chain-copy of registers and better ballance register
10907     // use between vgpr and agpr as agpr tuples tend to be big.
10908     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10909       unsigned Opc = MI.getOpcode();
10910       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10911       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10912                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10913         if (I == -1)
10914           break;
10915         MachineOperand &Op = MI.getOperand(I);
10916         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10917              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10918             !Register::isVirtualRegister(Op.getReg()) ||
10919             !TRI->isAGPR(MRI, Op.getReg()))
10920           continue;
10921         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10922         if (!Src || !Src->isCopy() ||
10923             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10924           continue;
10925         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10926         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10927         // All uses of agpr64 and agpr32 can also accept vgpr except for
10928         // v_accvgpr_read, but we do not produce agpr reads during selection,
10929         // so no use checks are needed.
10930         MRI.setRegClass(Op.getReg(), NewRC);
10931       }
10932     }
10933 
10934     return;
10935   }
10936 
10937   // Replace unused atomics with the no return version.
10938   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10939   if (NoRetAtomicOp != -1) {
10940     if (!Node->hasAnyUseOfValue(0)) {
10941       MI.setDesc(TII->get(NoRetAtomicOp));
10942       MI.RemoveOperand(0);
10943       return;
10944     }
10945 
10946     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10947     // instruction, because the return type of these instructions is a vec2 of
10948     // the memory type, so it can be tied to the input operand.
10949     // This means these instructions always have a use, so we need to add a
10950     // special case to check if the atomic has only one extract_subreg use,
10951     // which itself has no uses.
10952     if ((Node->hasNUsesOfValue(1, 0) &&
10953          Node->use_begin()->isMachineOpcode() &&
10954          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10955          !Node->use_begin()->hasAnyUseOfValue(0))) {
10956       Register Def = MI.getOperand(0).getReg();
10957 
10958       // Change this into a noret atomic.
10959       MI.setDesc(TII->get(NoRetAtomicOp));
10960       MI.RemoveOperand(0);
10961 
10962       // If we only remove the def operand from the atomic instruction, the
10963       // extract_subreg will be left with a use of a vreg without a def.
10964       // So we need to insert an implicit_def to avoid machine verifier
10965       // errors.
10966       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10967               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10968     }
10969     return;
10970   }
10971 }
10972 
10973 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10974                               uint64_t Val) {
10975   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10976   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10977 }
10978 
10979 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10980                                                 const SDLoc &DL,
10981                                                 SDValue Ptr) const {
10982   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10983 
10984   // Build the half of the subregister with the constants before building the
10985   // full 128-bit register. If we are building multiple resource descriptors,
10986   // this will allow CSEing of the 2-component register.
10987   const SDValue Ops0[] = {
10988     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10989     buildSMovImm32(DAG, DL, 0),
10990     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10991     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10992     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10993   };
10994 
10995   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10996                                                 MVT::v2i32, Ops0), 0);
10997 
10998   // Combine the constants and the pointer.
10999   const SDValue Ops1[] = {
11000     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11001     Ptr,
11002     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11003     SubRegHi,
11004     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11005   };
11006 
11007   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11008 }
11009 
11010 /// Return a resource descriptor with the 'Add TID' bit enabled
11011 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11012 ///        of the resource descriptor) to create an offset, which is added to
11013 ///        the resource pointer.
11014 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11015                                            SDValue Ptr, uint32_t RsrcDword1,
11016                                            uint64_t RsrcDword2And3) const {
11017   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11018   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11019   if (RsrcDword1) {
11020     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11021                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11022                     0);
11023   }
11024 
11025   SDValue DataLo = buildSMovImm32(DAG, DL,
11026                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11027   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11028 
11029   const SDValue Ops[] = {
11030     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11031     PtrLo,
11032     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11033     PtrHi,
11034     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11035     DataLo,
11036     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11037     DataHi,
11038     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11039   };
11040 
11041   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11042 }
11043 
11044 //===----------------------------------------------------------------------===//
11045 //                         SI Inline Assembly Support
11046 //===----------------------------------------------------------------------===//
11047 
11048 std::pair<unsigned, const TargetRegisterClass *>
11049 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11050                                                StringRef Constraint,
11051                                                MVT VT) const {
11052   const TargetRegisterClass *RC = nullptr;
11053   if (Constraint.size() == 1) {
11054     const unsigned BitWidth = VT.getSizeInBits();
11055     switch (Constraint[0]) {
11056     default:
11057       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11058     case 's':
11059     case 'r':
11060       switch (BitWidth) {
11061       case 16:
11062         RC = &AMDGPU::SReg_32RegClass;
11063         break;
11064       case 64:
11065         RC = &AMDGPU::SGPR_64RegClass;
11066         break;
11067       default:
11068         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11069         if (!RC)
11070           return std::make_pair(0U, nullptr);
11071         break;
11072       }
11073       break;
11074     case 'v':
11075       switch (BitWidth) {
11076       case 16:
11077         RC = &AMDGPU::VGPR_32RegClass;
11078         break;
11079       default:
11080         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11081         if (!RC)
11082           return std::make_pair(0U, nullptr);
11083         break;
11084       }
11085       break;
11086     case 'a':
11087       if (!Subtarget->hasMAIInsts())
11088         break;
11089       switch (BitWidth) {
11090       case 16:
11091         RC = &AMDGPU::AGPR_32RegClass;
11092         break;
11093       default:
11094         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11095         if (!RC)
11096           return std::make_pair(0U, nullptr);
11097         break;
11098       }
11099       break;
11100     }
11101     // We actually support i128, i16 and f16 as inline parameters
11102     // even if they are not reported as legal
11103     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11104                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11105       return std::make_pair(0U, RC);
11106   }
11107 
11108   if (Constraint.size() > 1) {
11109     if (Constraint[1] == 'v') {
11110       RC = &AMDGPU::VGPR_32RegClass;
11111     } else if (Constraint[1] == 's') {
11112       RC = &AMDGPU::SGPR_32RegClass;
11113     } else if (Constraint[1] == 'a') {
11114       RC = &AMDGPU::AGPR_32RegClass;
11115     }
11116 
11117     if (RC) {
11118       uint32_t Idx;
11119       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11120       if (!Failed && Idx < RC->getNumRegs())
11121         return std::make_pair(RC->getRegister(Idx), RC);
11122     }
11123   }
11124 
11125   // FIXME: Returns VS_32 for physical SGPR constraints
11126   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11127 }
11128 
11129 static bool isImmConstraint(StringRef Constraint) {
11130   if (Constraint.size() == 1) {
11131     switch (Constraint[0]) {
11132     default: break;
11133     case 'I':
11134     case 'J':
11135     case 'A':
11136     case 'B':
11137     case 'C':
11138       return true;
11139     }
11140   } else if (Constraint == "DA" ||
11141              Constraint == "DB") {
11142     return true;
11143   }
11144   return false;
11145 }
11146 
11147 SITargetLowering::ConstraintType
11148 SITargetLowering::getConstraintType(StringRef Constraint) const {
11149   if (Constraint.size() == 1) {
11150     switch (Constraint[0]) {
11151     default: break;
11152     case 's':
11153     case 'v':
11154     case 'a':
11155       return C_RegisterClass;
11156     }
11157   }
11158   if (isImmConstraint(Constraint)) {
11159     return C_Other;
11160   }
11161   return TargetLowering::getConstraintType(Constraint);
11162 }
11163 
11164 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11165   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11166     Val = Val & maskTrailingOnes<uint64_t>(Size);
11167   }
11168   return Val;
11169 }
11170 
11171 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11172                                                     std::string &Constraint,
11173                                                     std::vector<SDValue> &Ops,
11174                                                     SelectionDAG &DAG) const {
11175   if (isImmConstraint(Constraint)) {
11176     uint64_t Val;
11177     if (getAsmOperandConstVal(Op, Val) &&
11178         checkAsmConstraintVal(Op, Constraint, Val)) {
11179       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11180       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11181     }
11182   } else {
11183     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11184   }
11185 }
11186 
11187 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11188   unsigned Size = Op.getScalarValueSizeInBits();
11189   if (Size > 64)
11190     return false;
11191 
11192   if (Size == 16 && !Subtarget->has16BitInsts())
11193     return false;
11194 
11195   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11196     Val = C->getSExtValue();
11197     return true;
11198   }
11199   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11200     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11201     return true;
11202   }
11203   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11204     if (Size != 16 || Op.getNumOperands() != 2)
11205       return false;
11206     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11207       return false;
11208     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11209       Val = C->getSExtValue();
11210       return true;
11211     }
11212     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11213       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11214       return true;
11215     }
11216   }
11217 
11218   return false;
11219 }
11220 
11221 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11222                                              const std::string &Constraint,
11223                                              uint64_t Val) const {
11224   if (Constraint.size() == 1) {
11225     switch (Constraint[0]) {
11226     case 'I':
11227       return AMDGPU::isInlinableIntLiteral(Val);
11228     case 'J':
11229       return isInt<16>(Val);
11230     case 'A':
11231       return checkAsmConstraintValA(Op, Val);
11232     case 'B':
11233       return isInt<32>(Val);
11234     case 'C':
11235       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11236              AMDGPU::isInlinableIntLiteral(Val);
11237     default:
11238       break;
11239     }
11240   } else if (Constraint.size() == 2) {
11241     if (Constraint == "DA") {
11242       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11243       int64_t LoBits = static_cast<int32_t>(Val);
11244       return checkAsmConstraintValA(Op, HiBits, 32) &&
11245              checkAsmConstraintValA(Op, LoBits, 32);
11246     }
11247     if (Constraint == "DB") {
11248       return true;
11249     }
11250   }
11251   llvm_unreachable("Invalid asm constraint");
11252 }
11253 
11254 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11255                                               uint64_t Val,
11256                                               unsigned MaxSize) const {
11257   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11258   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11259   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11260       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11261       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11262     return true;
11263   }
11264   return false;
11265 }
11266 
11267 // Figure out which registers should be reserved for stack access. Only after
11268 // the function is legalized do we know all of the non-spill stack objects or if
11269 // calls are present.
11270 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11271   MachineRegisterInfo &MRI = MF.getRegInfo();
11272   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11273   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11274   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11275 
11276   if (Info->isEntryFunction()) {
11277     // Callable functions have fixed registers used for stack access.
11278     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11279   }
11280 
11281   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11282                              Info->getStackPtrOffsetReg()));
11283   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11284     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11285 
11286   // We need to worry about replacing the default register with itself in case
11287   // of MIR testcases missing the MFI.
11288   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11289     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11290 
11291   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11292     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11293 
11294   Info->limitOccupancy(MF);
11295 
11296   if (ST.isWave32() && !MF.empty()) {
11297     // Add VCC_HI def because many instructions marked as imp-use VCC where
11298     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11299     // having a use of undef.
11300 
11301     const SIInstrInfo *TII = ST.getInstrInfo();
11302     DebugLoc DL;
11303 
11304     MachineBasicBlock &MBB = MF.front();
11305     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11306     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11307 
11308     for (auto &MBB : MF) {
11309       for (auto &MI : MBB) {
11310         TII->fixImplicitOperands(MI);
11311       }
11312     }
11313   }
11314 
11315   TargetLoweringBase::finalizeLowering(MF);
11316 
11317   // Allocate a VGPR for future SGPR Spill if
11318   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11319   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11320   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11321       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11322     Info->reserveVGPRforSGPRSpills(MF);
11323 }
11324 
11325 void SITargetLowering::computeKnownBitsForFrameIndex(
11326   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11327   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11328 
11329   // Set the high bits to zero based on the maximum allowed scratch size per
11330   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11331   // calculation won't overflow, so assume the sign bit is never set.
11332   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11333 }
11334 
11335 Align SITargetLowering::computeKnownAlignForTargetInstr(
11336   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11337   unsigned Depth) const {
11338   const MachineInstr *MI = MRI.getVRegDef(R);
11339   switch (MI->getOpcode()) {
11340   case AMDGPU::G_INTRINSIC:
11341   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11342     // FIXME: Can this move to generic code? What about the case where the call
11343     // site specifies a lower alignment?
11344     Intrinsic::ID IID = MI->getIntrinsicID();
11345     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11346     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11347     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11348       return *RetAlign;
11349     return Align(1);
11350   }
11351   default:
11352     return Align(1);
11353   }
11354 }
11355 
11356 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11357   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11358   const Align CacheLineAlign = Align(64);
11359 
11360   // Pre-GFX10 target did not benefit from loop alignment
11361   if (!ML || DisableLoopAlignment ||
11362       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11363       getSubtarget()->hasInstFwdPrefetchBug())
11364     return PrefAlign;
11365 
11366   // On GFX10 I$ is 4 x 64 bytes cache lines.
11367   // By default prefetcher keeps one cache line behind and reads two ahead.
11368   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11369   // behind and one ahead.
11370   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11371   // If loop fits 64 bytes it always spans no more than two cache lines and
11372   // does not need an alignment.
11373   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11374   // Else if loop is less or equal 192 bytes we need two lines behind.
11375 
11376   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11377   const MachineBasicBlock *Header = ML->getHeader();
11378   if (Header->getAlignment() != PrefAlign)
11379     return Header->getAlignment(); // Already processed.
11380 
11381   unsigned LoopSize = 0;
11382   for (const MachineBasicBlock *MBB : ML->blocks()) {
11383     // If inner loop block is aligned assume in average half of the alignment
11384     // size to be added as nops.
11385     if (MBB != Header)
11386       LoopSize += MBB->getAlignment().value() / 2;
11387 
11388     for (const MachineInstr &MI : *MBB) {
11389       LoopSize += TII->getInstSizeInBytes(MI);
11390       if (LoopSize > 192)
11391         return PrefAlign;
11392     }
11393   }
11394 
11395   if (LoopSize <= 64)
11396     return PrefAlign;
11397 
11398   if (LoopSize <= 128)
11399     return CacheLineAlign;
11400 
11401   // If any of parent loops is surrounded by prefetch instructions do not
11402   // insert new for inner loop, which would reset parent's settings.
11403   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11404     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11405       auto I = Exit->getFirstNonDebugInstr();
11406       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11407         return CacheLineAlign;
11408     }
11409   }
11410 
11411   MachineBasicBlock *Pre = ML->getLoopPreheader();
11412   MachineBasicBlock *Exit = ML->getExitBlock();
11413 
11414   if (Pre && Exit) {
11415     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11416             TII->get(AMDGPU::S_INST_PREFETCH))
11417       .addImm(1); // prefetch 2 lines behind PC
11418 
11419     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11420             TII->get(AMDGPU::S_INST_PREFETCH))
11421       .addImm(2); // prefetch 1 line behind PC
11422   }
11423 
11424   return CacheLineAlign;
11425 }
11426 
11427 LLVM_ATTRIBUTE_UNUSED
11428 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11429   assert(N->getOpcode() == ISD::CopyFromReg);
11430   do {
11431     // Follow the chain until we find an INLINEASM node.
11432     N = N->getOperand(0).getNode();
11433     if (N->getOpcode() == ISD::INLINEASM ||
11434         N->getOpcode() == ISD::INLINEASM_BR)
11435       return true;
11436   } while (N->getOpcode() == ISD::CopyFromReg);
11437   return false;
11438 }
11439 
11440 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11441   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11442 {
11443   switch (N->getOpcode()) {
11444     case ISD::CopyFromReg:
11445     {
11446       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11447       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11448       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11449       Register Reg = R->getReg();
11450 
11451       // FIXME: Why does this need to consider isLiveIn?
11452       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11453         return !TRI->isSGPRReg(MRI, Reg);
11454 
11455       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11456         return KDA->isDivergent(V);
11457 
11458       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11459       return !TRI->isSGPRReg(MRI, Reg);
11460     }
11461     break;
11462     case ISD::LOAD: {
11463       const LoadSDNode *L = cast<LoadSDNode>(N);
11464       unsigned AS = L->getAddressSpace();
11465       // A flat load may access private memory.
11466       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11467     } break;
11468     case ISD::CALLSEQ_END:
11469     return true;
11470     break;
11471     case ISD::INTRINSIC_WO_CHAIN:
11472     {
11473 
11474     }
11475       return AMDGPU::isIntrinsicSourceOfDivergence(
11476       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11477     case ISD::INTRINSIC_W_CHAIN:
11478       return AMDGPU::isIntrinsicSourceOfDivergence(
11479       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11480   }
11481   return false;
11482 }
11483 
11484 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11485                                                EVT VT) const {
11486   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11487   case MVT::f32:
11488     return hasFP32Denormals(DAG.getMachineFunction());
11489   case MVT::f64:
11490   case MVT::f16:
11491     return hasFP64FP16Denormals(DAG.getMachineFunction());
11492   default:
11493     return false;
11494   }
11495 }
11496 
11497 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11498                                                     const SelectionDAG &DAG,
11499                                                     bool SNaN,
11500                                                     unsigned Depth) const {
11501   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11502     const MachineFunction &MF = DAG.getMachineFunction();
11503     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11504 
11505     if (Info->getMode().DX10Clamp)
11506       return true; // Clamped to 0.
11507     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11508   }
11509 
11510   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11511                                                             SNaN, Depth);
11512 }
11513 
11514 TargetLowering::AtomicExpansionKind
11515 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11516   switch (RMW->getOperation()) {
11517   case AtomicRMWInst::FAdd: {
11518     Type *Ty = RMW->getType();
11519 
11520     // We don't have a way to support 16-bit atomics now, so just leave them
11521     // as-is.
11522     if (Ty->isHalfTy())
11523       return AtomicExpansionKind::None;
11524 
11525     if (!Ty->isFloatTy())
11526       return AtomicExpansionKind::CmpXChg;
11527 
11528     // TODO: Do have these for flat. Older targets also had them for buffers.
11529     unsigned AS = RMW->getPointerAddressSpace();
11530 
11531     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11532       return RMW->use_empty() ? AtomicExpansionKind::None :
11533                                 AtomicExpansionKind::CmpXChg;
11534     }
11535 
11536     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11537       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11538   }
11539   default:
11540     break;
11541   }
11542 
11543   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11544 }
11545 
11546 const TargetRegisterClass *
11547 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11548   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11549   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11550   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11551     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11552                                                : &AMDGPU::SReg_32RegClass;
11553   if (!TRI->isSGPRClass(RC) && !isDivergent)
11554     return TRI->getEquivalentSGPRClass(RC);
11555   else if (TRI->isSGPRClass(RC) && isDivergent)
11556     return TRI->getEquivalentVGPRClass(RC);
11557 
11558   return RC;
11559 }
11560 
11561 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11562 // uniform values (as produced by the mask results of control flow intrinsics)
11563 // used outside of divergent blocks. The phi users need to also be treated as
11564 // always uniform.
11565 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11566                       unsigned WaveSize) {
11567   // FIXME: We asssume we never cast the mask results of a control flow
11568   // intrinsic.
11569   // Early exit if the type won't be consistent as a compile time hack.
11570   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11571   if (!IT || IT->getBitWidth() != WaveSize)
11572     return false;
11573 
11574   if (!isa<Instruction>(V))
11575     return false;
11576   if (!Visited.insert(V).second)
11577     return false;
11578   bool Result = false;
11579   for (auto U : V->users()) {
11580     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11581       if (V == U->getOperand(1)) {
11582         switch (Intrinsic->getIntrinsicID()) {
11583         default:
11584           Result = false;
11585           break;
11586         case Intrinsic::amdgcn_if_break:
11587         case Intrinsic::amdgcn_if:
11588         case Intrinsic::amdgcn_else:
11589           Result = true;
11590           break;
11591         }
11592       }
11593       if (V == U->getOperand(0)) {
11594         switch (Intrinsic->getIntrinsicID()) {
11595         default:
11596           Result = false;
11597           break;
11598         case Intrinsic::amdgcn_end_cf:
11599         case Intrinsic::amdgcn_loop:
11600           Result = true;
11601           break;
11602         }
11603       }
11604     } else {
11605       Result = hasCFUser(U, Visited, WaveSize);
11606     }
11607     if (Result)
11608       break;
11609   }
11610   return Result;
11611 }
11612 
11613 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11614                                                const Value *V) const {
11615   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11616     if (CI->isInlineAsm()) {
11617       // FIXME: This cannot give a correct answer. This should only trigger in
11618       // the case where inline asm returns mixed SGPR and VGPR results, used
11619       // outside the defining block. We don't have a specific result to
11620       // consider, so this assumes if any value is SGPR, the overall register
11621       // also needs to be SGPR.
11622       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11623       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11624           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11625       for (auto &TC : TargetConstraints) {
11626         if (TC.Type == InlineAsm::isOutput) {
11627           ComputeConstraintToUse(TC, SDValue());
11628           unsigned AssignedReg;
11629           const TargetRegisterClass *RC;
11630           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11631               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11632           if (RC) {
11633             MachineRegisterInfo &MRI = MF.getRegInfo();
11634             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11635               return true;
11636             else if (SIRI->isSGPRClass(RC))
11637               return true;
11638           }
11639         }
11640       }
11641     }
11642   }
11643   SmallPtrSet<const Value *, 16> Visited;
11644   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11645 }
11646 
11647 std::pair<int, MVT>
11648 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11649                                           Type *Ty) const {
11650   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11651   auto Size = DL.getTypeSizeInBits(Ty);
11652   // Maximum load or store can handle 8 dwords for scalar and 4 for
11653   // vector ALU. Let's assume anything above 8 dwords is expensive
11654   // even if legal.
11655   if (Size <= 256)
11656     return Cost;
11657 
11658   Cost.first = (Size + 255) / 256;
11659   return Cost;
11660 }
11661