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 = ISD::INTRINSIC_W_CHAIN;
1086       Info.memVT = MVT::getVT(CI.getType());
1087       Info.flags = MachineMemOperand::MOLoad |
1088                    MachineMemOperand::MOStore |
1089                    MachineMemOperand::MODereferenceable;
1090 
1091       // XXX - Should this be volatile without known ordering?
1092       Info.flags |= MachineMemOperand::MOVolatile;
1093     }
1094     return true;
1095   }
1096 
1097   switch (IntrID) {
1098   case Intrinsic::amdgcn_atomic_inc:
1099   case Intrinsic::amdgcn_atomic_dec:
1100   case Intrinsic::amdgcn_ds_ordered_add:
1101   case Intrinsic::amdgcn_ds_ordered_swap:
1102   case Intrinsic::amdgcn_ds_fadd:
1103   case Intrinsic::amdgcn_ds_fmin:
1104   case Intrinsic::amdgcn_ds_fmax: {
1105     Info.opc = ISD::INTRINSIC_W_CHAIN;
1106     Info.memVT = MVT::getVT(CI.getType());
1107     Info.ptrVal = CI.getOperand(0);
1108     Info.align.reset();
1109     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1110 
1111     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1112     if (!Vol->isZero())
1113       Info.flags |= MachineMemOperand::MOVolatile;
1114 
1115     return true;
1116   }
1117   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1118     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1119 
1120     Info.opc = ISD::INTRINSIC_VOID;
1121     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1122     Info.ptrVal = MFI->getBufferPSV(
1123       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1124       CI.getArgOperand(1));
1125     Info.align.reset();
1126     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1127 
1128     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1129     if (!Vol || !Vol->isZero())
1130       Info.flags |= MachineMemOperand::MOVolatile;
1131 
1132     return true;
1133   }
1134   case Intrinsic::amdgcn_global_atomic_fadd: {
1135     Info.opc = ISD::INTRINSIC_VOID;
1136     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1137                             ->getPointerElementType());
1138     Info.ptrVal = CI.getOperand(0);
1139     Info.align.reset();
1140     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1141 
1142     return true;
1143   }
1144   case Intrinsic::amdgcn_ds_append:
1145   case Intrinsic::amdgcn_ds_consume: {
1146     Info.opc = ISD::INTRINSIC_W_CHAIN;
1147     Info.memVT = MVT::getVT(CI.getType());
1148     Info.ptrVal = CI.getOperand(0);
1149     Info.align.reset();
1150     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1151 
1152     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1153     if (!Vol->isZero())
1154       Info.flags |= MachineMemOperand::MOVolatile;
1155 
1156     return true;
1157   }
1158   case Intrinsic::amdgcn_global_atomic_csub: {
1159     Info.opc = ISD::INTRINSIC_W_CHAIN;
1160     Info.memVT = MVT::getVT(CI.getType());
1161     Info.ptrVal = CI.getOperand(0);
1162     Info.align.reset();
1163     Info.flags = MachineMemOperand::MOLoad |
1164                  MachineMemOperand::MOStore |
1165                  MachineMemOperand::MOVolatile;
1166     return true;
1167   }
1168   case Intrinsic::amdgcn_ds_gws_init:
1169   case Intrinsic::amdgcn_ds_gws_barrier:
1170   case Intrinsic::amdgcn_ds_gws_sema_v:
1171   case Intrinsic::amdgcn_ds_gws_sema_br:
1172   case Intrinsic::amdgcn_ds_gws_sema_p:
1173   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1174     Info.opc = ISD::INTRINSIC_VOID;
1175 
1176     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1177     Info.ptrVal =
1178         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1179 
1180     // This is an abstract access, but we need to specify a type and size.
1181     Info.memVT = MVT::i32;
1182     Info.size = 4;
1183     Info.align = Align(4);
1184 
1185     Info.flags = MachineMemOperand::MOStore;
1186     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1187       Info.flags = MachineMemOperand::MOLoad;
1188     return true;
1189   }
1190   default:
1191     return false;
1192   }
1193 }
1194 
1195 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1196                                             SmallVectorImpl<Value*> &Ops,
1197                                             Type *&AccessTy) const {
1198   switch (II->getIntrinsicID()) {
1199   case Intrinsic::amdgcn_atomic_inc:
1200   case Intrinsic::amdgcn_atomic_dec:
1201   case Intrinsic::amdgcn_ds_ordered_add:
1202   case Intrinsic::amdgcn_ds_ordered_swap:
1203   case Intrinsic::amdgcn_ds_append:
1204   case Intrinsic::amdgcn_ds_consume:
1205   case Intrinsic::amdgcn_ds_fadd:
1206   case Intrinsic::amdgcn_ds_fmin:
1207   case Intrinsic::amdgcn_ds_fmax:
1208   case Intrinsic::amdgcn_global_atomic_fadd:
1209   case Intrinsic::amdgcn_global_atomic_csub: {
1210     Value *Ptr = II->getArgOperand(0);
1211     AccessTy = II->getType();
1212     Ops.push_back(Ptr);
1213     return true;
1214   }
1215   default:
1216     return false;
1217   }
1218 }
1219 
1220 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1221   if (!Subtarget->hasFlatInstOffsets()) {
1222     // Flat instructions do not have offsets, and only have the register
1223     // address.
1224     return AM.BaseOffs == 0 && AM.Scale == 0;
1225   }
1226 
1227   return AM.Scale == 0 &&
1228          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1229                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1230                                   /*Signed=*/false));
1231 }
1232 
1233 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1234   if (Subtarget->hasFlatGlobalInsts())
1235     return AM.Scale == 0 &&
1236            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1237                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1238                                     /*Signed=*/true));
1239 
1240   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1241       // Assume the we will use FLAT for all global memory accesses
1242       // on VI.
1243       // FIXME: This assumption is currently wrong.  On VI we still use
1244       // MUBUF instructions for the r + i addressing mode.  As currently
1245       // implemented, the MUBUF instructions only work on buffer < 4GB.
1246       // It may be possible to support > 4GB buffers with MUBUF instructions,
1247       // by setting the stride value in the resource descriptor which would
1248       // increase the size limit to (stride * 4GB).  However, this is risky,
1249       // because it has never been validated.
1250     return isLegalFlatAddressingMode(AM);
1251   }
1252 
1253   return isLegalMUBUFAddressingMode(AM);
1254 }
1255 
1256 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1257   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1258   // additionally can do r + r + i with addr64. 32-bit has more addressing
1259   // mode options. Depending on the resource constant, it can also do
1260   // (i64 r0) + (i32 r1) * (i14 i).
1261   //
1262   // Private arrays end up using a scratch buffer most of the time, so also
1263   // assume those use MUBUF instructions. Scratch loads / stores are currently
1264   // implemented as mubuf instructions with offen bit set, so slightly
1265   // different than the normal addr64.
1266   if (!isUInt<12>(AM.BaseOffs))
1267     return false;
1268 
1269   // FIXME: Since we can split immediate into soffset and immediate offset,
1270   // would it make sense to allow any immediate?
1271 
1272   switch (AM.Scale) {
1273   case 0: // r + i or just i, depending on HasBaseReg.
1274     return true;
1275   case 1:
1276     return true; // We have r + r or r + i.
1277   case 2:
1278     if (AM.HasBaseReg) {
1279       // Reject 2 * r + r.
1280       return false;
1281     }
1282 
1283     // Allow 2 * r as r + r
1284     // Or  2 * r + i is allowed as r + r + i.
1285     return true;
1286   default: // Don't allow n * r
1287     return false;
1288   }
1289 }
1290 
1291 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1292                                              const AddrMode &AM, Type *Ty,
1293                                              unsigned AS, Instruction *I) const {
1294   // No global is ever allowed as a base.
1295   if (AM.BaseGV)
1296     return false;
1297 
1298   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1299     return isLegalGlobalAddressingMode(AM);
1300 
1301   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1302       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1303       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1304     // If the offset isn't a multiple of 4, it probably isn't going to be
1305     // correctly aligned.
1306     // FIXME: Can we get the real alignment here?
1307     if (AM.BaseOffs % 4 != 0)
1308       return isLegalMUBUFAddressingMode(AM);
1309 
1310     // There are no SMRD extloads, so if we have to do a small type access we
1311     // will use a MUBUF load.
1312     // FIXME?: We also need to do this if unaligned, but we don't know the
1313     // alignment here.
1314     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1315       return isLegalGlobalAddressingMode(AM);
1316 
1317     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1318       // SMRD instructions have an 8-bit, dword offset on SI.
1319       if (!isUInt<8>(AM.BaseOffs / 4))
1320         return false;
1321     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1322       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1323       // in 8-bits, it can use a smaller encoding.
1324       if (!isUInt<32>(AM.BaseOffs / 4))
1325         return false;
1326     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1327       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1328       if (!isUInt<20>(AM.BaseOffs))
1329         return false;
1330     } else
1331       llvm_unreachable("unhandled generation");
1332 
1333     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1334       return true;
1335 
1336     if (AM.Scale == 1 && AM.HasBaseReg)
1337       return true;
1338 
1339     return false;
1340 
1341   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1342     return isLegalMUBUFAddressingMode(AM);
1343   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1344              AS == AMDGPUAS::REGION_ADDRESS) {
1345     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1346     // field.
1347     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1348     // an 8-bit dword offset but we don't know the alignment here.
1349     if (!isUInt<16>(AM.BaseOffs))
1350       return false;
1351 
1352     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1353       return true;
1354 
1355     if (AM.Scale == 1 && AM.HasBaseReg)
1356       return true;
1357 
1358     return false;
1359   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1360              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1361     // For an unknown address space, this usually means that this is for some
1362     // reason being used for pure arithmetic, and not based on some addressing
1363     // computation. We don't have instructions that compute pointers with any
1364     // addressing modes, so treat them as having no offset like flat
1365     // instructions.
1366     return isLegalFlatAddressingMode(AM);
1367   }
1368 
1369   // Assume a user alias of global for unknown address spaces.
1370   return isLegalGlobalAddressingMode(AM);
1371 }
1372 
1373 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1374                                         const SelectionDAG &DAG) const {
1375   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1376     return (MemVT.getSizeInBits() <= 4 * 32);
1377   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1378     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1379     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1380   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1381     return (MemVT.getSizeInBits() <= 2 * 32);
1382   }
1383   return true;
1384 }
1385 
1386 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1387     unsigned Size, unsigned AddrSpace, unsigned Align,
1388     MachineMemOperand::Flags Flags, bool *IsFast) const {
1389   if (IsFast)
1390     *IsFast = false;
1391 
1392   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1393       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1394     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1395     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1396     // with adjacent offsets.
1397     bool AlignedBy4 = (Align % 4 == 0);
1398     if (IsFast)
1399       *IsFast = AlignedBy4;
1400 
1401     return AlignedBy4;
1402   }
1403 
1404   // FIXME: We have to be conservative here and assume that flat operations
1405   // will access scratch.  If we had access to the IR function, then we
1406   // could determine if any private memory was used in the function.
1407   if (!Subtarget->hasUnalignedScratchAccess() &&
1408       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1409        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1410     bool AlignedBy4 = Align >= 4;
1411     if (IsFast)
1412       *IsFast = AlignedBy4;
1413 
1414     return AlignedBy4;
1415   }
1416 
1417   if (Subtarget->hasUnalignedBufferAccess()) {
1418     // If we have an uniform constant load, it still requires using a slow
1419     // buffer instruction if unaligned.
1420     if (IsFast) {
1421       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1422       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1423       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1424                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1425         Align >= 4 : Align != 2;
1426     }
1427 
1428     return true;
1429   }
1430 
1431   // Smaller than dword value must be aligned.
1432   if (Size < 32)
1433     return false;
1434 
1435   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1436   // byte-address are ignored, thus forcing Dword alignment.
1437   // This applies to private, global, and constant memory.
1438   if (IsFast)
1439     *IsFast = true;
1440 
1441   return Size >= 32 && Align >= 4;
1442 }
1443 
1444 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1445     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1446     bool *IsFast) const {
1447   if (IsFast)
1448     *IsFast = false;
1449 
1450   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1451   // which isn't a simple VT.
1452   // Until MVT is extended to handle this, simply check for the size and
1453   // rely on the condition below: allow accesses if the size is a multiple of 4.
1454   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1455                            VT.getStoreSize() > 16)) {
1456     return false;
1457   }
1458 
1459   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1460                                             Align, Flags, IsFast);
1461 }
1462 
1463 EVT SITargetLowering::getOptimalMemOpType(
1464     const MemOp &Op, const AttributeList &FuncAttributes) const {
1465   // FIXME: Should account for address space here.
1466 
1467   // The default fallback uses the private pointer size as a guess for a type to
1468   // use. Make sure we switch these to 64-bit accesses.
1469 
1470   if (Op.size() >= 16 &&
1471       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1472     return MVT::v4i32;
1473 
1474   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1475     return MVT::v2i32;
1476 
1477   // Use the default.
1478   return MVT::Other;
1479 }
1480 
1481 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1482                                            unsigned DestAS) const {
1483   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1484 }
1485 
1486 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1487   const MemSDNode *MemNode = cast<MemSDNode>(N);
1488   const Value *Ptr = MemNode->getMemOperand()->getValue();
1489   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1490   return I && I->getMetadata("amdgpu.noclobber");
1491 }
1492 
1493 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1494                                            unsigned DestAS) const {
1495   // Flat -> private/local is a simple truncate.
1496   // Flat -> global is no-op
1497   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1498     return true;
1499 
1500   return isNoopAddrSpaceCast(SrcAS, DestAS);
1501 }
1502 
1503 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1504   const MemSDNode *MemNode = cast<MemSDNode>(N);
1505 
1506   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1507 }
1508 
1509 TargetLoweringBase::LegalizeTypeAction
1510 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1511   int NumElts = VT.getVectorNumElements();
1512   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1513     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1514   return TargetLoweringBase::getPreferredVectorAction(VT);
1515 }
1516 
1517 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1518                                                          Type *Ty) const {
1519   // FIXME: Could be smarter if called for vector constants.
1520   return true;
1521 }
1522 
1523 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1524   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1525     switch (Op) {
1526     case ISD::LOAD:
1527     case ISD::STORE:
1528 
1529     // These operations are done with 32-bit instructions anyway.
1530     case ISD::AND:
1531     case ISD::OR:
1532     case ISD::XOR:
1533     case ISD::SELECT:
1534       // TODO: Extensions?
1535       return true;
1536     default:
1537       return false;
1538     }
1539   }
1540 
1541   // SimplifySetCC uses this function to determine whether or not it should
1542   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1543   if (VT == MVT::i1 && Op == ISD::SETCC)
1544     return false;
1545 
1546   return TargetLowering::isTypeDesirableForOp(Op, VT);
1547 }
1548 
1549 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1550                                                    const SDLoc &SL,
1551                                                    SDValue Chain,
1552                                                    uint64_t Offset) const {
1553   const DataLayout &DL = DAG.getDataLayout();
1554   MachineFunction &MF = DAG.getMachineFunction();
1555   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1556 
1557   const ArgDescriptor *InputPtrReg;
1558   const TargetRegisterClass *RC;
1559   LLT ArgTy;
1560 
1561   std::tie(InputPtrReg, RC, ArgTy) =
1562       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1563 
1564   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1565   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1566   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1567     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1568 
1569   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1570 }
1571 
1572 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1573                                             const SDLoc &SL) const {
1574   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1575                                                FIRST_IMPLICIT);
1576   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1577 }
1578 
1579 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1580                                          const SDLoc &SL, SDValue Val,
1581                                          bool Signed,
1582                                          const ISD::InputArg *Arg) const {
1583   // First, if it is a widened vector, narrow it.
1584   if (VT.isVector() &&
1585       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1586     EVT NarrowedVT =
1587         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1588                          VT.getVectorNumElements());
1589     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1590                       DAG.getConstant(0, SL, MVT::i32));
1591   }
1592 
1593   // Then convert the vector elements or scalar value.
1594   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1595       VT.bitsLT(MemVT)) {
1596     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1597     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1598   }
1599 
1600   if (MemVT.isFloatingPoint())
1601     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1602   else if (Signed)
1603     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1604   else
1605     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1606 
1607   return Val;
1608 }
1609 
1610 SDValue SITargetLowering::lowerKernargMemParameter(
1611     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1612     uint64_t Offset, Align Alignment, bool Signed,
1613     const ISD::InputArg *Arg) const {
1614   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1615 
1616   // Try to avoid using an extload by loading earlier than the argument address,
1617   // and extracting the relevant bits. The load should hopefully be merged with
1618   // the previous argument.
1619   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1620     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1621     int64_t AlignDownOffset = alignDown(Offset, 4);
1622     int64_t OffsetDiff = Offset - AlignDownOffset;
1623 
1624     EVT IntVT = MemVT.changeTypeToInteger();
1625 
1626     // TODO: If we passed in the base kernel offset we could have a better
1627     // alignment than 4, but we don't really need it.
1628     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1629     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1630                                MachineMemOperand::MODereferenceable |
1631                                MachineMemOperand::MOInvariant);
1632 
1633     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1634     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1635 
1636     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1637     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1638     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1639 
1640 
1641     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1642   }
1643 
1644   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1645   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1646                              MachineMemOperand::MODereferenceable |
1647                                  MachineMemOperand::MOInvariant);
1648 
1649   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1650   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1651 }
1652 
1653 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1654                                               const SDLoc &SL, SDValue Chain,
1655                                               const ISD::InputArg &Arg) const {
1656   MachineFunction &MF = DAG.getMachineFunction();
1657   MachineFrameInfo &MFI = MF.getFrameInfo();
1658 
1659   if (Arg.Flags.isByVal()) {
1660     unsigned Size = Arg.Flags.getByValSize();
1661     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1662     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1663   }
1664 
1665   unsigned ArgOffset = VA.getLocMemOffset();
1666   unsigned ArgSize = VA.getValVT().getStoreSize();
1667 
1668   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1669 
1670   // Create load nodes to retrieve arguments from the stack.
1671   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1672   SDValue ArgValue;
1673 
1674   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1675   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1676   MVT MemVT = VA.getValVT();
1677 
1678   switch (VA.getLocInfo()) {
1679   default:
1680     break;
1681   case CCValAssign::BCvt:
1682     MemVT = VA.getLocVT();
1683     break;
1684   case CCValAssign::SExt:
1685     ExtType = ISD::SEXTLOAD;
1686     break;
1687   case CCValAssign::ZExt:
1688     ExtType = ISD::ZEXTLOAD;
1689     break;
1690   case CCValAssign::AExt:
1691     ExtType = ISD::EXTLOAD;
1692     break;
1693   }
1694 
1695   ArgValue = DAG.getExtLoad(
1696     ExtType, SL, VA.getLocVT(), Chain, FIN,
1697     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1698     MemVT);
1699   return ArgValue;
1700 }
1701 
1702 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1703   const SIMachineFunctionInfo &MFI,
1704   EVT VT,
1705   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1706   const ArgDescriptor *Reg;
1707   const TargetRegisterClass *RC;
1708   LLT Ty;
1709 
1710   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1711   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1712 }
1713 
1714 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1715                                    CallingConv::ID CallConv,
1716                                    ArrayRef<ISD::InputArg> Ins,
1717                                    BitVector &Skipped,
1718                                    FunctionType *FType,
1719                                    SIMachineFunctionInfo *Info) {
1720   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1721     const ISD::InputArg *Arg = &Ins[I];
1722 
1723     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1724            "vector type argument should have been split");
1725 
1726     // First check if it's a PS input addr.
1727     if (CallConv == CallingConv::AMDGPU_PS &&
1728         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1729       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1730 
1731       // Inconveniently only the first part of the split is marked as isSplit,
1732       // so skip to the end. We only want to increment PSInputNum once for the
1733       // entire split argument.
1734       if (Arg->Flags.isSplit()) {
1735         while (!Arg->Flags.isSplitEnd()) {
1736           assert((!Arg->VT.isVector() ||
1737                   Arg->VT.getScalarSizeInBits() == 16) &&
1738                  "unexpected vector split in ps argument type");
1739           if (!SkipArg)
1740             Splits.push_back(*Arg);
1741           Arg = &Ins[++I];
1742         }
1743       }
1744 
1745       if (SkipArg) {
1746         // We can safely skip PS inputs.
1747         Skipped.set(Arg->getOrigArgIndex());
1748         ++PSInputNum;
1749         continue;
1750       }
1751 
1752       Info->markPSInputAllocated(PSInputNum);
1753       if (Arg->Used)
1754         Info->markPSInputEnabled(PSInputNum);
1755 
1756       ++PSInputNum;
1757     }
1758 
1759     Splits.push_back(*Arg);
1760   }
1761 }
1762 
1763 // Allocate special inputs passed in VGPRs.
1764 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1765                                                       MachineFunction &MF,
1766                                                       const SIRegisterInfo &TRI,
1767                                                       SIMachineFunctionInfo &Info) const {
1768   const LLT S32 = LLT::scalar(32);
1769   MachineRegisterInfo &MRI = MF.getRegInfo();
1770 
1771   if (Info.hasWorkItemIDX()) {
1772     Register Reg = AMDGPU::VGPR0;
1773     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1774 
1775     CCInfo.AllocateReg(Reg);
1776     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1777   }
1778 
1779   if (Info.hasWorkItemIDY()) {
1780     Register Reg = AMDGPU::VGPR1;
1781     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1782 
1783     CCInfo.AllocateReg(Reg);
1784     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1785   }
1786 
1787   if (Info.hasWorkItemIDZ()) {
1788     Register Reg = AMDGPU::VGPR2;
1789     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1790 
1791     CCInfo.AllocateReg(Reg);
1792     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1793   }
1794 }
1795 
1796 // Try to allocate a VGPR at the end of the argument list, or if no argument
1797 // VGPRs are left allocating a stack slot.
1798 // If \p Mask is is given it indicates bitfield position in the register.
1799 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1800 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1801                                          ArgDescriptor Arg = ArgDescriptor()) {
1802   if (Arg.isSet())
1803     return ArgDescriptor::createArg(Arg, Mask);
1804 
1805   ArrayRef<MCPhysReg> ArgVGPRs
1806     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1807   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1808   if (RegIdx == ArgVGPRs.size()) {
1809     // Spill to stack required.
1810     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1811 
1812     return ArgDescriptor::createStack(Offset, Mask);
1813   }
1814 
1815   unsigned Reg = ArgVGPRs[RegIdx];
1816   Reg = CCInfo.AllocateReg(Reg);
1817   assert(Reg != AMDGPU::NoRegister);
1818 
1819   MachineFunction &MF = CCInfo.getMachineFunction();
1820   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1821   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1822   return ArgDescriptor::createRegister(Reg, Mask);
1823 }
1824 
1825 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1826                                              const TargetRegisterClass *RC,
1827                                              unsigned NumArgRegs) {
1828   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1829   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1830   if (RegIdx == ArgSGPRs.size())
1831     report_fatal_error("ran out of SGPRs for arguments");
1832 
1833   unsigned Reg = ArgSGPRs[RegIdx];
1834   Reg = CCInfo.AllocateReg(Reg);
1835   assert(Reg != AMDGPU::NoRegister);
1836 
1837   MachineFunction &MF = CCInfo.getMachineFunction();
1838   MF.addLiveIn(Reg, RC);
1839   return ArgDescriptor::createRegister(Reg);
1840 }
1841 
1842 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1843   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1844 }
1845 
1846 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1847   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1848 }
1849 
1850 /// Allocate implicit function VGPR arguments at the end of allocated user
1851 /// arguments.
1852 void SITargetLowering::allocateSpecialInputVGPRs(
1853   CCState &CCInfo, MachineFunction &MF,
1854   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1855   const unsigned Mask = 0x3ff;
1856   ArgDescriptor Arg;
1857 
1858   if (Info.hasWorkItemIDX()) {
1859     Arg = allocateVGPR32Input(CCInfo, Mask);
1860     Info.setWorkItemIDX(Arg);
1861   }
1862 
1863   if (Info.hasWorkItemIDY()) {
1864     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1865     Info.setWorkItemIDY(Arg);
1866   }
1867 
1868   if (Info.hasWorkItemIDZ())
1869     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1870 }
1871 
1872 /// Allocate implicit function VGPR arguments in fixed registers.
1873 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1874   CCState &CCInfo, MachineFunction &MF,
1875   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1876   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1877   if (!Reg)
1878     report_fatal_error("failed to allocated VGPR for implicit arguments");
1879 
1880   const unsigned Mask = 0x3ff;
1881   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1882   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1883   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1884 }
1885 
1886 void SITargetLowering::allocateSpecialInputSGPRs(
1887   CCState &CCInfo,
1888   MachineFunction &MF,
1889   const SIRegisterInfo &TRI,
1890   SIMachineFunctionInfo &Info) const {
1891   auto &ArgInfo = Info.getArgInfo();
1892 
1893   // TODO: Unify handling with private memory pointers.
1894 
1895   if (Info.hasDispatchPtr())
1896     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1897 
1898   if (Info.hasQueuePtr())
1899     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1900 
1901   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1902   // constant offset from the kernarg segment.
1903   if (Info.hasImplicitArgPtr())
1904     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1905 
1906   if (Info.hasDispatchID())
1907     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1908 
1909   // flat_scratch_init is not applicable for non-kernel functions.
1910 
1911   if (Info.hasWorkGroupIDX())
1912     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1913 
1914   if (Info.hasWorkGroupIDY())
1915     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1916 
1917   if (Info.hasWorkGroupIDZ())
1918     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1919 }
1920 
1921 // Allocate special inputs passed in user SGPRs.
1922 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1923                                             MachineFunction &MF,
1924                                             const SIRegisterInfo &TRI,
1925                                             SIMachineFunctionInfo &Info) const {
1926   if (Info.hasImplicitBufferPtr()) {
1927     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1928     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1929     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1930   }
1931 
1932   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1933   if (Info.hasPrivateSegmentBuffer()) {
1934     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1935     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1936     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1937   }
1938 
1939   if (Info.hasDispatchPtr()) {
1940     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1941     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1942     CCInfo.AllocateReg(DispatchPtrReg);
1943   }
1944 
1945   if (Info.hasQueuePtr()) {
1946     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1947     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1948     CCInfo.AllocateReg(QueuePtrReg);
1949   }
1950 
1951   if (Info.hasKernargSegmentPtr()) {
1952     MachineRegisterInfo &MRI = MF.getRegInfo();
1953     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1954     CCInfo.AllocateReg(InputPtrReg);
1955 
1956     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1957     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1958   }
1959 
1960   if (Info.hasDispatchID()) {
1961     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1962     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1963     CCInfo.AllocateReg(DispatchIDReg);
1964   }
1965 
1966   if (Info.hasFlatScratchInit()) {
1967     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1968     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1969     CCInfo.AllocateReg(FlatScratchInitReg);
1970   }
1971 
1972   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1973   // these from the dispatch pointer.
1974 }
1975 
1976 // Allocate special input registers that are initialized per-wave.
1977 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1978                                            MachineFunction &MF,
1979                                            SIMachineFunctionInfo &Info,
1980                                            CallingConv::ID CallConv,
1981                                            bool IsShader) const {
1982   if (Info.hasWorkGroupIDX()) {
1983     unsigned Reg = Info.addWorkGroupIDX();
1984     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1985     CCInfo.AllocateReg(Reg);
1986   }
1987 
1988   if (Info.hasWorkGroupIDY()) {
1989     unsigned Reg = Info.addWorkGroupIDY();
1990     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1991     CCInfo.AllocateReg(Reg);
1992   }
1993 
1994   if (Info.hasWorkGroupIDZ()) {
1995     unsigned Reg = Info.addWorkGroupIDZ();
1996     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1997     CCInfo.AllocateReg(Reg);
1998   }
1999 
2000   if (Info.hasWorkGroupInfo()) {
2001     unsigned Reg = Info.addWorkGroupInfo();
2002     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2003     CCInfo.AllocateReg(Reg);
2004   }
2005 
2006   if (Info.hasPrivateSegmentWaveByteOffset()) {
2007     // Scratch wave offset passed in system SGPR.
2008     unsigned PrivateSegmentWaveByteOffsetReg;
2009 
2010     if (IsShader) {
2011       PrivateSegmentWaveByteOffsetReg =
2012         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2013 
2014       // This is true if the scratch wave byte offset doesn't have a fixed
2015       // location.
2016       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2017         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2018         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2019       }
2020     } else
2021       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2022 
2023     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2024     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2025   }
2026 }
2027 
2028 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2029                                      MachineFunction &MF,
2030                                      const SIRegisterInfo &TRI,
2031                                      SIMachineFunctionInfo &Info) {
2032   // Now that we've figured out where the scratch register inputs are, see if
2033   // should reserve the arguments and use them directly.
2034   MachineFrameInfo &MFI = MF.getFrameInfo();
2035   bool HasStackObjects = MFI.hasStackObjects();
2036   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2037 
2038   // Record that we know we have non-spill stack objects so we don't need to
2039   // check all stack objects later.
2040   if (HasStackObjects)
2041     Info.setHasNonSpillStackObjects(true);
2042 
2043   // Everything live out of a block is spilled with fast regalloc, so it's
2044   // almost certain that spilling will be required.
2045   if (TM.getOptLevel() == CodeGenOpt::None)
2046     HasStackObjects = true;
2047 
2048   // For now assume stack access is needed in any callee functions, so we need
2049   // the scratch registers to pass in.
2050   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2051 
2052   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2053     // If we have stack objects, we unquestionably need the private buffer
2054     // resource. For the Code Object V2 ABI, this will be the first 4 user
2055     // SGPR inputs. We can reserve those and use them directly.
2056 
2057     Register PrivateSegmentBufferReg =
2058         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2059     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2060   } else {
2061     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2062     // We tentatively reserve the last registers (skipping the last registers
2063     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2064     // we'll replace these with the ones immediately after those which were
2065     // really allocated. In the prologue copies will be inserted from the
2066     // argument to these reserved registers.
2067 
2068     // Without HSA, relocations are used for the scratch pointer and the
2069     // buffer resource setup is always inserted in the prologue. Scratch wave
2070     // offset is still in an input SGPR.
2071     Info.setScratchRSrcReg(ReservedBufferReg);
2072   }
2073 
2074   MachineRegisterInfo &MRI = MF.getRegInfo();
2075 
2076   // For entry functions we have to set up the stack pointer if we use it,
2077   // whereas non-entry functions get this "for free". This means there is no
2078   // intrinsic advantage to using S32 over S34 in cases where we do not have
2079   // calls but do need a frame pointer (i.e. if we are requested to have one
2080   // because frame pointer elimination is disabled). To keep things simple we
2081   // only ever use S32 as the call ABI stack pointer, and so using it does not
2082   // imply we need a separate frame pointer.
2083   //
2084   // Try to use s32 as the SP, but move it if it would interfere with input
2085   // arguments. This won't work with calls though.
2086   //
2087   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2088   // registers.
2089   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2090     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2091   } else {
2092     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2093 
2094     if (MFI.hasCalls())
2095       report_fatal_error("call in graphics shader with too many input SGPRs");
2096 
2097     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2098       if (!MRI.isLiveIn(Reg)) {
2099         Info.setStackPtrOffsetReg(Reg);
2100         break;
2101       }
2102     }
2103 
2104     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2105       report_fatal_error("failed to find register for SP");
2106   }
2107 
2108   // hasFP should be accurate for entry functions even before the frame is
2109   // finalized, because it does not rely on the known stack size, only
2110   // properties like whether variable sized objects are present.
2111   if (ST.getFrameLowering()->hasFP(MF)) {
2112     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2113   }
2114 }
2115 
2116 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2117   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2118   return !Info->isEntryFunction();
2119 }
2120 
2121 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2122 
2123 }
2124 
2125 void SITargetLowering::insertCopiesSplitCSR(
2126   MachineBasicBlock *Entry,
2127   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2128   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2129 
2130   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2131   if (!IStart)
2132     return;
2133 
2134   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2135   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2136   MachineBasicBlock::iterator MBBI = Entry->begin();
2137   for (const MCPhysReg *I = IStart; *I; ++I) {
2138     const TargetRegisterClass *RC = nullptr;
2139     if (AMDGPU::SReg_64RegClass.contains(*I))
2140       RC = &AMDGPU::SGPR_64RegClass;
2141     else if (AMDGPU::SReg_32RegClass.contains(*I))
2142       RC = &AMDGPU::SGPR_32RegClass;
2143     else
2144       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2145 
2146     Register NewVR = MRI->createVirtualRegister(RC);
2147     // Create copy from CSR to a virtual register.
2148     Entry->addLiveIn(*I);
2149     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2150       .addReg(*I);
2151 
2152     // Insert the copy-back instructions right before the terminator.
2153     for (auto *Exit : Exits)
2154       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2155               TII->get(TargetOpcode::COPY), *I)
2156         .addReg(NewVR);
2157   }
2158 }
2159 
2160 SDValue SITargetLowering::LowerFormalArguments(
2161     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2162     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2163     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2164   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2165 
2166   MachineFunction &MF = DAG.getMachineFunction();
2167   const Function &Fn = MF.getFunction();
2168   FunctionType *FType = MF.getFunction().getFunctionType();
2169   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2170 
2171   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2172     DiagnosticInfoUnsupported NoGraphicsHSA(
2173         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2174     DAG.getContext()->diagnose(NoGraphicsHSA);
2175     return DAG.getEntryNode();
2176   }
2177 
2178   SmallVector<ISD::InputArg, 16> Splits;
2179   SmallVector<CCValAssign, 16> ArgLocs;
2180   BitVector Skipped(Ins.size());
2181   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2182                  *DAG.getContext());
2183 
2184   bool IsShader = AMDGPU::isShader(CallConv);
2185   bool IsKernel = AMDGPU::isKernel(CallConv);
2186   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2187 
2188   if (IsShader) {
2189     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2190 
2191     // At least one interpolation mode must be enabled or else the GPU will
2192     // hang.
2193     //
2194     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2195     // set PSInputAddr, the user wants to enable some bits after the compilation
2196     // based on run-time states. Since we can't know what the final PSInputEna
2197     // will look like, so we shouldn't do anything here and the user should take
2198     // responsibility for the correct programming.
2199     //
2200     // Otherwise, the following restrictions apply:
2201     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2202     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2203     //   enabled too.
2204     if (CallConv == CallingConv::AMDGPU_PS) {
2205       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2206            ((Info->getPSInputAddr() & 0xF) == 0 &&
2207             Info->isPSInputAllocated(11))) {
2208         CCInfo.AllocateReg(AMDGPU::VGPR0);
2209         CCInfo.AllocateReg(AMDGPU::VGPR1);
2210         Info->markPSInputAllocated(0);
2211         Info->markPSInputEnabled(0);
2212       }
2213       if (Subtarget->isAmdPalOS()) {
2214         // For isAmdPalOS, the user does not enable some bits after compilation
2215         // based on run-time states; the register values being generated here are
2216         // the final ones set in hardware. Therefore we need to apply the
2217         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2218         // a bit is set in PSInputAddr but not PSInputEnable is where the
2219         // frontend set up an input arg for a particular interpolation mode, but
2220         // nothing uses that input arg. Really we should have an earlier pass
2221         // that removes such an arg.)
2222         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2223         if ((PsInputBits & 0x7F) == 0 ||
2224             ((PsInputBits & 0xF) == 0 &&
2225              (PsInputBits >> 11 & 1)))
2226           Info->markPSInputEnabled(
2227               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2228       }
2229     }
2230 
2231     assert(!Info->hasDispatchPtr() &&
2232            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2233            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2234            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2235            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2236            !Info->hasWorkItemIDZ());
2237   } else if (IsKernel) {
2238     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2239   } else {
2240     Splits.append(Ins.begin(), Ins.end());
2241   }
2242 
2243   if (IsEntryFunc) {
2244     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2245     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2246   } else {
2247     // For the fixed ABI, pass workitem IDs in the last argument register.
2248     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2249       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2250   }
2251 
2252   if (IsKernel) {
2253     analyzeFormalArgumentsCompute(CCInfo, Ins);
2254   } else {
2255     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2256     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2257   }
2258 
2259   SmallVector<SDValue, 16> Chains;
2260 
2261   // FIXME: This is the minimum kernel argument alignment. We should improve
2262   // this to the maximum alignment of the arguments.
2263   //
2264   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2265   // kern arg offset.
2266   const Align KernelArgBaseAlign = Align(16);
2267 
2268   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2269     const ISD::InputArg &Arg = Ins[i];
2270     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2271       InVals.push_back(DAG.getUNDEF(Arg.VT));
2272       continue;
2273     }
2274 
2275     CCValAssign &VA = ArgLocs[ArgIdx++];
2276     MVT VT = VA.getLocVT();
2277 
2278     if (IsEntryFunc && VA.isMemLoc()) {
2279       VT = Ins[i].VT;
2280       EVT MemVT = VA.getLocVT();
2281 
2282       const uint64_t Offset = VA.getLocMemOffset();
2283       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2284 
2285       if (Arg.Flags.isByRef()) {
2286         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2287 
2288         if (!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, RegState::Undef, 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, RegState::Undef, 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, RegState::Undef, 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, RegState::Undef, 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 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6646   switch (MF.getFunction().getCallingConv()) {
6647   case CallingConv::AMDGPU_PS:
6648     return 1;
6649   case CallingConv::AMDGPU_VS:
6650     return 2;
6651   case CallingConv::AMDGPU_GS:
6652     return 3;
6653   case CallingConv::AMDGPU_HS:
6654   case CallingConv::AMDGPU_LS:
6655   case CallingConv::AMDGPU_ES:
6656     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6657   case CallingConv::AMDGPU_CS:
6658   case CallingConv::AMDGPU_KERNEL:
6659   case CallingConv::C:
6660   case CallingConv::Fast:
6661   default:
6662     // Assume other calling conventions are various compute callable functions
6663     return 0;
6664   }
6665 }
6666 
6667 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6668                                                  SelectionDAG &DAG) const {
6669   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6670   SDLoc DL(Op);
6671 
6672   switch (IntrID) {
6673   case Intrinsic::amdgcn_ds_ordered_add:
6674   case Intrinsic::amdgcn_ds_ordered_swap: {
6675     MemSDNode *M = cast<MemSDNode>(Op);
6676     SDValue Chain = M->getOperand(0);
6677     SDValue M0 = M->getOperand(2);
6678     SDValue Value = M->getOperand(3);
6679     unsigned IndexOperand = M->getConstantOperandVal(7);
6680     unsigned WaveRelease = M->getConstantOperandVal(8);
6681     unsigned WaveDone = M->getConstantOperandVal(9);
6682 
6683     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6684     IndexOperand &= ~0x3f;
6685     unsigned CountDw = 0;
6686 
6687     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6688       CountDw = (IndexOperand >> 24) & 0xf;
6689       IndexOperand &= ~(0xf << 24);
6690 
6691       if (CountDw < 1 || CountDw > 4) {
6692         report_fatal_error(
6693             "ds_ordered_count: dword count must be between 1 and 4");
6694       }
6695     }
6696 
6697     if (IndexOperand)
6698       report_fatal_error("ds_ordered_count: bad index operand");
6699 
6700     if (WaveDone && !WaveRelease)
6701       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6702 
6703     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6704     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6705     unsigned Offset0 = OrderedCountIndex << 2;
6706     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6707                        (Instruction << 4);
6708 
6709     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6710       Offset1 |= (CountDw - 1) << 6;
6711 
6712     unsigned Offset = Offset0 | (Offset1 << 8);
6713 
6714     SDValue Ops[] = {
6715       Chain,
6716       Value,
6717       DAG.getTargetConstant(Offset, DL, MVT::i16),
6718       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6719     };
6720     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6721                                    M->getVTList(), Ops, M->getMemoryVT(),
6722                                    M->getMemOperand());
6723   }
6724   case Intrinsic::amdgcn_ds_fadd: {
6725     MemSDNode *M = cast<MemSDNode>(Op);
6726     unsigned Opc;
6727     switch (IntrID) {
6728     case Intrinsic::amdgcn_ds_fadd:
6729       Opc = ISD::ATOMIC_LOAD_FADD;
6730       break;
6731     }
6732 
6733     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6734                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6735                          M->getMemOperand());
6736   }
6737   case Intrinsic::amdgcn_atomic_inc:
6738   case Intrinsic::amdgcn_atomic_dec:
6739   case Intrinsic::amdgcn_ds_fmin:
6740   case Intrinsic::amdgcn_ds_fmax: {
6741     MemSDNode *M = cast<MemSDNode>(Op);
6742     unsigned Opc;
6743     switch (IntrID) {
6744     case Intrinsic::amdgcn_atomic_inc:
6745       Opc = AMDGPUISD::ATOMIC_INC;
6746       break;
6747     case Intrinsic::amdgcn_atomic_dec:
6748       Opc = AMDGPUISD::ATOMIC_DEC;
6749       break;
6750     case Intrinsic::amdgcn_ds_fmin:
6751       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6752       break;
6753     case Intrinsic::amdgcn_ds_fmax:
6754       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6755       break;
6756     default:
6757       llvm_unreachable("Unknown intrinsic!");
6758     }
6759     SDValue Ops[] = {
6760       M->getOperand(0), // Chain
6761       M->getOperand(2), // Ptr
6762       M->getOperand(3)  // Value
6763     };
6764 
6765     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6766                                    M->getMemoryVT(), M->getMemOperand());
6767   }
6768   case Intrinsic::amdgcn_buffer_load:
6769   case Intrinsic::amdgcn_buffer_load_format: {
6770     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6771     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6772     unsigned IdxEn = 1;
6773     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6774       IdxEn = Idx->getZExtValue() != 0;
6775     SDValue Ops[] = {
6776       Op.getOperand(0), // Chain
6777       Op.getOperand(2), // rsrc
6778       Op.getOperand(3), // vindex
6779       SDValue(),        // voffset -- will be set by setBufferOffsets
6780       SDValue(),        // soffset -- will be set by setBufferOffsets
6781       SDValue(),        // offset -- will be set by setBufferOffsets
6782       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6783       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6784     };
6785 
6786     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6787     // We don't know the offset if vindex is non-zero, so clear it.
6788     if (IdxEn)
6789       Offset = 0;
6790 
6791     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6792         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6793 
6794     EVT VT = Op.getValueType();
6795     EVT IntVT = VT.changeTypeToInteger();
6796     auto *M = cast<MemSDNode>(Op);
6797     M->getMemOperand()->setOffset(Offset);
6798     EVT LoadVT = Op.getValueType();
6799 
6800     if (LoadVT.getScalarType() == MVT::f16)
6801       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6802                                  M, DAG, Ops);
6803 
6804     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6805     if (LoadVT.getScalarType() == MVT::i8 ||
6806         LoadVT.getScalarType() == MVT::i16)
6807       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6808 
6809     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6810                                M->getMemOperand(), DAG);
6811   }
6812   case Intrinsic::amdgcn_raw_buffer_load:
6813   case Intrinsic::amdgcn_raw_buffer_load_format: {
6814     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6815 
6816     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6817     SDValue Ops[] = {
6818       Op.getOperand(0), // Chain
6819       Op.getOperand(2), // rsrc
6820       DAG.getConstant(0, DL, MVT::i32), // vindex
6821       Offsets.first,    // voffset
6822       Op.getOperand(4), // soffset
6823       Offsets.second,   // offset
6824       Op.getOperand(5), // cachepolicy, swizzled buffer
6825       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6826     };
6827 
6828     auto *M = cast<MemSDNode>(Op);
6829     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6830     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6831   }
6832   case Intrinsic::amdgcn_struct_buffer_load:
6833   case Intrinsic::amdgcn_struct_buffer_load_format: {
6834     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6835 
6836     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6837     SDValue Ops[] = {
6838       Op.getOperand(0), // Chain
6839       Op.getOperand(2), // rsrc
6840       Op.getOperand(3), // vindex
6841       Offsets.first,    // voffset
6842       Op.getOperand(5), // soffset
6843       Offsets.second,   // offset
6844       Op.getOperand(6), // cachepolicy, swizzled buffer
6845       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6846     };
6847 
6848     auto *M = cast<MemSDNode>(Op);
6849     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6850                                                         Ops[2]));
6851     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6852   }
6853   case Intrinsic::amdgcn_tbuffer_load: {
6854     MemSDNode *M = cast<MemSDNode>(Op);
6855     EVT LoadVT = Op.getValueType();
6856 
6857     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6858     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6859     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6860     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6861     unsigned IdxEn = 1;
6862     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6863       IdxEn = Idx->getZExtValue() != 0;
6864     SDValue Ops[] = {
6865       Op.getOperand(0),  // Chain
6866       Op.getOperand(2),  // rsrc
6867       Op.getOperand(3),  // vindex
6868       Op.getOperand(4),  // voffset
6869       Op.getOperand(5),  // soffset
6870       Op.getOperand(6),  // offset
6871       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6872       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6873       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6874     };
6875 
6876     if (LoadVT.getScalarType() == MVT::f16)
6877       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6878                                  M, DAG, Ops);
6879     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6880                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6881                                DAG);
6882   }
6883   case Intrinsic::amdgcn_raw_tbuffer_load: {
6884     MemSDNode *M = cast<MemSDNode>(Op);
6885     EVT LoadVT = Op.getValueType();
6886     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6887 
6888     SDValue Ops[] = {
6889       Op.getOperand(0),  // Chain
6890       Op.getOperand(2),  // rsrc
6891       DAG.getConstant(0, DL, MVT::i32), // vindex
6892       Offsets.first,     // voffset
6893       Op.getOperand(4),  // soffset
6894       Offsets.second,    // offset
6895       Op.getOperand(5),  // format
6896       Op.getOperand(6),  // cachepolicy, swizzled buffer
6897       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6898     };
6899 
6900     if (LoadVT.getScalarType() == MVT::f16)
6901       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6902                                  M, DAG, Ops);
6903     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6904                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6905                                DAG);
6906   }
6907   case Intrinsic::amdgcn_struct_tbuffer_load: {
6908     MemSDNode *M = cast<MemSDNode>(Op);
6909     EVT LoadVT = Op.getValueType();
6910     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6911 
6912     SDValue Ops[] = {
6913       Op.getOperand(0),  // Chain
6914       Op.getOperand(2),  // rsrc
6915       Op.getOperand(3),  // vindex
6916       Offsets.first,     // voffset
6917       Op.getOperand(5),  // soffset
6918       Offsets.second,    // offset
6919       Op.getOperand(6),  // format
6920       Op.getOperand(7),  // cachepolicy, swizzled buffer
6921       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6922     };
6923 
6924     if (LoadVT.getScalarType() == MVT::f16)
6925       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6926                                  M, DAG, Ops);
6927     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6928                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6929                                DAG);
6930   }
6931   case Intrinsic::amdgcn_buffer_atomic_swap:
6932   case Intrinsic::amdgcn_buffer_atomic_add:
6933   case Intrinsic::amdgcn_buffer_atomic_sub:
6934   case Intrinsic::amdgcn_buffer_atomic_csub:
6935   case Intrinsic::amdgcn_buffer_atomic_smin:
6936   case Intrinsic::amdgcn_buffer_atomic_umin:
6937   case Intrinsic::amdgcn_buffer_atomic_smax:
6938   case Intrinsic::amdgcn_buffer_atomic_umax:
6939   case Intrinsic::amdgcn_buffer_atomic_and:
6940   case Intrinsic::amdgcn_buffer_atomic_or:
6941   case Intrinsic::amdgcn_buffer_atomic_xor: {
6942     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6943     unsigned IdxEn = 1;
6944     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6945       IdxEn = Idx->getZExtValue() != 0;
6946     SDValue Ops[] = {
6947       Op.getOperand(0), // Chain
6948       Op.getOperand(2), // vdata
6949       Op.getOperand(3), // rsrc
6950       Op.getOperand(4), // vindex
6951       SDValue(),        // voffset -- will be set by setBufferOffsets
6952       SDValue(),        // soffset -- will be set by setBufferOffsets
6953       SDValue(),        // offset -- will be set by setBufferOffsets
6954       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6955       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6956     };
6957     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6958     // We don't know the offset if vindex is non-zero, so clear it.
6959     if (IdxEn)
6960       Offset = 0;
6961     EVT VT = Op.getValueType();
6962 
6963     auto *M = cast<MemSDNode>(Op);
6964     M->getMemOperand()->setOffset(Offset);
6965     unsigned Opcode = 0;
6966 
6967     switch (IntrID) {
6968     case Intrinsic::amdgcn_buffer_atomic_swap:
6969       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6970       break;
6971     case Intrinsic::amdgcn_buffer_atomic_add:
6972       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6973       break;
6974     case Intrinsic::amdgcn_buffer_atomic_sub:
6975       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6976       break;
6977     case Intrinsic::amdgcn_buffer_atomic_csub:
6978       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
6979       break;
6980     case Intrinsic::amdgcn_buffer_atomic_smin:
6981       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6982       break;
6983     case Intrinsic::amdgcn_buffer_atomic_umin:
6984       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6985       break;
6986     case Intrinsic::amdgcn_buffer_atomic_smax:
6987       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6988       break;
6989     case Intrinsic::amdgcn_buffer_atomic_umax:
6990       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6991       break;
6992     case Intrinsic::amdgcn_buffer_atomic_and:
6993       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6994       break;
6995     case Intrinsic::amdgcn_buffer_atomic_or:
6996       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6997       break;
6998     case Intrinsic::amdgcn_buffer_atomic_xor:
6999       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7000       break;
7001     default:
7002       llvm_unreachable("unhandled atomic opcode");
7003     }
7004 
7005     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7006                                    M->getMemOperand());
7007   }
7008   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7009   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7010   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7011   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7012   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7013   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7014   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7015   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7016   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7017   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7018   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7019   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
7020     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7021     SDValue Ops[] = {
7022       Op.getOperand(0), // Chain
7023       Op.getOperand(2), // vdata
7024       Op.getOperand(3), // rsrc
7025       DAG.getConstant(0, DL, MVT::i32), // vindex
7026       Offsets.first,    // voffset
7027       Op.getOperand(5), // soffset
7028       Offsets.second,   // offset
7029       Op.getOperand(6), // cachepolicy
7030       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7031     };
7032     EVT VT = Op.getValueType();
7033 
7034     auto *M = cast<MemSDNode>(Op);
7035     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7036     unsigned Opcode = 0;
7037 
7038     switch (IntrID) {
7039     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7040       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7041       break;
7042     case Intrinsic::amdgcn_raw_buffer_atomic_add:
7043       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7044       break;
7045     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7046       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7047       break;
7048     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7049       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7050       break;
7051     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7052       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7053       break;
7054     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7055       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7056       break;
7057     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7058       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7059       break;
7060     case Intrinsic::amdgcn_raw_buffer_atomic_and:
7061       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7062       break;
7063     case Intrinsic::amdgcn_raw_buffer_atomic_or:
7064       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7065       break;
7066     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7067       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7068       break;
7069     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7070       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
7071       break;
7072     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7073       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
7074       break;
7075     default:
7076       llvm_unreachable("unhandled atomic opcode");
7077     }
7078 
7079     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7080                                    M->getMemOperand());
7081   }
7082   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7083   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7084   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7085   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7086   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7087   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7088   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7089   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7090   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7091   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7092   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7093   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
7094     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7095     SDValue Ops[] = {
7096       Op.getOperand(0), // Chain
7097       Op.getOperand(2), // vdata
7098       Op.getOperand(3), // rsrc
7099       Op.getOperand(4), // vindex
7100       Offsets.first,    // voffset
7101       Op.getOperand(6), // soffset
7102       Offsets.second,   // offset
7103       Op.getOperand(7), // cachepolicy
7104       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7105     };
7106     EVT VT = Op.getValueType();
7107 
7108     auto *M = cast<MemSDNode>(Op);
7109     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7110                                                         Ops[3]));
7111     unsigned Opcode = 0;
7112 
7113     switch (IntrID) {
7114     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7115       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7116       break;
7117     case Intrinsic::amdgcn_struct_buffer_atomic_add:
7118       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7119       break;
7120     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7121       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7122       break;
7123     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7124       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7125       break;
7126     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7127       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7128       break;
7129     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7130       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7131       break;
7132     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7133       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7134       break;
7135     case Intrinsic::amdgcn_struct_buffer_atomic_and:
7136       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7137       break;
7138     case Intrinsic::amdgcn_struct_buffer_atomic_or:
7139       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7140       break;
7141     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7142       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7143       break;
7144     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7145       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
7146       break;
7147     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7148       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
7149       break;
7150     default:
7151       llvm_unreachable("unhandled atomic opcode");
7152     }
7153 
7154     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7155                                    M->getMemOperand());
7156   }
7157   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7158     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7159     unsigned IdxEn = 1;
7160     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7161       IdxEn = Idx->getZExtValue() != 0;
7162     SDValue Ops[] = {
7163       Op.getOperand(0), // Chain
7164       Op.getOperand(2), // src
7165       Op.getOperand(3), // cmp
7166       Op.getOperand(4), // rsrc
7167       Op.getOperand(5), // vindex
7168       SDValue(),        // voffset -- will be set by setBufferOffsets
7169       SDValue(),        // soffset -- will be set by setBufferOffsets
7170       SDValue(),        // offset -- will be set by setBufferOffsets
7171       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7172       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7173     };
7174     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7175     // We don't know the offset if vindex is non-zero, so clear it.
7176     if (IdxEn)
7177       Offset = 0;
7178     EVT VT = Op.getValueType();
7179     auto *M = cast<MemSDNode>(Op);
7180     M->getMemOperand()->setOffset(Offset);
7181 
7182     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7183                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7184   }
7185   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7186     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7187     SDValue Ops[] = {
7188       Op.getOperand(0), // Chain
7189       Op.getOperand(2), // src
7190       Op.getOperand(3), // cmp
7191       Op.getOperand(4), // rsrc
7192       DAG.getConstant(0, DL, MVT::i32), // vindex
7193       Offsets.first,    // voffset
7194       Op.getOperand(6), // soffset
7195       Offsets.second,   // offset
7196       Op.getOperand(7), // cachepolicy
7197       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7198     };
7199     EVT VT = Op.getValueType();
7200     auto *M = cast<MemSDNode>(Op);
7201     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7202 
7203     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7204                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7205   }
7206   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7207     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7208     SDValue Ops[] = {
7209       Op.getOperand(0), // Chain
7210       Op.getOperand(2), // src
7211       Op.getOperand(3), // cmp
7212       Op.getOperand(4), // rsrc
7213       Op.getOperand(5), // vindex
7214       Offsets.first,    // voffset
7215       Op.getOperand(7), // soffset
7216       Offsets.second,   // offset
7217       Op.getOperand(8), // cachepolicy
7218       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7219     };
7220     EVT VT = Op.getValueType();
7221     auto *M = cast<MemSDNode>(Op);
7222     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7223                                                         Ops[4]));
7224 
7225     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7226                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7227   }
7228   default:
7229     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7230             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7231       return lowerImage(Op, ImageDimIntr, DAG);
7232 
7233     return SDValue();
7234   }
7235 }
7236 
7237 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7238 // dwordx4 if on SI.
7239 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7240                                               SDVTList VTList,
7241                                               ArrayRef<SDValue> Ops, EVT MemVT,
7242                                               MachineMemOperand *MMO,
7243                                               SelectionDAG &DAG) const {
7244   EVT VT = VTList.VTs[0];
7245   EVT WidenedVT = VT;
7246   EVT WidenedMemVT = MemVT;
7247   if (!Subtarget->hasDwordx3LoadStores() &&
7248       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7249     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7250                                  WidenedVT.getVectorElementType(), 4);
7251     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7252                                     WidenedMemVT.getVectorElementType(), 4);
7253     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7254   }
7255 
7256   assert(VTList.NumVTs == 2);
7257   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7258 
7259   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7260                                        WidenedMemVT, MMO);
7261   if (WidenedVT != VT) {
7262     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7263                                DAG.getVectorIdxConstant(0, DL));
7264     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7265   }
7266   return NewOp;
7267 }
7268 
7269 SDValue SITargetLowering::handleD16VData(SDValue VData,
7270                                          SelectionDAG &DAG) const {
7271   EVT StoreVT = VData.getValueType();
7272 
7273   // No change for f16 and legal vector D16 types.
7274   if (!StoreVT.isVector())
7275     return VData;
7276 
7277   SDLoc DL(VData);
7278   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
7279 
7280   if (Subtarget->hasUnpackedD16VMem()) {
7281     // We need to unpack the packed data to store.
7282     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7283     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7284 
7285     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
7286                                         StoreVT.getVectorNumElements());
7287     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7288     return DAG.UnrollVectorOp(ZExt.getNode());
7289   }
7290 
7291   assert(isTypeLegal(StoreVT));
7292   return VData;
7293 }
7294 
7295 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7296                                               SelectionDAG &DAG) const {
7297   SDLoc DL(Op);
7298   SDValue Chain = Op.getOperand(0);
7299   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7300   MachineFunction &MF = DAG.getMachineFunction();
7301 
7302   switch (IntrinsicID) {
7303   case Intrinsic::amdgcn_exp_compr: {
7304     SDValue Src0 = Op.getOperand(4);
7305     SDValue Src1 = Op.getOperand(5);
7306     // Hack around illegal type on SI by directly selecting it.
7307     if (isTypeLegal(Src0.getValueType()))
7308       return SDValue();
7309 
7310     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7311     SDValue Undef = DAG.getUNDEF(MVT::f32);
7312     const SDValue Ops[] = {
7313       Op.getOperand(2), // tgt
7314       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7315       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7316       Undef, // src2
7317       Undef, // src3
7318       Op.getOperand(7), // vm
7319       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7320       Op.getOperand(3), // en
7321       Op.getOperand(0) // Chain
7322     };
7323 
7324     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7325     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7326   }
7327   case Intrinsic::amdgcn_s_barrier: {
7328     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7329       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7330       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7331       if (WGSize <= ST.getWavefrontSize())
7332         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7333                                           Op.getOperand(0)), 0);
7334     }
7335     return SDValue();
7336   };
7337   case Intrinsic::amdgcn_tbuffer_store: {
7338     SDValue VData = Op.getOperand(2);
7339     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7340     if (IsD16)
7341       VData = handleD16VData(VData, DAG);
7342     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7343     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7344     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7345     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7346     unsigned IdxEn = 1;
7347     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7348       IdxEn = Idx->getZExtValue() != 0;
7349     SDValue Ops[] = {
7350       Chain,
7351       VData,             // vdata
7352       Op.getOperand(3),  // rsrc
7353       Op.getOperand(4),  // vindex
7354       Op.getOperand(5),  // voffset
7355       Op.getOperand(6),  // soffset
7356       Op.getOperand(7),  // offset
7357       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7358       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7359       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7360     };
7361     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7362                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7363     MemSDNode *M = cast<MemSDNode>(Op);
7364     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7365                                    M->getMemoryVT(), M->getMemOperand());
7366   }
7367 
7368   case Intrinsic::amdgcn_struct_tbuffer_store: {
7369     SDValue VData = Op.getOperand(2);
7370     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7371     if (IsD16)
7372       VData = handleD16VData(VData, DAG);
7373     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7374     SDValue Ops[] = {
7375       Chain,
7376       VData,             // vdata
7377       Op.getOperand(3),  // rsrc
7378       Op.getOperand(4),  // vindex
7379       Offsets.first,     // voffset
7380       Op.getOperand(6),  // soffset
7381       Offsets.second,    // offset
7382       Op.getOperand(7),  // format
7383       Op.getOperand(8),  // cachepolicy, swizzled buffer
7384       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7385     };
7386     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7387                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7388     MemSDNode *M = cast<MemSDNode>(Op);
7389     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7390                                    M->getMemoryVT(), M->getMemOperand());
7391   }
7392 
7393   case Intrinsic::amdgcn_raw_tbuffer_store: {
7394     SDValue VData = Op.getOperand(2);
7395     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7396     if (IsD16)
7397       VData = handleD16VData(VData, DAG);
7398     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7399     SDValue Ops[] = {
7400       Chain,
7401       VData,             // vdata
7402       Op.getOperand(3),  // rsrc
7403       DAG.getConstant(0, DL, MVT::i32), // vindex
7404       Offsets.first,     // voffset
7405       Op.getOperand(5),  // soffset
7406       Offsets.second,    // offset
7407       Op.getOperand(6),  // format
7408       Op.getOperand(7),  // cachepolicy, swizzled buffer
7409       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7410     };
7411     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7412                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7413     MemSDNode *M = cast<MemSDNode>(Op);
7414     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7415                                    M->getMemoryVT(), M->getMemOperand());
7416   }
7417 
7418   case Intrinsic::amdgcn_buffer_store:
7419   case Intrinsic::amdgcn_buffer_store_format: {
7420     SDValue VData = Op.getOperand(2);
7421     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7422     if (IsD16)
7423       VData = handleD16VData(VData, DAG);
7424     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7425     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7426     unsigned IdxEn = 1;
7427     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7428       IdxEn = Idx->getZExtValue() != 0;
7429     SDValue Ops[] = {
7430       Chain,
7431       VData,
7432       Op.getOperand(3), // rsrc
7433       Op.getOperand(4), // vindex
7434       SDValue(), // voffset -- will be set by setBufferOffsets
7435       SDValue(), // soffset -- will be set by setBufferOffsets
7436       SDValue(), // offset -- will be set by setBufferOffsets
7437       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7438       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7439     };
7440     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7441     // We don't know the offset if vindex is non-zero, so clear it.
7442     if (IdxEn)
7443       Offset = 0;
7444     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7445                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7446     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7447     MemSDNode *M = cast<MemSDNode>(Op);
7448     M->getMemOperand()->setOffset(Offset);
7449 
7450     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7451     EVT VDataType = VData.getValueType().getScalarType();
7452     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7453       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7454 
7455     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7456                                    M->getMemoryVT(), M->getMemOperand());
7457   }
7458 
7459   case Intrinsic::amdgcn_raw_buffer_store:
7460   case Intrinsic::amdgcn_raw_buffer_store_format: {
7461     const bool IsFormat =
7462         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7463 
7464     SDValue VData = Op.getOperand(2);
7465     EVT VDataVT = VData.getValueType();
7466     EVT EltType = VDataVT.getScalarType();
7467     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7468     if (IsD16)
7469       VData = handleD16VData(VData, DAG);
7470 
7471     if (!isTypeLegal(VDataVT)) {
7472       VData =
7473           DAG.getNode(ISD::BITCAST, DL,
7474                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7475     }
7476 
7477     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7478     SDValue Ops[] = {
7479       Chain,
7480       VData,
7481       Op.getOperand(3), // rsrc
7482       DAG.getConstant(0, DL, MVT::i32), // vindex
7483       Offsets.first,    // voffset
7484       Op.getOperand(5), // soffset
7485       Offsets.second,   // offset
7486       Op.getOperand(6), // cachepolicy, swizzled buffer
7487       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7488     };
7489     unsigned Opc =
7490         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7491     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7492     MemSDNode *M = cast<MemSDNode>(Op);
7493     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7494 
7495     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7496     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7497       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7498 
7499     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7500                                    M->getMemoryVT(), M->getMemOperand());
7501   }
7502 
7503   case Intrinsic::amdgcn_struct_buffer_store:
7504   case Intrinsic::amdgcn_struct_buffer_store_format: {
7505     const bool IsFormat =
7506         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7507 
7508     SDValue VData = Op.getOperand(2);
7509     EVT VDataVT = VData.getValueType();
7510     EVT EltType = VDataVT.getScalarType();
7511     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7512 
7513     if (IsD16)
7514       VData = handleD16VData(VData, DAG);
7515 
7516     if (!isTypeLegal(VDataVT)) {
7517       VData =
7518           DAG.getNode(ISD::BITCAST, DL,
7519                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7520     }
7521 
7522     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7523     SDValue Ops[] = {
7524       Chain,
7525       VData,
7526       Op.getOperand(3), // rsrc
7527       Op.getOperand(4), // vindex
7528       Offsets.first,    // voffset
7529       Op.getOperand(6), // soffset
7530       Offsets.second,   // offset
7531       Op.getOperand(7), // cachepolicy, swizzled buffer
7532       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7533     };
7534     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7535                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7536     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7537     MemSDNode *M = cast<MemSDNode>(Op);
7538     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7539                                                         Ops[3]));
7540 
7541     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7542     EVT VDataType = VData.getValueType().getScalarType();
7543     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7544       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7545 
7546     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7547                                    M->getMemoryVT(), M->getMemOperand());
7548   }
7549 
7550   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7551     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7552     unsigned IdxEn = 1;
7553     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7554       IdxEn = Idx->getZExtValue() != 0;
7555     SDValue Ops[] = {
7556       Chain,
7557       Op.getOperand(2), // vdata
7558       Op.getOperand(3), // rsrc
7559       Op.getOperand(4), // vindex
7560       SDValue(),        // voffset -- will be set by setBufferOffsets
7561       SDValue(),        // soffset -- will be set by setBufferOffsets
7562       SDValue(),        // offset -- will be set by setBufferOffsets
7563       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7564       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7565     };
7566     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7567     // We don't know the offset if vindex is non-zero, so clear it.
7568     if (IdxEn)
7569       Offset = 0;
7570     EVT VT = Op.getOperand(2).getValueType();
7571 
7572     auto *M = cast<MemSDNode>(Op);
7573     M->getMemOperand()->setOffset(Offset);
7574     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7575                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7576 
7577     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7578                                    M->getMemOperand());
7579   }
7580 
7581   case Intrinsic::amdgcn_global_atomic_fadd: {
7582     SDValue Ops[] = {
7583       Chain,
7584       Op.getOperand(2), // ptr
7585       Op.getOperand(3)  // vdata
7586     };
7587     EVT VT = Op.getOperand(3).getValueType();
7588 
7589     auto *M = cast<MemSDNode>(Op);
7590     if (VT.isVector()) {
7591       return DAG.getMemIntrinsicNode(
7592         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7593         M->getMemOperand());
7594     }
7595 
7596     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7597                          DAG.getVTList(VT, MVT::Other), Ops,
7598                          M->getMemOperand()).getValue(1);
7599   }
7600   case Intrinsic::amdgcn_end_cf:
7601     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7602                                       Op->getOperand(2), Chain), 0);
7603 
7604   default: {
7605     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7606             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7607       return lowerImage(Op, ImageDimIntr, DAG);
7608 
7609     return Op;
7610   }
7611   }
7612 }
7613 
7614 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7615 // offset (the offset that is included in bounds checking and swizzling, to be
7616 // split between the instruction's voffset and immoffset fields) and soffset
7617 // (the offset that is excluded from bounds checking and swizzling, to go in
7618 // the instruction's soffset field).  This function takes the first kind of
7619 // offset and figures out how to split it between voffset and immoffset.
7620 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7621     SDValue Offset, SelectionDAG &DAG) const {
7622   SDLoc DL(Offset);
7623   const unsigned MaxImm = 4095;
7624   SDValue N0 = Offset;
7625   ConstantSDNode *C1 = nullptr;
7626 
7627   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7628     N0 = SDValue();
7629   else if (DAG.isBaseWithConstantOffset(N0)) {
7630     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7631     N0 = N0.getOperand(0);
7632   }
7633 
7634   if (C1) {
7635     unsigned ImmOffset = C1->getZExtValue();
7636     // If the immediate value is too big for the immoffset field, put the value
7637     // and -4096 into the immoffset field so that the value that is copied/added
7638     // for the voffset field is a multiple of 4096, and it stands more chance
7639     // of being CSEd with the copy/add for another similar load/store.
7640     // However, do not do that rounding down to a multiple of 4096 if that is a
7641     // negative number, as it appears to be illegal to have a negative offset
7642     // in the vgpr, even if adding the immediate offset makes it positive.
7643     unsigned Overflow = ImmOffset & ~MaxImm;
7644     ImmOffset -= Overflow;
7645     if ((int32_t)Overflow < 0) {
7646       Overflow += ImmOffset;
7647       ImmOffset = 0;
7648     }
7649     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7650     if (Overflow) {
7651       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7652       if (!N0)
7653         N0 = OverflowVal;
7654       else {
7655         SDValue Ops[] = { N0, OverflowVal };
7656         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7657       }
7658     }
7659   }
7660   if (!N0)
7661     N0 = DAG.getConstant(0, DL, MVT::i32);
7662   if (!C1)
7663     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7664   return {N0, SDValue(C1, 0)};
7665 }
7666 
7667 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7668 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7669 // pointed to by Offsets.
7670 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7671                                             SelectionDAG &DAG, SDValue *Offsets,
7672                                             Align Alignment) const {
7673   SDLoc DL(CombinedOffset);
7674   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7675     uint32_t Imm = C->getZExtValue();
7676     uint32_t SOffset, ImmOffset;
7677     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7678                                  Alignment)) {
7679       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7680       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7681       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7682       return SOffset + ImmOffset;
7683     }
7684   }
7685   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7686     SDValue N0 = CombinedOffset.getOperand(0);
7687     SDValue N1 = CombinedOffset.getOperand(1);
7688     uint32_t SOffset, ImmOffset;
7689     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7690     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7691                                                 Subtarget, Alignment)) {
7692       Offsets[0] = N0;
7693       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7694       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7695       return 0;
7696     }
7697   }
7698   Offsets[0] = CombinedOffset;
7699   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7700   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7701   return 0;
7702 }
7703 
7704 // Handle 8 bit and 16 bit buffer loads
7705 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7706                                                      EVT LoadVT, SDLoc DL,
7707                                                      ArrayRef<SDValue> Ops,
7708                                                      MemSDNode *M) const {
7709   EVT IntVT = LoadVT.changeTypeToInteger();
7710   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7711          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7712 
7713   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7714   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7715                                                Ops, IntVT,
7716                                                M->getMemOperand());
7717   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7718   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7719 
7720   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7721 }
7722 
7723 // Handle 8 bit and 16 bit buffer stores
7724 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7725                                                       EVT VDataType, SDLoc DL,
7726                                                       SDValue Ops[],
7727                                                       MemSDNode *M) const {
7728   if (VDataType == MVT::f16)
7729     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7730 
7731   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7732   Ops[1] = BufferStoreExt;
7733   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7734                                  AMDGPUISD::BUFFER_STORE_SHORT;
7735   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7736   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7737                                      M->getMemOperand());
7738 }
7739 
7740 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7741                                  ISD::LoadExtType ExtType, SDValue Op,
7742                                  const SDLoc &SL, EVT VT) {
7743   if (VT.bitsLT(Op.getValueType()))
7744     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7745 
7746   switch (ExtType) {
7747   case ISD::SEXTLOAD:
7748     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7749   case ISD::ZEXTLOAD:
7750     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7751   case ISD::EXTLOAD:
7752     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7753   case ISD::NON_EXTLOAD:
7754     return Op;
7755   }
7756 
7757   llvm_unreachable("invalid ext type");
7758 }
7759 
7760 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7761   SelectionDAG &DAG = DCI.DAG;
7762   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7763     return SDValue();
7764 
7765   // FIXME: Constant loads should all be marked invariant.
7766   unsigned AS = Ld->getAddressSpace();
7767   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7768       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7769       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7770     return SDValue();
7771 
7772   // Don't do this early, since it may interfere with adjacent load merging for
7773   // illegal types. We can avoid losing alignment information for exotic types
7774   // pre-legalize.
7775   EVT MemVT = Ld->getMemoryVT();
7776   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7777       MemVT.getSizeInBits() >= 32)
7778     return SDValue();
7779 
7780   SDLoc SL(Ld);
7781 
7782   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7783          "unexpected vector extload");
7784 
7785   // TODO: Drop only high part of range.
7786   SDValue Ptr = Ld->getBasePtr();
7787   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7788                                 MVT::i32, SL, Ld->getChain(), Ptr,
7789                                 Ld->getOffset(),
7790                                 Ld->getPointerInfo(), MVT::i32,
7791                                 Ld->getAlignment(),
7792                                 Ld->getMemOperand()->getFlags(),
7793                                 Ld->getAAInfo(),
7794                                 nullptr); // Drop ranges
7795 
7796   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7797   if (MemVT.isFloatingPoint()) {
7798     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7799            "unexpected fp extload");
7800     TruncVT = MemVT.changeTypeToInteger();
7801   }
7802 
7803   SDValue Cvt = NewLoad;
7804   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7805     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7806                       DAG.getValueType(TruncVT));
7807   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7808              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7809     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7810   } else {
7811     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7812   }
7813 
7814   EVT VT = Ld->getValueType(0);
7815   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7816 
7817   DCI.AddToWorklist(Cvt.getNode());
7818 
7819   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7820   // the appropriate extension from the 32-bit load.
7821   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7822   DCI.AddToWorklist(Cvt.getNode());
7823 
7824   // Handle conversion back to floating point if necessary.
7825   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7826 
7827   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7828 }
7829 
7830 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7831   SDLoc DL(Op);
7832   LoadSDNode *Load = cast<LoadSDNode>(Op);
7833   ISD::LoadExtType ExtType = Load->getExtensionType();
7834   EVT MemVT = Load->getMemoryVT();
7835 
7836   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7837     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7838       return SDValue();
7839 
7840     // FIXME: Copied from PPC
7841     // First, load into 32 bits, then truncate to 1 bit.
7842 
7843     SDValue Chain = Load->getChain();
7844     SDValue BasePtr = Load->getBasePtr();
7845     MachineMemOperand *MMO = Load->getMemOperand();
7846 
7847     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7848 
7849     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7850                                    BasePtr, RealMemVT, MMO);
7851 
7852     if (!MemVT.isVector()) {
7853       SDValue Ops[] = {
7854         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7855         NewLD.getValue(1)
7856       };
7857 
7858       return DAG.getMergeValues(Ops, DL);
7859     }
7860 
7861     SmallVector<SDValue, 3> Elts;
7862     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7863       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7864                                 DAG.getConstant(I, DL, MVT::i32));
7865 
7866       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7867     }
7868 
7869     SDValue Ops[] = {
7870       DAG.getBuildVector(MemVT, DL, Elts),
7871       NewLD.getValue(1)
7872     };
7873 
7874     return DAG.getMergeValues(Ops, DL);
7875   }
7876 
7877   if (!MemVT.isVector())
7878     return SDValue();
7879 
7880   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7881          "Custom lowering for non-i32 vectors hasn't been implemented.");
7882 
7883   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7884                                       MemVT, *Load->getMemOperand())) {
7885     SDValue Ops[2];
7886     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7887     return DAG.getMergeValues(Ops, DL);
7888   }
7889 
7890   unsigned Alignment = Load->getAlignment();
7891   unsigned AS = Load->getAddressSpace();
7892   if (Subtarget->hasLDSMisalignedBug() &&
7893       AS == AMDGPUAS::FLAT_ADDRESS &&
7894       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7895     return SplitVectorLoad(Op, DAG);
7896   }
7897 
7898   MachineFunction &MF = DAG.getMachineFunction();
7899   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7900   // If there is a possibilty that flat instruction access scratch memory
7901   // then we need to use the same legalization rules we use for private.
7902   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7903       !Subtarget->hasMultiDwordFlatScratchAddressing())
7904     AS = MFI->hasFlatScratchInit() ?
7905          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7906 
7907   unsigned NumElements = MemVT.getVectorNumElements();
7908 
7909   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7910       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7911     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7912       if (MemVT.isPow2VectorType())
7913         return SDValue();
7914       if (NumElements == 3)
7915         return WidenVectorLoad(Op, DAG);
7916       return SplitVectorLoad(Op, DAG);
7917     }
7918     // Non-uniform loads will be selected to MUBUF instructions, so they
7919     // have the same legalization requirements as global and private
7920     // loads.
7921     //
7922   }
7923 
7924   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7925       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7926       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7927     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7928         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7929         Alignment >= 4 && NumElements < 32) {
7930       if (MemVT.isPow2VectorType())
7931         return SDValue();
7932       if (NumElements == 3)
7933         return WidenVectorLoad(Op, DAG);
7934       return SplitVectorLoad(Op, DAG);
7935     }
7936     // Non-uniform loads will be selected to MUBUF instructions, so they
7937     // have the same legalization requirements as global and private
7938     // loads.
7939     //
7940   }
7941   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7942       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7943       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7944       AS == AMDGPUAS::FLAT_ADDRESS) {
7945     if (NumElements > 4)
7946       return SplitVectorLoad(Op, DAG);
7947     // v3 loads not supported on SI.
7948     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7949       return WidenVectorLoad(Op, DAG);
7950     // v3 and v4 loads are supported for private and global memory.
7951     return SDValue();
7952   }
7953   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7954     // Depending on the setting of the private_element_size field in the
7955     // resource descriptor, we can only make private accesses up to a certain
7956     // size.
7957     switch (Subtarget->getMaxPrivateElementSize()) {
7958     case 4: {
7959       SDValue Ops[2];
7960       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7961       return DAG.getMergeValues(Ops, DL);
7962     }
7963     case 8:
7964       if (NumElements > 2)
7965         return SplitVectorLoad(Op, DAG);
7966       return SDValue();
7967     case 16:
7968       // Same as global/flat
7969       if (NumElements > 4)
7970         return SplitVectorLoad(Op, DAG);
7971       // v3 loads not supported on SI.
7972       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7973         return WidenVectorLoad(Op, DAG);
7974       return SDValue();
7975     default:
7976       llvm_unreachable("unsupported private_element_size");
7977     }
7978   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7979     // Use ds_read_b128 if possible.
7980     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7981         MemVT.getStoreSize() == 16)
7982       return SDValue();
7983 
7984     if (NumElements > 2)
7985       return SplitVectorLoad(Op, DAG);
7986 
7987     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7988     // address is negative, then the instruction is incorrectly treated as
7989     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7990     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7991     // load later in the SILoadStoreOptimizer.
7992     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7993         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7994         Load->getAlignment() < 8) {
7995       return SplitVectorLoad(Op, DAG);
7996     }
7997   }
7998   return SDValue();
7999 }
8000 
8001 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8002   EVT VT = Op.getValueType();
8003   assert(VT.getSizeInBits() == 64);
8004 
8005   SDLoc DL(Op);
8006   SDValue Cond = Op.getOperand(0);
8007 
8008   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8009   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8010 
8011   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8012   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8013 
8014   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8015   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8016 
8017   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8018 
8019   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8020   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8021 
8022   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8023 
8024   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8025   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8026 }
8027 
8028 // Catch division cases where we can use shortcuts with rcp and rsq
8029 // instructions.
8030 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8031                                               SelectionDAG &DAG) const {
8032   SDLoc SL(Op);
8033   SDValue LHS = Op.getOperand(0);
8034   SDValue RHS = Op.getOperand(1);
8035   EVT VT = Op.getValueType();
8036   const SDNodeFlags Flags = Op->getFlags();
8037 
8038   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
8039                             Flags.hasApproximateFuncs();
8040 
8041   // Without !fpmath accuracy information, we can't do more because we don't
8042   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8043   if (!AllowInaccurateRcp)
8044     return SDValue();
8045 
8046   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8047     if (CLHS->isExactlyValue(1.0)) {
8048       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8049       // the CI documentation has a worst case error of 1 ulp.
8050       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8051       // use it as long as we aren't trying to use denormals.
8052       //
8053       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8054 
8055       // 1.0 / sqrt(x) -> rsq(x)
8056 
8057       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8058       // error seems really high at 2^29 ULP.
8059       if (RHS.getOpcode() == ISD::FSQRT)
8060         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8061 
8062       // 1.0 / x -> rcp(x)
8063       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8064     }
8065 
8066     // Same as for 1.0, but expand the sign out of the constant.
8067     if (CLHS->isExactlyValue(-1.0)) {
8068       // -1.0 / x -> rcp (fneg x)
8069       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8070       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8071     }
8072   }
8073 
8074   // Turn into multiply by the reciprocal.
8075   // x / y -> x * (1.0 / y)
8076   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8077   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8078 }
8079 
8080 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8081                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8082                           SDNodeFlags Flags) {
8083   if (GlueChain->getNumValues() <= 1) {
8084     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8085   }
8086 
8087   assert(GlueChain->getNumValues() == 3);
8088 
8089   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8090   switch (Opcode) {
8091   default: llvm_unreachable("no chain equivalent for opcode");
8092   case ISD::FMUL:
8093     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8094     break;
8095   }
8096 
8097   return DAG.getNode(Opcode, SL, VTList,
8098                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8099                      Flags);
8100 }
8101 
8102 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8103                            EVT VT, SDValue A, SDValue B, SDValue C,
8104                            SDValue GlueChain, SDNodeFlags Flags) {
8105   if (GlueChain->getNumValues() <= 1) {
8106     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8107   }
8108 
8109   assert(GlueChain->getNumValues() == 3);
8110 
8111   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8112   switch (Opcode) {
8113   default: llvm_unreachable("no chain equivalent for opcode");
8114   case ISD::FMA:
8115     Opcode = AMDGPUISD::FMA_W_CHAIN;
8116     break;
8117   }
8118 
8119   return DAG.getNode(Opcode, SL, VTList,
8120                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8121                      Flags);
8122 }
8123 
8124 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8125   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8126     return FastLowered;
8127 
8128   SDLoc SL(Op);
8129   SDValue Src0 = Op.getOperand(0);
8130   SDValue Src1 = Op.getOperand(1);
8131 
8132   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8133   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8134 
8135   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8136   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8137 
8138   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8139   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8140 
8141   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8142 }
8143 
8144 // Faster 2.5 ULP division that does not support denormals.
8145 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8146   SDLoc SL(Op);
8147   SDValue LHS = Op.getOperand(1);
8148   SDValue RHS = Op.getOperand(2);
8149 
8150   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8151 
8152   const APFloat K0Val(BitsToFloat(0x6f800000));
8153   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8154 
8155   const APFloat K1Val(BitsToFloat(0x2f800000));
8156   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8157 
8158   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8159 
8160   EVT SetCCVT =
8161     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8162 
8163   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8164 
8165   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8166 
8167   // TODO: Should this propagate fast-math-flags?
8168   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8169 
8170   // rcp does not support denormals.
8171   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8172 
8173   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8174 
8175   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8176 }
8177 
8178 // Returns immediate value for setting the F32 denorm mode when using the
8179 // S_DENORM_MODE instruction.
8180 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8181                                           const SDLoc &SL, const GCNSubtarget *ST) {
8182   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8183   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8184                                 ? FP_DENORM_FLUSH_NONE
8185                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8186 
8187   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8188   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8189 }
8190 
8191 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8192   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8193     return FastLowered;
8194 
8195   // The selection matcher assumes anything with a chain selecting to a
8196   // mayRaiseFPException machine instruction. Since we're introducing a chain
8197   // here, we need to explicitly report nofpexcept for the regular fdiv
8198   // lowering.
8199   SDNodeFlags Flags = Op->getFlags();
8200   Flags.setNoFPExcept(true);
8201 
8202   SDLoc SL(Op);
8203   SDValue LHS = Op.getOperand(0);
8204   SDValue RHS = Op.getOperand(1);
8205 
8206   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8207 
8208   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8209 
8210   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8211                                           {RHS, RHS, LHS}, Flags);
8212   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8213                                         {LHS, RHS, LHS}, Flags);
8214 
8215   // Denominator is scaled to not be denormal, so using rcp is ok.
8216   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8217                                   DenominatorScaled, Flags);
8218   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8219                                      DenominatorScaled, Flags);
8220 
8221   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8222                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8223                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8224   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8225 
8226   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8227 
8228   if (!HasFP32Denormals) {
8229     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8230     // lowering. The chain dependence is insufficient, and we need glue. We do
8231     // not need the glue variants in a strictfp function.
8232 
8233     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8234 
8235     SDNode *EnableDenorm;
8236     if (Subtarget->hasDenormModeInst()) {
8237       const SDValue EnableDenormValue =
8238           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8239 
8240       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8241                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8242     } else {
8243       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8244                                                         SL, MVT::i32);
8245       EnableDenorm =
8246           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8247                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8248     }
8249 
8250     SDValue Ops[3] = {
8251       NegDivScale0,
8252       SDValue(EnableDenorm, 0),
8253       SDValue(EnableDenorm, 1)
8254     };
8255 
8256     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8257   }
8258 
8259   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8260                              ApproxRcp, One, NegDivScale0, Flags);
8261 
8262   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8263                              ApproxRcp, Fma0, Flags);
8264 
8265   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8266                            Fma1, Fma1, Flags);
8267 
8268   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8269                              NumeratorScaled, Mul, Flags);
8270 
8271   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8272                              Fma2, Fma1, Mul, Fma2, Flags);
8273 
8274   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8275                              NumeratorScaled, Fma3, Flags);
8276 
8277   if (!HasFP32Denormals) {
8278     SDNode *DisableDenorm;
8279     if (Subtarget->hasDenormModeInst()) {
8280       const SDValue DisableDenormValue =
8281           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8282 
8283       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8284                                   Fma4.getValue(1), DisableDenormValue,
8285                                   Fma4.getValue(2)).getNode();
8286     } else {
8287       const SDValue DisableDenormValue =
8288           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8289 
8290       DisableDenorm = DAG.getMachineNode(
8291           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8292           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8293     }
8294 
8295     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8296                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8297     DAG.setRoot(OutputChain);
8298   }
8299 
8300   SDValue Scale = NumeratorScaled.getValue(1);
8301   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8302                              {Fma4, Fma1, Fma3, Scale}, Flags);
8303 
8304   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8305 }
8306 
8307 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8308   if (DAG.getTarget().Options.UnsafeFPMath)
8309     return lowerFastUnsafeFDIV(Op, DAG);
8310 
8311   SDLoc SL(Op);
8312   SDValue X = Op.getOperand(0);
8313   SDValue Y = Op.getOperand(1);
8314 
8315   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8316 
8317   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8318 
8319   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8320 
8321   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8322 
8323   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8324 
8325   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8326 
8327   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8328 
8329   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8330 
8331   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8332 
8333   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8334   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8335 
8336   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8337                              NegDivScale0, Mul, DivScale1);
8338 
8339   SDValue Scale;
8340 
8341   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8342     // Workaround a hardware bug on SI where the condition output from div_scale
8343     // is not usable.
8344 
8345     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8346 
8347     // Figure out if the scale to use for div_fmas.
8348     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8349     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8350     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8351     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8352 
8353     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8354     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8355 
8356     SDValue Scale0Hi
8357       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8358     SDValue Scale1Hi
8359       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8360 
8361     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8362     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8363     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8364   } else {
8365     Scale = DivScale1.getValue(1);
8366   }
8367 
8368   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8369                              Fma4, Fma3, Mul, Scale);
8370 
8371   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8372 }
8373 
8374 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8375   EVT VT = Op.getValueType();
8376 
8377   if (VT == MVT::f32)
8378     return LowerFDIV32(Op, DAG);
8379 
8380   if (VT == MVT::f64)
8381     return LowerFDIV64(Op, DAG);
8382 
8383   if (VT == MVT::f16)
8384     return LowerFDIV16(Op, DAG);
8385 
8386   llvm_unreachable("Unexpected type for fdiv");
8387 }
8388 
8389 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8390   SDLoc DL(Op);
8391   StoreSDNode *Store = cast<StoreSDNode>(Op);
8392   EVT VT = Store->getMemoryVT();
8393 
8394   if (VT == MVT::i1) {
8395     return DAG.getTruncStore(Store->getChain(), DL,
8396        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8397        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8398   }
8399 
8400   assert(VT.isVector() &&
8401          Store->getValue().getValueType().getScalarType() == MVT::i32);
8402 
8403   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8404                                       VT, *Store->getMemOperand())) {
8405     return expandUnalignedStore(Store, DAG);
8406   }
8407 
8408   unsigned AS = Store->getAddressSpace();
8409   if (Subtarget->hasLDSMisalignedBug() &&
8410       AS == AMDGPUAS::FLAT_ADDRESS &&
8411       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8412     return SplitVectorStore(Op, DAG);
8413   }
8414 
8415   MachineFunction &MF = DAG.getMachineFunction();
8416   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8417   // If there is a possibilty that flat instruction access scratch memory
8418   // then we need to use the same legalization rules we use for private.
8419   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8420       !Subtarget->hasMultiDwordFlatScratchAddressing())
8421     AS = MFI->hasFlatScratchInit() ?
8422          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8423 
8424   unsigned NumElements = VT.getVectorNumElements();
8425   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8426       AS == AMDGPUAS::FLAT_ADDRESS) {
8427     if (NumElements > 4)
8428       return SplitVectorStore(Op, DAG);
8429     // v3 stores not supported on SI.
8430     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8431       return SplitVectorStore(Op, DAG);
8432     return SDValue();
8433   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8434     switch (Subtarget->getMaxPrivateElementSize()) {
8435     case 4:
8436       return scalarizeVectorStore(Store, DAG);
8437     case 8:
8438       if (NumElements > 2)
8439         return SplitVectorStore(Op, DAG);
8440       return SDValue();
8441     case 16:
8442       if (NumElements > 4 || NumElements == 3)
8443         return SplitVectorStore(Op, DAG);
8444       return SDValue();
8445     default:
8446       llvm_unreachable("unsupported private_element_size");
8447     }
8448   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8449     // Use ds_write_b128 if possible.
8450     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8451         VT.getStoreSize() == 16 && NumElements != 3)
8452       return SDValue();
8453 
8454     if (NumElements > 2)
8455       return SplitVectorStore(Op, DAG);
8456 
8457     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8458     // address is negative, then the instruction is incorrectly treated as
8459     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8460     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8461     // store later in the SILoadStoreOptimizer.
8462     if (!Subtarget->hasUsableDSOffset() &&
8463         NumElements == 2 && VT.getStoreSize() == 8 &&
8464         Store->getAlignment() < 8) {
8465       return SplitVectorStore(Op, DAG);
8466     }
8467 
8468     return SDValue();
8469   } else {
8470     llvm_unreachable("unhandled address space");
8471   }
8472 }
8473 
8474 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8475   SDLoc DL(Op);
8476   EVT VT = Op.getValueType();
8477   SDValue Arg = Op.getOperand(0);
8478   SDValue TrigVal;
8479 
8480   // Propagate fast-math flags so that the multiply we introduce can be folded
8481   // if Arg is already the result of a multiply by constant.
8482   auto Flags = Op->getFlags();
8483 
8484   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8485 
8486   if (Subtarget->hasTrigReducedRange()) {
8487     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8488     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8489   } else {
8490     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8491   }
8492 
8493   switch (Op.getOpcode()) {
8494   case ISD::FCOS:
8495     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8496   case ISD::FSIN:
8497     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8498   default:
8499     llvm_unreachable("Wrong trig opcode");
8500   }
8501 }
8502 
8503 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8504   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8505   assert(AtomicNode->isCompareAndSwap());
8506   unsigned AS = AtomicNode->getAddressSpace();
8507 
8508   // No custom lowering required for local address space
8509   if (!isFlatGlobalAddrSpace(AS))
8510     return Op;
8511 
8512   // Non-local address space requires custom lowering for atomic compare
8513   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8514   SDLoc DL(Op);
8515   SDValue ChainIn = Op.getOperand(0);
8516   SDValue Addr = Op.getOperand(1);
8517   SDValue Old = Op.getOperand(2);
8518   SDValue New = Op.getOperand(3);
8519   EVT VT = Op.getValueType();
8520   MVT SimpleVT = VT.getSimpleVT();
8521   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8522 
8523   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8524   SDValue Ops[] = { ChainIn, Addr, NewOld };
8525 
8526   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8527                                  Ops, VT, AtomicNode->getMemOperand());
8528 }
8529 
8530 //===----------------------------------------------------------------------===//
8531 // Custom DAG optimizations
8532 //===----------------------------------------------------------------------===//
8533 
8534 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8535                                                      DAGCombinerInfo &DCI) const {
8536   EVT VT = N->getValueType(0);
8537   EVT ScalarVT = VT.getScalarType();
8538   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8539     return SDValue();
8540 
8541   SelectionDAG &DAG = DCI.DAG;
8542   SDLoc DL(N);
8543 
8544   SDValue Src = N->getOperand(0);
8545   EVT SrcVT = Src.getValueType();
8546 
8547   // TODO: We could try to match extracting the higher bytes, which would be
8548   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8549   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8550   // about in practice.
8551   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8552     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8553       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8554       DCI.AddToWorklist(Cvt.getNode());
8555 
8556       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8557       if (ScalarVT != MVT::f32) {
8558         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8559                           DAG.getTargetConstant(0, DL, MVT::i32));
8560       }
8561       return Cvt;
8562     }
8563   }
8564 
8565   return SDValue();
8566 }
8567 
8568 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8569 
8570 // This is a variant of
8571 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8572 //
8573 // The normal DAG combiner will do this, but only if the add has one use since
8574 // that would increase the number of instructions.
8575 //
8576 // This prevents us from seeing a constant offset that can be folded into a
8577 // memory instruction's addressing mode. If we know the resulting add offset of
8578 // a pointer can be folded into an addressing offset, we can replace the pointer
8579 // operand with the add of new constant offset. This eliminates one of the uses,
8580 // and may allow the remaining use to also be simplified.
8581 //
8582 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8583                                                unsigned AddrSpace,
8584                                                EVT MemVT,
8585                                                DAGCombinerInfo &DCI) const {
8586   SDValue N0 = N->getOperand(0);
8587   SDValue N1 = N->getOperand(1);
8588 
8589   // We only do this to handle cases where it's profitable when there are
8590   // multiple uses of the add, so defer to the standard combine.
8591   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8592       N0->hasOneUse())
8593     return SDValue();
8594 
8595   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8596   if (!CN1)
8597     return SDValue();
8598 
8599   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8600   if (!CAdd)
8601     return SDValue();
8602 
8603   // If the resulting offset is too large, we can't fold it into the addressing
8604   // mode offset.
8605   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8606   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8607 
8608   AddrMode AM;
8609   AM.HasBaseReg = true;
8610   AM.BaseOffs = Offset.getSExtValue();
8611   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8612     return SDValue();
8613 
8614   SelectionDAG &DAG = DCI.DAG;
8615   SDLoc SL(N);
8616   EVT VT = N->getValueType(0);
8617 
8618   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8619   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8620 
8621   SDNodeFlags Flags;
8622   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8623                           (N0.getOpcode() == ISD::OR ||
8624                            N0->getFlags().hasNoUnsignedWrap()));
8625 
8626   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8627 }
8628 
8629 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8630                                                   DAGCombinerInfo &DCI) const {
8631   SDValue Ptr = N->getBasePtr();
8632   SelectionDAG &DAG = DCI.DAG;
8633   SDLoc SL(N);
8634 
8635   // TODO: We could also do this for multiplies.
8636   if (Ptr.getOpcode() == ISD::SHL) {
8637     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8638                                           N->getMemoryVT(), DCI);
8639     if (NewPtr) {
8640       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8641 
8642       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8643       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8644     }
8645   }
8646 
8647   return SDValue();
8648 }
8649 
8650 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8651   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8652          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8653          (Opc == ISD::XOR && Val == 0);
8654 }
8655 
8656 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8657 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8658 // integer combine opportunities since most 64-bit operations are decomposed
8659 // this way.  TODO: We won't want this for SALU especially if it is an inline
8660 // immediate.
8661 SDValue SITargetLowering::splitBinaryBitConstantOp(
8662   DAGCombinerInfo &DCI,
8663   const SDLoc &SL,
8664   unsigned Opc, SDValue LHS,
8665   const ConstantSDNode *CRHS) const {
8666   uint64_t Val = CRHS->getZExtValue();
8667   uint32_t ValLo = Lo_32(Val);
8668   uint32_t ValHi = Hi_32(Val);
8669   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8670 
8671     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8672          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8673         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8674     // If we need to materialize a 64-bit immediate, it will be split up later
8675     // anyway. Avoid creating the harder to understand 64-bit immediate
8676     // materialization.
8677     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8678   }
8679 
8680   return SDValue();
8681 }
8682 
8683 // Returns true if argument is a boolean value which is not serialized into
8684 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8685 static bool isBoolSGPR(SDValue V) {
8686   if (V.getValueType() != MVT::i1)
8687     return false;
8688   switch (V.getOpcode()) {
8689   default: break;
8690   case ISD::SETCC:
8691   case ISD::AND:
8692   case ISD::OR:
8693   case ISD::XOR:
8694   case AMDGPUISD::FP_CLASS:
8695     return true;
8696   }
8697   return false;
8698 }
8699 
8700 // If a constant has all zeroes or all ones within each byte return it.
8701 // Otherwise return 0.
8702 static uint32_t getConstantPermuteMask(uint32_t C) {
8703   // 0xff for any zero byte in the mask
8704   uint32_t ZeroByteMask = 0;
8705   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8706   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8707   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8708   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8709   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8710   if ((NonZeroByteMask & C) != NonZeroByteMask)
8711     return 0; // Partial bytes selected.
8712   return C;
8713 }
8714 
8715 // Check if a node selects whole bytes from its operand 0 starting at a byte
8716 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8717 // or -1 if not succeeded.
8718 // Note byte select encoding:
8719 // value 0-3 selects corresponding source byte;
8720 // value 0xc selects zero;
8721 // value 0xff selects 0xff.
8722 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8723   assert(V.getValueSizeInBits() == 32);
8724 
8725   if (V.getNumOperands() != 2)
8726     return ~0;
8727 
8728   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8729   if (!N1)
8730     return ~0;
8731 
8732   uint32_t C = N1->getZExtValue();
8733 
8734   switch (V.getOpcode()) {
8735   default:
8736     break;
8737   case ISD::AND:
8738     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8739       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8740     }
8741     break;
8742 
8743   case ISD::OR:
8744     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8745       return (0x03020100 & ~ConstMask) | ConstMask;
8746     }
8747     break;
8748 
8749   case ISD::SHL:
8750     if (C % 8)
8751       return ~0;
8752 
8753     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8754 
8755   case ISD::SRL:
8756     if (C % 8)
8757       return ~0;
8758 
8759     return uint32_t(0x0c0c0c0c03020100ull >> C);
8760   }
8761 
8762   return ~0;
8763 }
8764 
8765 SDValue SITargetLowering::performAndCombine(SDNode *N,
8766                                             DAGCombinerInfo &DCI) const {
8767   if (DCI.isBeforeLegalize())
8768     return SDValue();
8769 
8770   SelectionDAG &DAG = DCI.DAG;
8771   EVT VT = N->getValueType(0);
8772   SDValue LHS = N->getOperand(0);
8773   SDValue RHS = N->getOperand(1);
8774 
8775 
8776   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8777   if (VT == MVT::i64 && CRHS) {
8778     if (SDValue Split
8779         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8780       return Split;
8781   }
8782 
8783   if (CRHS && VT == MVT::i32) {
8784     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8785     // nb = number of trailing zeroes in mask
8786     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8787     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8788     uint64_t Mask = CRHS->getZExtValue();
8789     unsigned Bits = countPopulation(Mask);
8790     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8791         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8792       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8793         unsigned Shift = CShift->getZExtValue();
8794         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8795         unsigned Offset = NB + Shift;
8796         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8797           SDLoc SL(N);
8798           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8799                                     LHS->getOperand(0),
8800                                     DAG.getConstant(Offset, SL, MVT::i32),
8801                                     DAG.getConstant(Bits, SL, MVT::i32));
8802           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8803           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8804                                     DAG.getValueType(NarrowVT));
8805           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8806                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8807           return Shl;
8808         }
8809       }
8810     }
8811 
8812     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8813     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8814         isa<ConstantSDNode>(LHS.getOperand(2))) {
8815       uint32_t Sel = getConstantPermuteMask(Mask);
8816       if (!Sel)
8817         return SDValue();
8818 
8819       // Select 0xc for all zero bytes
8820       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8821       SDLoc DL(N);
8822       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8823                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8824     }
8825   }
8826 
8827   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8828   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8829   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8830     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8831     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8832 
8833     SDValue X = LHS.getOperand(0);
8834     SDValue Y = RHS.getOperand(0);
8835     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8836       return SDValue();
8837 
8838     if (LCC == ISD::SETO) {
8839       if (X != LHS.getOperand(1))
8840         return SDValue();
8841 
8842       if (RCC == ISD::SETUNE) {
8843         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8844         if (!C1 || !C1->isInfinity() || C1->isNegative())
8845           return SDValue();
8846 
8847         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8848                               SIInstrFlags::N_SUBNORMAL |
8849                               SIInstrFlags::N_ZERO |
8850                               SIInstrFlags::P_ZERO |
8851                               SIInstrFlags::P_SUBNORMAL |
8852                               SIInstrFlags::P_NORMAL;
8853 
8854         static_assert(((~(SIInstrFlags::S_NAN |
8855                           SIInstrFlags::Q_NAN |
8856                           SIInstrFlags::N_INFINITY |
8857                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8858                       "mask not equal");
8859 
8860         SDLoc DL(N);
8861         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8862                            X, DAG.getConstant(Mask, DL, MVT::i32));
8863       }
8864     }
8865   }
8866 
8867   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8868     std::swap(LHS, RHS);
8869 
8870   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8871       RHS.hasOneUse()) {
8872     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8873     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8874     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8875     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8876     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8877         (RHS.getOperand(0) == LHS.getOperand(0) &&
8878          LHS.getOperand(0) == LHS.getOperand(1))) {
8879       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8880       unsigned NewMask = LCC == ISD::SETO ?
8881         Mask->getZExtValue() & ~OrdMask :
8882         Mask->getZExtValue() & OrdMask;
8883 
8884       SDLoc DL(N);
8885       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8886                          DAG.getConstant(NewMask, DL, MVT::i32));
8887     }
8888   }
8889 
8890   if (VT == MVT::i32 &&
8891       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8892     // and x, (sext cc from i1) => select cc, x, 0
8893     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8894       std::swap(LHS, RHS);
8895     if (isBoolSGPR(RHS.getOperand(0)))
8896       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8897                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8898   }
8899 
8900   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8901   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8902   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8903       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8904     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8905     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8906     if (LHSMask != ~0u && RHSMask != ~0u) {
8907       // Canonicalize the expression in an attempt to have fewer unique masks
8908       // and therefore fewer registers used to hold the masks.
8909       if (LHSMask > RHSMask) {
8910         std::swap(LHSMask, RHSMask);
8911         std::swap(LHS, RHS);
8912       }
8913 
8914       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8915       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8916       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8917       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8918 
8919       // Check of we need to combine values from two sources within a byte.
8920       if (!(LHSUsedLanes & RHSUsedLanes) &&
8921           // If we select high and lower word keep it for SDWA.
8922           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8923           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8924         // Each byte in each mask is either selector mask 0-3, or has higher
8925         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8926         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8927         // mask which is not 0xff wins. By anding both masks we have a correct
8928         // result except that 0x0c shall be corrected to give 0x0c only.
8929         uint32_t Mask = LHSMask & RHSMask;
8930         for (unsigned I = 0; I < 32; I += 8) {
8931           uint32_t ByteSel = 0xff << I;
8932           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8933             Mask &= (0x0c << I) & 0xffffffff;
8934         }
8935 
8936         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8937         // or 0x0c.
8938         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8939         SDLoc DL(N);
8940 
8941         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8942                            LHS.getOperand(0), RHS.getOperand(0),
8943                            DAG.getConstant(Sel, DL, MVT::i32));
8944       }
8945     }
8946   }
8947 
8948   return SDValue();
8949 }
8950 
8951 SDValue SITargetLowering::performOrCombine(SDNode *N,
8952                                            DAGCombinerInfo &DCI) const {
8953   SelectionDAG &DAG = DCI.DAG;
8954   SDValue LHS = N->getOperand(0);
8955   SDValue RHS = N->getOperand(1);
8956 
8957   EVT VT = N->getValueType(0);
8958   if (VT == MVT::i1) {
8959     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8960     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8961         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8962       SDValue Src = LHS.getOperand(0);
8963       if (Src != RHS.getOperand(0))
8964         return SDValue();
8965 
8966       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8967       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8968       if (!CLHS || !CRHS)
8969         return SDValue();
8970 
8971       // Only 10 bits are used.
8972       static const uint32_t MaxMask = 0x3ff;
8973 
8974       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8975       SDLoc DL(N);
8976       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8977                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8978     }
8979 
8980     return SDValue();
8981   }
8982 
8983   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8984   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8985       LHS.getOpcode() == AMDGPUISD::PERM &&
8986       isa<ConstantSDNode>(LHS.getOperand(2))) {
8987     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8988     if (!Sel)
8989       return SDValue();
8990 
8991     Sel |= LHS.getConstantOperandVal(2);
8992     SDLoc DL(N);
8993     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8994                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8995   }
8996 
8997   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8998   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8999   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9000       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9001     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9002     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9003     if (LHSMask != ~0u && RHSMask != ~0u) {
9004       // Canonicalize the expression in an attempt to have fewer unique masks
9005       // and therefore fewer registers used to hold the masks.
9006       if (LHSMask > RHSMask) {
9007         std::swap(LHSMask, RHSMask);
9008         std::swap(LHS, RHS);
9009       }
9010 
9011       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9012       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9013       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9014       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9015 
9016       // Check of we need to combine values from two sources within a byte.
9017       if (!(LHSUsedLanes & RHSUsedLanes) &&
9018           // If we select high and lower word keep it for SDWA.
9019           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9020           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9021         // Kill zero bytes selected by other mask. Zero value is 0xc.
9022         LHSMask &= ~RHSUsedLanes;
9023         RHSMask &= ~LHSUsedLanes;
9024         // Add 4 to each active LHS lane
9025         LHSMask |= LHSUsedLanes & 0x04040404;
9026         // Combine masks
9027         uint32_t Sel = LHSMask | RHSMask;
9028         SDLoc DL(N);
9029 
9030         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9031                            LHS.getOperand(0), RHS.getOperand(0),
9032                            DAG.getConstant(Sel, DL, MVT::i32));
9033       }
9034     }
9035   }
9036 
9037   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9038     return SDValue();
9039 
9040   // TODO: This could be a generic combine with a predicate for extracting the
9041   // high half of an integer being free.
9042 
9043   // (or i64:x, (zero_extend i32:y)) ->
9044   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9045   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9046       RHS.getOpcode() != ISD::ZERO_EXTEND)
9047     std::swap(LHS, RHS);
9048 
9049   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9050     SDValue ExtSrc = RHS.getOperand(0);
9051     EVT SrcVT = ExtSrc.getValueType();
9052     if (SrcVT == MVT::i32) {
9053       SDLoc SL(N);
9054       SDValue LowLHS, HiBits;
9055       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9056       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9057 
9058       DCI.AddToWorklist(LowOr.getNode());
9059       DCI.AddToWorklist(HiBits.getNode());
9060 
9061       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9062                                 LowOr, HiBits);
9063       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9064     }
9065   }
9066 
9067   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9068   if (CRHS) {
9069     if (SDValue Split
9070           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9071       return Split;
9072   }
9073 
9074   return SDValue();
9075 }
9076 
9077 SDValue SITargetLowering::performXorCombine(SDNode *N,
9078                                             DAGCombinerInfo &DCI) const {
9079   EVT VT = N->getValueType(0);
9080   if (VT != MVT::i64)
9081     return SDValue();
9082 
9083   SDValue LHS = N->getOperand(0);
9084   SDValue RHS = N->getOperand(1);
9085 
9086   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9087   if (CRHS) {
9088     if (SDValue Split
9089           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9090       return Split;
9091   }
9092 
9093   return SDValue();
9094 }
9095 
9096 // Instructions that will be lowered with a final instruction that zeros the
9097 // high result bits.
9098 // XXX - probably only need to list legal operations.
9099 static bool fp16SrcZerosHighBits(unsigned Opc) {
9100   switch (Opc) {
9101   case ISD::FADD:
9102   case ISD::FSUB:
9103   case ISD::FMUL:
9104   case ISD::FDIV:
9105   case ISD::FREM:
9106   case ISD::FMA:
9107   case ISD::FMAD:
9108   case ISD::FCANONICALIZE:
9109   case ISD::FP_ROUND:
9110   case ISD::UINT_TO_FP:
9111   case ISD::SINT_TO_FP:
9112   case ISD::FABS:
9113     // Fabs is lowered to a bit operation, but it's an and which will clear the
9114     // high bits anyway.
9115   case ISD::FSQRT:
9116   case ISD::FSIN:
9117   case ISD::FCOS:
9118   case ISD::FPOWI:
9119   case ISD::FPOW:
9120   case ISD::FLOG:
9121   case ISD::FLOG2:
9122   case ISD::FLOG10:
9123   case ISD::FEXP:
9124   case ISD::FEXP2:
9125   case ISD::FCEIL:
9126   case ISD::FTRUNC:
9127   case ISD::FRINT:
9128   case ISD::FNEARBYINT:
9129   case ISD::FROUND:
9130   case ISD::FFLOOR:
9131   case ISD::FMINNUM:
9132   case ISD::FMAXNUM:
9133   case AMDGPUISD::FRACT:
9134   case AMDGPUISD::CLAMP:
9135   case AMDGPUISD::COS_HW:
9136   case AMDGPUISD::SIN_HW:
9137   case AMDGPUISD::FMIN3:
9138   case AMDGPUISD::FMAX3:
9139   case AMDGPUISD::FMED3:
9140   case AMDGPUISD::FMAD_FTZ:
9141   case AMDGPUISD::RCP:
9142   case AMDGPUISD::RSQ:
9143   case AMDGPUISD::RCP_IFLAG:
9144   case AMDGPUISD::LDEXP:
9145     return true;
9146   default:
9147     // fcopysign, select and others may be lowered to 32-bit bit operations
9148     // which don't zero the high bits.
9149     return false;
9150   }
9151 }
9152 
9153 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9154                                                    DAGCombinerInfo &DCI) const {
9155   if (!Subtarget->has16BitInsts() ||
9156       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9157     return SDValue();
9158 
9159   EVT VT = N->getValueType(0);
9160   if (VT != MVT::i32)
9161     return SDValue();
9162 
9163   SDValue Src = N->getOperand(0);
9164   if (Src.getValueType() != MVT::i16)
9165     return SDValue();
9166 
9167   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9168   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9169   if (Src.getOpcode() == ISD::BITCAST) {
9170     SDValue BCSrc = Src.getOperand(0);
9171     if (BCSrc.getValueType() == MVT::f16 &&
9172         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9173       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9174   }
9175 
9176   return SDValue();
9177 }
9178 
9179 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9180                                                         DAGCombinerInfo &DCI)
9181                                                         const {
9182   SDValue Src = N->getOperand(0);
9183   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9184 
9185   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9186       VTSign->getVT() == MVT::i8) ||
9187       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9188       VTSign->getVT() == MVT::i16)) &&
9189       Src.hasOneUse()) {
9190     auto *M = cast<MemSDNode>(Src);
9191     SDValue Ops[] = {
9192       Src.getOperand(0), // Chain
9193       Src.getOperand(1), // rsrc
9194       Src.getOperand(2), // vindex
9195       Src.getOperand(3), // voffset
9196       Src.getOperand(4), // soffset
9197       Src.getOperand(5), // offset
9198       Src.getOperand(6),
9199       Src.getOperand(7)
9200     };
9201     // replace with BUFFER_LOAD_BYTE/SHORT
9202     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9203                                          Src.getOperand(0).getValueType());
9204     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9205                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9206     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9207                                                           ResList,
9208                                                           Ops, M->getMemoryVT(),
9209                                                           M->getMemOperand());
9210     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9211                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9212   }
9213   return SDValue();
9214 }
9215 
9216 SDValue SITargetLowering::performClassCombine(SDNode *N,
9217                                               DAGCombinerInfo &DCI) const {
9218   SelectionDAG &DAG = DCI.DAG;
9219   SDValue Mask = N->getOperand(1);
9220 
9221   // fp_class x, 0 -> false
9222   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9223     if (CMask->isNullValue())
9224       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9225   }
9226 
9227   if (N->getOperand(0).isUndef())
9228     return DAG.getUNDEF(MVT::i1);
9229 
9230   return SDValue();
9231 }
9232 
9233 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9234                                             DAGCombinerInfo &DCI) const {
9235   EVT VT = N->getValueType(0);
9236   SDValue N0 = N->getOperand(0);
9237 
9238   if (N0.isUndef())
9239     return N0;
9240 
9241   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9242                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9243     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9244                            N->getFlags());
9245   }
9246 
9247   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9248     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9249                            N0.getOperand(0), N->getFlags());
9250   }
9251 
9252   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9253 }
9254 
9255 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9256                                        unsigned MaxDepth) const {
9257   unsigned Opcode = Op.getOpcode();
9258   if (Opcode == ISD::FCANONICALIZE)
9259     return true;
9260 
9261   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9262     auto F = CFP->getValueAPF();
9263     if (F.isNaN() && F.isSignaling())
9264       return false;
9265     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9266   }
9267 
9268   // If source is a result of another standard FP operation it is already in
9269   // canonical form.
9270   if (MaxDepth == 0)
9271     return false;
9272 
9273   switch (Opcode) {
9274   // These will flush denorms if required.
9275   case ISD::FADD:
9276   case ISD::FSUB:
9277   case ISD::FMUL:
9278   case ISD::FCEIL:
9279   case ISD::FFLOOR:
9280   case ISD::FMA:
9281   case ISD::FMAD:
9282   case ISD::FSQRT:
9283   case ISD::FDIV:
9284   case ISD::FREM:
9285   case ISD::FP_ROUND:
9286   case ISD::FP_EXTEND:
9287   case AMDGPUISD::FMUL_LEGACY:
9288   case AMDGPUISD::FMAD_FTZ:
9289   case AMDGPUISD::RCP:
9290   case AMDGPUISD::RSQ:
9291   case AMDGPUISD::RSQ_CLAMP:
9292   case AMDGPUISD::RCP_LEGACY:
9293   case AMDGPUISD::RCP_IFLAG:
9294   case AMDGPUISD::DIV_SCALE:
9295   case AMDGPUISD::DIV_FMAS:
9296   case AMDGPUISD::DIV_FIXUP:
9297   case AMDGPUISD::FRACT:
9298   case AMDGPUISD::LDEXP:
9299   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9300   case AMDGPUISD::CVT_F32_UBYTE0:
9301   case AMDGPUISD::CVT_F32_UBYTE1:
9302   case AMDGPUISD::CVT_F32_UBYTE2:
9303   case AMDGPUISD::CVT_F32_UBYTE3:
9304     return true;
9305 
9306   // It can/will be lowered or combined as a bit operation.
9307   // Need to check their input recursively to handle.
9308   case ISD::FNEG:
9309   case ISD::FABS:
9310   case ISD::FCOPYSIGN:
9311     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9312 
9313   case ISD::FSIN:
9314   case ISD::FCOS:
9315   case ISD::FSINCOS:
9316     return Op.getValueType().getScalarType() != MVT::f16;
9317 
9318   case ISD::FMINNUM:
9319   case ISD::FMAXNUM:
9320   case ISD::FMINNUM_IEEE:
9321   case ISD::FMAXNUM_IEEE:
9322   case AMDGPUISD::CLAMP:
9323   case AMDGPUISD::FMED3:
9324   case AMDGPUISD::FMAX3:
9325   case AMDGPUISD::FMIN3: {
9326     // FIXME: Shouldn't treat the generic operations different based these.
9327     // However, we aren't really required to flush the result from
9328     // minnum/maxnum..
9329 
9330     // snans will be quieted, so we only need to worry about denormals.
9331     if (Subtarget->supportsMinMaxDenormModes() ||
9332         denormalsEnabledForType(DAG, Op.getValueType()))
9333       return true;
9334 
9335     // Flushing may be required.
9336     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9337     // targets need to check their input recursively.
9338 
9339     // FIXME: Does this apply with clamp? It's implemented with max.
9340     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9341       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9342         return false;
9343     }
9344 
9345     return true;
9346   }
9347   case ISD::SELECT: {
9348     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9349            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9350   }
9351   case ISD::BUILD_VECTOR: {
9352     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9353       SDValue SrcOp = Op.getOperand(i);
9354       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9355         return false;
9356     }
9357 
9358     return true;
9359   }
9360   case ISD::EXTRACT_VECTOR_ELT:
9361   case ISD::EXTRACT_SUBVECTOR: {
9362     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9363   }
9364   case ISD::INSERT_VECTOR_ELT: {
9365     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9366            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9367   }
9368   case ISD::UNDEF:
9369     // Could be anything.
9370     return false;
9371 
9372   case ISD::BITCAST: {
9373     // Hack round the mess we make when legalizing extract_vector_elt
9374     SDValue Src = Op.getOperand(0);
9375     if (Src.getValueType() == MVT::i16 &&
9376         Src.getOpcode() == ISD::TRUNCATE) {
9377       SDValue TruncSrc = Src.getOperand(0);
9378       if (TruncSrc.getValueType() == MVT::i32 &&
9379           TruncSrc.getOpcode() == ISD::BITCAST &&
9380           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9381         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9382       }
9383     }
9384 
9385     return false;
9386   }
9387   case ISD::INTRINSIC_WO_CHAIN: {
9388     unsigned IntrinsicID
9389       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9390     // TODO: Handle more intrinsics
9391     switch (IntrinsicID) {
9392     case Intrinsic::amdgcn_cvt_pkrtz:
9393     case Intrinsic::amdgcn_cubeid:
9394     case Intrinsic::amdgcn_frexp_mant:
9395     case Intrinsic::amdgcn_fdot2:
9396     case Intrinsic::amdgcn_rcp:
9397     case Intrinsic::amdgcn_rsq:
9398     case Intrinsic::amdgcn_rsq_clamp:
9399     case Intrinsic::amdgcn_rcp_legacy:
9400     case Intrinsic::amdgcn_rsq_legacy:
9401     case Intrinsic::amdgcn_trig_preop:
9402       return true;
9403     default:
9404       break;
9405     }
9406 
9407     LLVM_FALLTHROUGH;
9408   }
9409   default:
9410     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9411            DAG.isKnownNeverSNaN(Op);
9412   }
9413 
9414   llvm_unreachable("invalid operation");
9415 }
9416 
9417 // Constant fold canonicalize.
9418 SDValue SITargetLowering::getCanonicalConstantFP(
9419   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9420   // Flush denormals to 0 if not enabled.
9421   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9422     return DAG.getConstantFP(0.0, SL, VT);
9423 
9424   if (C.isNaN()) {
9425     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9426     if (C.isSignaling()) {
9427       // Quiet a signaling NaN.
9428       // FIXME: Is this supposed to preserve payload bits?
9429       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9430     }
9431 
9432     // Make sure it is the canonical NaN bitpattern.
9433     //
9434     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9435     // immediate?
9436     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9437       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9438   }
9439 
9440   // Already canonical.
9441   return DAG.getConstantFP(C, SL, VT);
9442 }
9443 
9444 static bool vectorEltWillFoldAway(SDValue Op) {
9445   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9446 }
9447 
9448 SDValue SITargetLowering::performFCanonicalizeCombine(
9449   SDNode *N,
9450   DAGCombinerInfo &DCI) const {
9451   SelectionDAG &DAG = DCI.DAG;
9452   SDValue N0 = N->getOperand(0);
9453   EVT VT = N->getValueType(0);
9454 
9455   // fcanonicalize undef -> qnan
9456   if (N0.isUndef()) {
9457     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9458     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9459   }
9460 
9461   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9462     EVT VT = N->getValueType(0);
9463     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9464   }
9465 
9466   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9467   //                                                   (fcanonicalize k)
9468   //
9469   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9470 
9471   // TODO: This could be better with wider vectors that will be split to v2f16,
9472   // and to consider uses since there aren't that many packed operations.
9473   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9474       isTypeLegal(MVT::v2f16)) {
9475     SDLoc SL(N);
9476     SDValue NewElts[2];
9477     SDValue Lo = N0.getOperand(0);
9478     SDValue Hi = N0.getOperand(1);
9479     EVT EltVT = Lo.getValueType();
9480 
9481     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9482       for (unsigned I = 0; I != 2; ++I) {
9483         SDValue Op = N0.getOperand(I);
9484         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9485           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9486                                               CFP->getValueAPF());
9487         } else if (Op.isUndef()) {
9488           // Handled below based on what the other operand is.
9489           NewElts[I] = Op;
9490         } else {
9491           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9492         }
9493       }
9494 
9495       // If one half is undef, and one is constant, perfer a splat vector rather
9496       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9497       // cheaper to use and may be free with a packed operation.
9498       if (NewElts[0].isUndef()) {
9499         if (isa<ConstantFPSDNode>(NewElts[1]))
9500           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9501             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9502       }
9503 
9504       if (NewElts[1].isUndef()) {
9505         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9506           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9507       }
9508 
9509       return DAG.getBuildVector(VT, SL, NewElts);
9510     }
9511   }
9512 
9513   unsigned SrcOpc = N0.getOpcode();
9514 
9515   // If it's free to do so, push canonicalizes further up the source, which may
9516   // find a canonical source.
9517   //
9518   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9519   // sNaNs.
9520   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9521     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9522     if (CRHS && N0.hasOneUse()) {
9523       SDLoc SL(N);
9524       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9525                                    N0.getOperand(0));
9526       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9527       DCI.AddToWorklist(Canon0.getNode());
9528 
9529       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9530     }
9531   }
9532 
9533   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9534 }
9535 
9536 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9537   switch (Opc) {
9538   case ISD::FMAXNUM:
9539   case ISD::FMAXNUM_IEEE:
9540     return AMDGPUISD::FMAX3;
9541   case ISD::SMAX:
9542     return AMDGPUISD::SMAX3;
9543   case ISD::UMAX:
9544     return AMDGPUISD::UMAX3;
9545   case ISD::FMINNUM:
9546   case ISD::FMINNUM_IEEE:
9547     return AMDGPUISD::FMIN3;
9548   case ISD::SMIN:
9549     return AMDGPUISD::SMIN3;
9550   case ISD::UMIN:
9551     return AMDGPUISD::UMIN3;
9552   default:
9553     llvm_unreachable("Not a min/max opcode");
9554   }
9555 }
9556 
9557 SDValue SITargetLowering::performIntMed3ImmCombine(
9558   SelectionDAG &DAG, const SDLoc &SL,
9559   SDValue Op0, SDValue Op1, bool Signed) const {
9560   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9561   if (!K1)
9562     return SDValue();
9563 
9564   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9565   if (!K0)
9566     return SDValue();
9567 
9568   if (Signed) {
9569     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9570       return SDValue();
9571   } else {
9572     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9573       return SDValue();
9574   }
9575 
9576   EVT VT = K0->getValueType(0);
9577   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9578   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9579     return DAG.getNode(Med3Opc, SL, VT,
9580                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9581   }
9582 
9583   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9584   MVT NVT = MVT::i32;
9585   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9586 
9587   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9588   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9589   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9590 
9591   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9592   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9593 }
9594 
9595 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9596   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9597     return C;
9598 
9599   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9600     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9601       return C;
9602   }
9603 
9604   return nullptr;
9605 }
9606 
9607 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9608                                                   const SDLoc &SL,
9609                                                   SDValue Op0,
9610                                                   SDValue Op1) const {
9611   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9612   if (!K1)
9613     return SDValue();
9614 
9615   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9616   if (!K0)
9617     return SDValue();
9618 
9619   // Ordered >= (although NaN inputs should have folded away by now).
9620   if (K0->getValueAPF() > K1->getValueAPF())
9621     return SDValue();
9622 
9623   const MachineFunction &MF = DAG.getMachineFunction();
9624   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9625 
9626   // TODO: Check IEEE bit enabled?
9627   EVT VT = Op0.getValueType();
9628   if (Info->getMode().DX10Clamp) {
9629     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9630     // hardware fmed3 behavior converting to a min.
9631     // FIXME: Should this be allowing -0.0?
9632     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9633       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9634   }
9635 
9636   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9637   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9638     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9639     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9640     // then give the other result, which is different from med3 with a NaN
9641     // input.
9642     SDValue Var = Op0.getOperand(0);
9643     if (!DAG.isKnownNeverSNaN(Var))
9644       return SDValue();
9645 
9646     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9647 
9648     if ((!K0->hasOneUse() ||
9649          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9650         (!K1->hasOneUse() ||
9651          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9652       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9653                          Var, SDValue(K0, 0), SDValue(K1, 0));
9654     }
9655   }
9656 
9657   return SDValue();
9658 }
9659 
9660 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9661                                                DAGCombinerInfo &DCI) const {
9662   SelectionDAG &DAG = DCI.DAG;
9663 
9664   EVT VT = N->getValueType(0);
9665   unsigned Opc = N->getOpcode();
9666   SDValue Op0 = N->getOperand(0);
9667   SDValue Op1 = N->getOperand(1);
9668 
9669   // Only do this if the inner op has one use since this will just increases
9670   // register pressure for no benefit.
9671 
9672   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9673       !VT.isVector() &&
9674       (VT == MVT::i32 || VT == MVT::f32 ||
9675        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9676     // max(max(a, b), c) -> max3(a, b, c)
9677     // min(min(a, b), c) -> min3(a, b, c)
9678     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9679       SDLoc DL(N);
9680       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9681                          DL,
9682                          N->getValueType(0),
9683                          Op0.getOperand(0),
9684                          Op0.getOperand(1),
9685                          Op1);
9686     }
9687 
9688     // Try commuted.
9689     // max(a, max(b, c)) -> max3(a, b, c)
9690     // min(a, min(b, c)) -> min3(a, b, c)
9691     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9692       SDLoc DL(N);
9693       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9694                          DL,
9695                          N->getValueType(0),
9696                          Op0,
9697                          Op1.getOperand(0),
9698                          Op1.getOperand(1));
9699     }
9700   }
9701 
9702   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9703   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9704     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9705       return Med3;
9706   }
9707 
9708   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9709     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9710       return Med3;
9711   }
9712 
9713   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9714   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9715        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9716        (Opc == AMDGPUISD::FMIN_LEGACY &&
9717         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9718       (VT == MVT::f32 || VT == MVT::f64 ||
9719        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9720        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9721       Op0.hasOneUse()) {
9722     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9723       return Res;
9724   }
9725 
9726   return SDValue();
9727 }
9728 
9729 static bool isClampZeroToOne(SDValue A, SDValue B) {
9730   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9731     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9732       // FIXME: Should this be allowing -0.0?
9733       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9734              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9735     }
9736   }
9737 
9738   return false;
9739 }
9740 
9741 // FIXME: Should only worry about snans for version with chain.
9742 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9743                                               DAGCombinerInfo &DCI) const {
9744   EVT VT = N->getValueType(0);
9745   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9746   // NaNs. With a NaN input, the order of the operands may change the result.
9747 
9748   SelectionDAG &DAG = DCI.DAG;
9749   SDLoc SL(N);
9750 
9751   SDValue Src0 = N->getOperand(0);
9752   SDValue Src1 = N->getOperand(1);
9753   SDValue Src2 = N->getOperand(2);
9754 
9755   if (isClampZeroToOne(Src0, Src1)) {
9756     // const_a, const_b, x -> clamp is safe in all cases including signaling
9757     // nans.
9758     // FIXME: Should this be allowing -0.0?
9759     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9760   }
9761 
9762   const MachineFunction &MF = DAG.getMachineFunction();
9763   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9764 
9765   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9766   // handling no dx10-clamp?
9767   if (Info->getMode().DX10Clamp) {
9768     // If NaNs is clamped to 0, we are free to reorder the inputs.
9769 
9770     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9771       std::swap(Src0, Src1);
9772 
9773     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9774       std::swap(Src1, Src2);
9775 
9776     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9777       std::swap(Src0, Src1);
9778 
9779     if (isClampZeroToOne(Src1, Src2))
9780       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9781   }
9782 
9783   return SDValue();
9784 }
9785 
9786 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9787                                                  DAGCombinerInfo &DCI) const {
9788   SDValue Src0 = N->getOperand(0);
9789   SDValue Src1 = N->getOperand(1);
9790   if (Src0.isUndef() && Src1.isUndef())
9791     return DCI.DAG.getUNDEF(N->getValueType(0));
9792   return SDValue();
9793 }
9794 
9795 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9796 // expanded into a set of cmp/select instructions.
9797 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9798                                                 unsigned NumElem,
9799                                                 bool IsDivergentIdx) {
9800   if (UseDivergentRegisterIndexing)
9801     return false;
9802 
9803   unsigned VecSize = EltSize * NumElem;
9804 
9805   // Sub-dword vectors of size 2 dword or less have better implementation.
9806   if (VecSize <= 64 && EltSize < 32)
9807     return false;
9808 
9809   // Always expand the rest of sub-dword instructions, otherwise it will be
9810   // lowered via memory.
9811   if (EltSize < 32)
9812     return true;
9813 
9814   // Always do this if var-idx is divergent, otherwise it will become a loop.
9815   if (IsDivergentIdx)
9816     return true;
9817 
9818   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9819   unsigned NumInsts = NumElem /* Number of compares */ +
9820                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9821   return NumInsts <= 16;
9822 }
9823 
9824 static bool shouldExpandVectorDynExt(SDNode *N) {
9825   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9826   if (isa<ConstantSDNode>(Idx))
9827     return false;
9828 
9829   SDValue Vec = N->getOperand(0);
9830   EVT VecVT = Vec.getValueType();
9831   EVT EltVT = VecVT.getVectorElementType();
9832   unsigned EltSize = EltVT.getSizeInBits();
9833   unsigned NumElem = VecVT.getVectorNumElements();
9834 
9835   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9836                                                     Idx->isDivergent());
9837 }
9838 
9839 SDValue SITargetLowering::performExtractVectorEltCombine(
9840   SDNode *N, DAGCombinerInfo &DCI) const {
9841   SDValue Vec = N->getOperand(0);
9842   SelectionDAG &DAG = DCI.DAG;
9843 
9844   EVT VecVT = Vec.getValueType();
9845   EVT EltVT = VecVT.getVectorElementType();
9846 
9847   if ((Vec.getOpcode() == ISD::FNEG ||
9848        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9849     SDLoc SL(N);
9850     EVT EltVT = N->getValueType(0);
9851     SDValue Idx = N->getOperand(1);
9852     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9853                               Vec.getOperand(0), Idx);
9854     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9855   }
9856 
9857   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9858   //    =>
9859   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9860   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9861   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9862   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9863     SDLoc SL(N);
9864     EVT EltVT = N->getValueType(0);
9865     SDValue Idx = N->getOperand(1);
9866     unsigned Opc = Vec.getOpcode();
9867 
9868     switch(Opc) {
9869     default:
9870       break;
9871       // TODO: Support other binary operations.
9872     case ISD::FADD:
9873     case ISD::FSUB:
9874     case ISD::FMUL:
9875     case ISD::ADD:
9876     case ISD::UMIN:
9877     case ISD::UMAX:
9878     case ISD::SMIN:
9879     case ISD::SMAX:
9880     case ISD::FMAXNUM:
9881     case ISD::FMINNUM:
9882     case ISD::FMAXNUM_IEEE:
9883     case ISD::FMINNUM_IEEE: {
9884       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9885                                  Vec.getOperand(0), Idx);
9886       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9887                                  Vec.getOperand(1), Idx);
9888 
9889       DCI.AddToWorklist(Elt0.getNode());
9890       DCI.AddToWorklist(Elt1.getNode());
9891       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9892     }
9893     }
9894   }
9895 
9896   unsigned VecSize = VecVT.getSizeInBits();
9897   unsigned EltSize = EltVT.getSizeInBits();
9898 
9899   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9900   if (::shouldExpandVectorDynExt(N)) {
9901     SDLoc SL(N);
9902     SDValue Idx = N->getOperand(1);
9903     SDValue V;
9904     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9905       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9906       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9907       if (I == 0)
9908         V = Elt;
9909       else
9910         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9911     }
9912     return V;
9913   }
9914 
9915   if (!DCI.isBeforeLegalize())
9916     return SDValue();
9917 
9918   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9919   // elements. This exposes more load reduction opportunities by replacing
9920   // multiple small extract_vector_elements with a single 32-bit extract.
9921   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9922   if (isa<MemSDNode>(Vec) &&
9923       EltSize <= 16 &&
9924       EltVT.isByteSized() &&
9925       VecSize > 32 &&
9926       VecSize % 32 == 0 &&
9927       Idx) {
9928     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9929 
9930     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9931     unsigned EltIdx = BitIndex / 32;
9932     unsigned LeftoverBitIdx = BitIndex % 32;
9933     SDLoc SL(N);
9934 
9935     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9936     DCI.AddToWorklist(Cast.getNode());
9937 
9938     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9939                               DAG.getConstant(EltIdx, SL, MVT::i32));
9940     DCI.AddToWorklist(Elt.getNode());
9941     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9942                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9943     DCI.AddToWorklist(Srl.getNode());
9944 
9945     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9946     DCI.AddToWorklist(Trunc.getNode());
9947     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9948   }
9949 
9950   return SDValue();
9951 }
9952 
9953 SDValue
9954 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9955                                                 DAGCombinerInfo &DCI) const {
9956   SDValue Vec = N->getOperand(0);
9957   SDValue Idx = N->getOperand(2);
9958   EVT VecVT = Vec.getValueType();
9959   EVT EltVT = VecVT.getVectorElementType();
9960 
9961   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9962   // => BUILD_VECTOR n x select (e, const-idx)
9963   if (!::shouldExpandVectorDynExt(N))
9964     return SDValue();
9965 
9966   SelectionDAG &DAG = DCI.DAG;
9967   SDLoc SL(N);
9968   SDValue Ins = N->getOperand(1);
9969   EVT IdxVT = Idx.getValueType();
9970 
9971   SmallVector<SDValue, 16> Ops;
9972   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9973     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9974     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9975     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9976     Ops.push_back(V);
9977   }
9978 
9979   return DAG.getBuildVector(VecVT, SL, Ops);
9980 }
9981 
9982 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9983                                           const SDNode *N0,
9984                                           const SDNode *N1) const {
9985   EVT VT = N0->getValueType(0);
9986 
9987   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9988   // support denormals ever.
9989   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9990        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9991         getSubtarget()->hasMadF16())) &&
9992        isOperationLegal(ISD::FMAD, VT))
9993     return ISD::FMAD;
9994 
9995   const TargetOptions &Options = DAG.getTarget().Options;
9996   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9997        (N0->getFlags().hasAllowContract() &&
9998         N1->getFlags().hasAllowContract())) &&
9999       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10000     return ISD::FMA;
10001   }
10002 
10003   return 0;
10004 }
10005 
10006 // For a reassociatable opcode perform:
10007 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10008 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10009                                                SelectionDAG &DAG) const {
10010   EVT VT = N->getValueType(0);
10011   if (VT != MVT::i32 && VT != MVT::i64)
10012     return SDValue();
10013 
10014   unsigned Opc = N->getOpcode();
10015   SDValue Op0 = N->getOperand(0);
10016   SDValue Op1 = N->getOperand(1);
10017 
10018   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10019     return SDValue();
10020 
10021   if (Op0->isDivergent())
10022     std::swap(Op0, Op1);
10023 
10024   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10025     return SDValue();
10026 
10027   SDValue Op2 = Op1.getOperand(1);
10028   Op1 = Op1.getOperand(0);
10029   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10030     return SDValue();
10031 
10032   if (Op1->isDivergent())
10033     std::swap(Op1, Op2);
10034 
10035   // If either operand is constant this will conflict with
10036   // DAGCombiner::ReassociateOps().
10037   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10038       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10039     return SDValue();
10040 
10041   SDLoc SL(N);
10042   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10043   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10044 }
10045 
10046 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10047                            EVT VT,
10048                            SDValue N0, SDValue N1, SDValue N2,
10049                            bool Signed) {
10050   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10051   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10052   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10053   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10054 }
10055 
10056 SDValue SITargetLowering::performAddCombine(SDNode *N,
10057                                             DAGCombinerInfo &DCI) const {
10058   SelectionDAG &DAG = DCI.DAG;
10059   EVT VT = N->getValueType(0);
10060   SDLoc SL(N);
10061   SDValue LHS = N->getOperand(0);
10062   SDValue RHS = N->getOperand(1);
10063 
10064   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10065       && Subtarget->hasMad64_32() &&
10066       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10067       VT.getScalarSizeInBits() <= 64) {
10068     if (LHS.getOpcode() != ISD::MUL)
10069       std::swap(LHS, RHS);
10070 
10071     SDValue MulLHS = LHS.getOperand(0);
10072     SDValue MulRHS = LHS.getOperand(1);
10073     SDValue AddRHS = RHS;
10074 
10075     // TODO: Maybe restrict if SGPR inputs.
10076     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10077         numBitsUnsigned(MulRHS, DAG) <= 32) {
10078       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10079       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10080       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10081       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10082     }
10083 
10084     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10085       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10086       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10087       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10088       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10089     }
10090 
10091     return SDValue();
10092   }
10093 
10094   if (SDValue V = reassociateScalarOps(N, DAG)) {
10095     return V;
10096   }
10097 
10098   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10099     return SDValue();
10100 
10101   // add x, zext (setcc) => addcarry x, 0, setcc
10102   // add x, sext (setcc) => subcarry x, 0, setcc
10103   unsigned Opc = LHS.getOpcode();
10104   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10105       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10106     std::swap(RHS, LHS);
10107 
10108   Opc = RHS.getOpcode();
10109   switch (Opc) {
10110   default: break;
10111   case ISD::ZERO_EXTEND:
10112   case ISD::SIGN_EXTEND:
10113   case ISD::ANY_EXTEND: {
10114     auto Cond = RHS.getOperand(0);
10115     // If this won't be a real VOPC output, we would still need to insert an
10116     // extra instruction anyway.
10117     if (!isBoolSGPR(Cond))
10118       break;
10119     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10120     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10121     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10122     return DAG.getNode(Opc, SL, VTList, Args);
10123   }
10124   case ISD::ADDCARRY: {
10125     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10126     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10127     if (!C || C->getZExtValue() != 0) break;
10128     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10129     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10130   }
10131   }
10132   return SDValue();
10133 }
10134 
10135 SDValue SITargetLowering::performSubCombine(SDNode *N,
10136                                             DAGCombinerInfo &DCI) const {
10137   SelectionDAG &DAG = DCI.DAG;
10138   EVT VT = N->getValueType(0);
10139 
10140   if (VT != MVT::i32)
10141     return SDValue();
10142 
10143   SDLoc SL(N);
10144   SDValue LHS = N->getOperand(0);
10145   SDValue RHS = N->getOperand(1);
10146 
10147   // sub x, zext (setcc) => subcarry x, 0, setcc
10148   // sub x, sext (setcc) => addcarry x, 0, setcc
10149   unsigned Opc = RHS.getOpcode();
10150   switch (Opc) {
10151   default: break;
10152   case ISD::ZERO_EXTEND:
10153   case ISD::SIGN_EXTEND:
10154   case ISD::ANY_EXTEND: {
10155     auto Cond = RHS.getOperand(0);
10156     // If this won't be a real VOPC output, we would still need to insert an
10157     // extra instruction anyway.
10158     if (!isBoolSGPR(Cond))
10159       break;
10160     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10161     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10162     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10163     return DAG.getNode(Opc, SL, VTList, Args);
10164   }
10165   }
10166 
10167   if (LHS.getOpcode() == ISD::SUBCARRY) {
10168     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10169     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10170     if (!C || !C->isNullValue())
10171       return SDValue();
10172     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10173     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10174   }
10175   return SDValue();
10176 }
10177 
10178 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10179   DAGCombinerInfo &DCI) const {
10180 
10181   if (N->getValueType(0) != MVT::i32)
10182     return SDValue();
10183 
10184   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10185   if (!C || C->getZExtValue() != 0)
10186     return SDValue();
10187 
10188   SelectionDAG &DAG = DCI.DAG;
10189   SDValue LHS = N->getOperand(0);
10190 
10191   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10192   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10193   unsigned LHSOpc = LHS.getOpcode();
10194   unsigned Opc = N->getOpcode();
10195   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10196       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10197     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10198     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10199   }
10200   return SDValue();
10201 }
10202 
10203 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10204                                              DAGCombinerInfo &DCI) const {
10205   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10206     return SDValue();
10207 
10208   SelectionDAG &DAG = DCI.DAG;
10209   EVT VT = N->getValueType(0);
10210 
10211   SDLoc SL(N);
10212   SDValue LHS = N->getOperand(0);
10213   SDValue RHS = N->getOperand(1);
10214 
10215   // These should really be instruction patterns, but writing patterns with
10216   // source modiifiers is a pain.
10217 
10218   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10219   if (LHS.getOpcode() == ISD::FADD) {
10220     SDValue A = LHS.getOperand(0);
10221     if (A == LHS.getOperand(1)) {
10222       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10223       if (FusedOp != 0) {
10224         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10225         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10226       }
10227     }
10228   }
10229 
10230   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10231   if (RHS.getOpcode() == ISD::FADD) {
10232     SDValue A = RHS.getOperand(0);
10233     if (A == RHS.getOperand(1)) {
10234       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10235       if (FusedOp != 0) {
10236         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10237         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10238       }
10239     }
10240   }
10241 
10242   return SDValue();
10243 }
10244 
10245 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10246                                              DAGCombinerInfo &DCI) const {
10247   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10248     return SDValue();
10249 
10250   SelectionDAG &DAG = DCI.DAG;
10251   SDLoc SL(N);
10252   EVT VT = N->getValueType(0);
10253   assert(!VT.isVector());
10254 
10255   // Try to get the fneg to fold into the source modifier. This undoes generic
10256   // DAG combines and folds them into the mad.
10257   //
10258   // Only do this if we are not trying to support denormals. v_mad_f32 does
10259   // not support denormals ever.
10260   SDValue LHS = N->getOperand(0);
10261   SDValue RHS = N->getOperand(1);
10262   if (LHS.getOpcode() == ISD::FADD) {
10263     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10264     SDValue A = LHS.getOperand(0);
10265     if (A == LHS.getOperand(1)) {
10266       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10267       if (FusedOp != 0){
10268         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10269         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10270 
10271         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10272       }
10273     }
10274   }
10275 
10276   if (RHS.getOpcode() == ISD::FADD) {
10277     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10278 
10279     SDValue A = RHS.getOperand(0);
10280     if (A == RHS.getOperand(1)) {
10281       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10282       if (FusedOp != 0){
10283         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10284         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10285       }
10286     }
10287   }
10288 
10289   return SDValue();
10290 }
10291 
10292 SDValue SITargetLowering::performFMACombine(SDNode *N,
10293                                             DAGCombinerInfo &DCI) const {
10294   SelectionDAG &DAG = DCI.DAG;
10295   EVT VT = N->getValueType(0);
10296   SDLoc SL(N);
10297 
10298   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10299     return SDValue();
10300 
10301   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10302   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10303   SDValue Op1 = N->getOperand(0);
10304   SDValue Op2 = N->getOperand(1);
10305   SDValue FMA = N->getOperand(2);
10306 
10307   if (FMA.getOpcode() != ISD::FMA ||
10308       Op1.getOpcode() != ISD::FP_EXTEND ||
10309       Op2.getOpcode() != ISD::FP_EXTEND)
10310     return SDValue();
10311 
10312   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10313   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10314   // is sufficient to allow generaing fdot2.
10315   const TargetOptions &Options = DAG.getTarget().Options;
10316   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10317       (N->getFlags().hasAllowContract() &&
10318        FMA->getFlags().hasAllowContract())) {
10319     Op1 = Op1.getOperand(0);
10320     Op2 = Op2.getOperand(0);
10321     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10322         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10323       return SDValue();
10324 
10325     SDValue Vec1 = Op1.getOperand(0);
10326     SDValue Idx1 = Op1.getOperand(1);
10327     SDValue Vec2 = Op2.getOperand(0);
10328 
10329     SDValue FMAOp1 = FMA.getOperand(0);
10330     SDValue FMAOp2 = FMA.getOperand(1);
10331     SDValue FMAAcc = FMA.getOperand(2);
10332 
10333     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10334         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10335       return SDValue();
10336 
10337     FMAOp1 = FMAOp1.getOperand(0);
10338     FMAOp2 = FMAOp2.getOperand(0);
10339     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10340         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10341       return SDValue();
10342 
10343     SDValue Vec3 = FMAOp1.getOperand(0);
10344     SDValue Vec4 = FMAOp2.getOperand(0);
10345     SDValue Idx2 = FMAOp1.getOperand(1);
10346 
10347     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10348         // Idx1 and Idx2 cannot be the same.
10349         Idx1 == Idx2)
10350       return SDValue();
10351 
10352     if (Vec1 == Vec2 || Vec3 == Vec4)
10353       return SDValue();
10354 
10355     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10356       return SDValue();
10357 
10358     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10359         (Vec1 == Vec4 && Vec2 == Vec3)) {
10360       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10361                          DAG.getTargetConstant(0, SL, MVT::i1));
10362     }
10363   }
10364   return SDValue();
10365 }
10366 
10367 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10368                                               DAGCombinerInfo &DCI) const {
10369   SelectionDAG &DAG = DCI.DAG;
10370   SDLoc SL(N);
10371 
10372   SDValue LHS = N->getOperand(0);
10373   SDValue RHS = N->getOperand(1);
10374   EVT VT = LHS.getValueType();
10375   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10376 
10377   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10378   if (!CRHS) {
10379     CRHS = dyn_cast<ConstantSDNode>(LHS);
10380     if (CRHS) {
10381       std::swap(LHS, RHS);
10382       CC = getSetCCSwappedOperands(CC);
10383     }
10384   }
10385 
10386   if (CRHS) {
10387     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10388         isBoolSGPR(LHS.getOperand(0))) {
10389       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10390       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10391       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10392       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10393       if ((CRHS->isAllOnesValue() &&
10394            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10395           (CRHS->isNullValue() &&
10396            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10397         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10398                            DAG.getConstant(-1, SL, MVT::i1));
10399       if ((CRHS->isAllOnesValue() &&
10400            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10401           (CRHS->isNullValue() &&
10402            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10403         return LHS.getOperand(0);
10404     }
10405 
10406     uint64_t CRHSVal = CRHS->getZExtValue();
10407     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10408         LHS.getOpcode() == ISD::SELECT &&
10409         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10410         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10411         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10412         isBoolSGPR(LHS.getOperand(0))) {
10413       // Given CT != FT:
10414       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10415       // setcc (select cc, CT, CF), CF, ne => cc
10416       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10417       // setcc (select cc, CT, CF), CT, eq => cc
10418       uint64_t CT = LHS.getConstantOperandVal(1);
10419       uint64_t CF = LHS.getConstantOperandVal(2);
10420 
10421       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10422           (CT == CRHSVal && CC == ISD::SETNE))
10423         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10424                            DAG.getConstant(-1, SL, MVT::i1));
10425       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10426           (CT == CRHSVal && CC == ISD::SETEQ))
10427         return LHS.getOperand(0);
10428     }
10429   }
10430 
10431   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10432                                            VT != MVT::f16))
10433     return SDValue();
10434 
10435   // Match isinf/isfinite pattern
10436   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10437   // (fcmp one (fabs x), inf) -> (fp_class x,
10438   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10439   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10440     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10441     if (!CRHS)
10442       return SDValue();
10443 
10444     const APFloat &APF = CRHS->getValueAPF();
10445     if (APF.isInfinity() && !APF.isNegative()) {
10446       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10447                                  SIInstrFlags::N_INFINITY;
10448       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10449                                     SIInstrFlags::P_ZERO |
10450                                     SIInstrFlags::N_NORMAL |
10451                                     SIInstrFlags::P_NORMAL |
10452                                     SIInstrFlags::N_SUBNORMAL |
10453                                     SIInstrFlags::P_SUBNORMAL;
10454       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10455       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10456                          DAG.getConstant(Mask, SL, MVT::i32));
10457     }
10458   }
10459 
10460   return SDValue();
10461 }
10462 
10463 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10464                                                      DAGCombinerInfo &DCI) const {
10465   SelectionDAG &DAG = DCI.DAG;
10466   SDLoc SL(N);
10467   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10468 
10469   SDValue Src = N->getOperand(0);
10470   SDValue Shift = N->getOperand(0);
10471 
10472   // TODO: Extend type shouldn't matter (assuming legal types).
10473   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10474     Shift = Shift.getOperand(0);
10475 
10476   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10477     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10478     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10479     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10480     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10481     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10482     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10483       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10484                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10485 
10486       unsigned ShiftOffset = 8 * Offset;
10487       if (Shift.getOpcode() == ISD::SHL)
10488         ShiftOffset -= C->getZExtValue();
10489       else
10490         ShiftOffset += C->getZExtValue();
10491 
10492       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10493         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10494                            MVT::f32, Shift);
10495       }
10496     }
10497   }
10498 
10499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10500   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10501   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10502     // We simplified Src. If this node is not dead, visit it again so it is
10503     // folded properly.
10504     if (N->getOpcode() != ISD::DELETED_NODE)
10505       DCI.AddToWorklist(N);
10506     return SDValue(N, 0);
10507   }
10508 
10509   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10510   if (SDValue DemandedSrc =
10511           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10512     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10513 
10514   return SDValue();
10515 }
10516 
10517 SDValue SITargetLowering::performClampCombine(SDNode *N,
10518                                               DAGCombinerInfo &DCI) const {
10519   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10520   if (!CSrc)
10521     return SDValue();
10522 
10523   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10524   const APFloat &F = CSrc->getValueAPF();
10525   APFloat Zero = APFloat::getZero(F.getSemantics());
10526   if (F < Zero ||
10527       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10528     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10529   }
10530 
10531   APFloat One(F.getSemantics(), "1.0");
10532   if (F > One)
10533     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10534 
10535   return SDValue(CSrc, 0);
10536 }
10537 
10538 
10539 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10540                                             DAGCombinerInfo &DCI) const {
10541   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10542     return SDValue();
10543   switch (N->getOpcode()) {
10544   default:
10545     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10546   case ISD::ADD:
10547     return performAddCombine(N, DCI);
10548   case ISD::SUB:
10549     return performSubCombine(N, DCI);
10550   case ISD::ADDCARRY:
10551   case ISD::SUBCARRY:
10552     return performAddCarrySubCarryCombine(N, DCI);
10553   case ISD::FADD:
10554     return performFAddCombine(N, DCI);
10555   case ISD::FSUB:
10556     return performFSubCombine(N, DCI);
10557   case ISD::SETCC:
10558     return performSetCCCombine(N, DCI);
10559   case ISD::FMAXNUM:
10560   case ISD::FMINNUM:
10561   case ISD::FMAXNUM_IEEE:
10562   case ISD::FMINNUM_IEEE:
10563   case ISD::SMAX:
10564   case ISD::SMIN:
10565   case ISD::UMAX:
10566   case ISD::UMIN:
10567   case AMDGPUISD::FMIN_LEGACY:
10568   case AMDGPUISD::FMAX_LEGACY:
10569     return performMinMaxCombine(N, DCI);
10570   case ISD::FMA:
10571     return performFMACombine(N, DCI);
10572   case ISD::LOAD: {
10573     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10574       return Widended;
10575     LLVM_FALLTHROUGH;
10576   }
10577   case ISD::STORE:
10578   case ISD::ATOMIC_LOAD:
10579   case ISD::ATOMIC_STORE:
10580   case ISD::ATOMIC_CMP_SWAP:
10581   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10582   case ISD::ATOMIC_SWAP:
10583   case ISD::ATOMIC_LOAD_ADD:
10584   case ISD::ATOMIC_LOAD_SUB:
10585   case ISD::ATOMIC_LOAD_AND:
10586   case ISD::ATOMIC_LOAD_OR:
10587   case ISD::ATOMIC_LOAD_XOR:
10588   case ISD::ATOMIC_LOAD_NAND:
10589   case ISD::ATOMIC_LOAD_MIN:
10590   case ISD::ATOMIC_LOAD_MAX:
10591   case ISD::ATOMIC_LOAD_UMIN:
10592   case ISD::ATOMIC_LOAD_UMAX:
10593   case ISD::ATOMIC_LOAD_FADD:
10594   case AMDGPUISD::ATOMIC_INC:
10595   case AMDGPUISD::ATOMIC_DEC:
10596   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10597   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10598     if (DCI.isBeforeLegalize())
10599       break;
10600     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10601   case ISD::AND:
10602     return performAndCombine(N, DCI);
10603   case ISD::OR:
10604     return performOrCombine(N, DCI);
10605   case ISD::XOR:
10606     return performXorCombine(N, DCI);
10607   case ISD::ZERO_EXTEND:
10608     return performZeroExtendCombine(N, DCI);
10609   case ISD::SIGN_EXTEND_INREG:
10610     return performSignExtendInRegCombine(N , DCI);
10611   case AMDGPUISD::FP_CLASS:
10612     return performClassCombine(N, DCI);
10613   case ISD::FCANONICALIZE:
10614     return performFCanonicalizeCombine(N, DCI);
10615   case AMDGPUISD::RCP:
10616     return performRcpCombine(N, DCI);
10617   case AMDGPUISD::FRACT:
10618   case AMDGPUISD::RSQ:
10619   case AMDGPUISD::RCP_LEGACY:
10620   case AMDGPUISD::RCP_IFLAG:
10621   case AMDGPUISD::RSQ_CLAMP:
10622   case AMDGPUISD::LDEXP: {
10623     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10624     SDValue Src = N->getOperand(0);
10625     if (Src.isUndef())
10626       return Src;
10627     break;
10628   }
10629   case ISD::SINT_TO_FP:
10630   case ISD::UINT_TO_FP:
10631     return performUCharToFloatCombine(N, DCI);
10632   case AMDGPUISD::CVT_F32_UBYTE0:
10633   case AMDGPUISD::CVT_F32_UBYTE1:
10634   case AMDGPUISD::CVT_F32_UBYTE2:
10635   case AMDGPUISD::CVT_F32_UBYTE3:
10636     return performCvtF32UByteNCombine(N, DCI);
10637   case AMDGPUISD::FMED3:
10638     return performFMed3Combine(N, DCI);
10639   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10640     return performCvtPkRTZCombine(N, DCI);
10641   case AMDGPUISD::CLAMP:
10642     return performClampCombine(N, DCI);
10643   case ISD::SCALAR_TO_VECTOR: {
10644     SelectionDAG &DAG = DCI.DAG;
10645     EVT VT = N->getValueType(0);
10646 
10647     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10648     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10649       SDLoc SL(N);
10650       SDValue Src = N->getOperand(0);
10651       EVT EltVT = Src.getValueType();
10652       if (EltVT == MVT::f16)
10653         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10654 
10655       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10656       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10657     }
10658 
10659     break;
10660   }
10661   case ISD::EXTRACT_VECTOR_ELT:
10662     return performExtractVectorEltCombine(N, DCI);
10663   case ISD::INSERT_VECTOR_ELT:
10664     return performInsertVectorEltCombine(N, DCI);
10665   }
10666   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10667 }
10668 
10669 /// Helper function for adjustWritemask
10670 static unsigned SubIdx2Lane(unsigned Idx) {
10671   switch (Idx) {
10672   default: return 0;
10673   case AMDGPU::sub0: return 0;
10674   case AMDGPU::sub1: return 1;
10675   case AMDGPU::sub2: return 2;
10676   case AMDGPU::sub3: return 3;
10677   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10678   }
10679 }
10680 
10681 /// Adjust the writemask of MIMG instructions
10682 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10683                                           SelectionDAG &DAG) const {
10684   unsigned Opcode = Node->getMachineOpcode();
10685 
10686   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10687   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10688   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10689     return Node; // not implemented for D16
10690 
10691   SDNode *Users[5] = { nullptr };
10692   unsigned Lane = 0;
10693   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10694   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10695   unsigned NewDmask = 0;
10696   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10697   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10698   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10699                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10700   unsigned TFCLane = 0;
10701   bool HasChain = Node->getNumValues() > 1;
10702 
10703   if (OldDmask == 0) {
10704     // These are folded out, but on the chance it happens don't assert.
10705     return Node;
10706   }
10707 
10708   unsigned OldBitsSet = countPopulation(OldDmask);
10709   // Work out which is the TFE/LWE lane if that is enabled.
10710   if (UsesTFC) {
10711     TFCLane = OldBitsSet;
10712   }
10713 
10714   // Try to figure out the used register components
10715   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10716        I != E; ++I) {
10717 
10718     // Don't look at users of the chain.
10719     if (I.getUse().getResNo() != 0)
10720       continue;
10721 
10722     // Abort if we can't understand the usage
10723     if (!I->isMachineOpcode() ||
10724         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10725       return Node;
10726 
10727     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10728     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10729     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10730     // set, etc.
10731     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10732 
10733     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10734     if (UsesTFC && Lane == TFCLane) {
10735       Users[Lane] = *I;
10736     } else {
10737       // Set which texture component corresponds to the lane.
10738       unsigned Comp;
10739       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10740         Comp = countTrailingZeros(Dmask);
10741         Dmask &= ~(1 << Comp);
10742       }
10743 
10744       // Abort if we have more than one user per component.
10745       if (Users[Lane])
10746         return Node;
10747 
10748       Users[Lane] = *I;
10749       NewDmask |= 1 << Comp;
10750     }
10751   }
10752 
10753   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10754   bool NoChannels = !NewDmask;
10755   if (NoChannels) {
10756     if (!UsesTFC) {
10757       // No uses of the result and not using TFC. Then do nothing.
10758       return Node;
10759     }
10760     // If the original dmask has one channel - then nothing to do
10761     if (OldBitsSet == 1)
10762       return Node;
10763     // Use an arbitrary dmask - required for the instruction to work
10764     NewDmask = 1;
10765   }
10766   // Abort if there's no change
10767   if (NewDmask == OldDmask)
10768     return Node;
10769 
10770   unsigned BitsSet = countPopulation(NewDmask);
10771 
10772   // Check for TFE or LWE - increase the number of channels by one to account
10773   // for the extra return value
10774   // This will need adjustment for D16 if this is also included in
10775   // adjustWriteMask (this function) but at present D16 are excluded.
10776   unsigned NewChannels = BitsSet + UsesTFC;
10777 
10778   int NewOpcode =
10779       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10780   assert(NewOpcode != -1 &&
10781          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10782          "failed to find equivalent MIMG op");
10783 
10784   // Adjust the writemask in the node
10785   SmallVector<SDValue, 12> Ops;
10786   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10787   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10788   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10789 
10790   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10791 
10792   MVT ResultVT = NewChannels == 1 ?
10793     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10794                            NewChannels == 5 ? 8 : NewChannels);
10795   SDVTList NewVTList = HasChain ?
10796     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10797 
10798 
10799   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10800                                               NewVTList, Ops);
10801 
10802   if (HasChain) {
10803     // Update chain.
10804     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10805     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10806   }
10807 
10808   if (NewChannels == 1) {
10809     assert(Node->hasNUsesOfValue(1, 0));
10810     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10811                                       SDLoc(Node), Users[Lane]->getValueType(0),
10812                                       SDValue(NewNode, 0));
10813     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10814     return nullptr;
10815   }
10816 
10817   // Update the users of the node with the new indices
10818   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10819     SDNode *User = Users[i];
10820     if (!User) {
10821       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10822       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10823       if (i || !NoChannels)
10824         continue;
10825     } else {
10826       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10827       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10828     }
10829 
10830     switch (Idx) {
10831     default: break;
10832     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10833     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10834     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10835     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10836     }
10837   }
10838 
10839   DAG.RemoveDeadNode(Node);
10840   return nullptr;
10841 }
10842 
10843 static bool isFrameIndexOp(SDValue Op) {
10844   if (Op.getOpcode() == ISD::AssertZext)
10845     Op = Op.getOperand(0);
10846 
10847   return isa<FrameIndexSDNode>(Op);
10848 }
10849 
10850 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10851 /// with frame index operands.
10852 /// LLVM assumes that inputs are to these instructions are registers.
10853 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10854                                                         SelectionDAG &DAG) const {
10855   if (Node->getOpcode() == ISD::CopyToReg) {
10856     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10857     SDValue SrcVal = Node->getOperand(2);
10858 
10859     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10860     // to try understanding copies to physical registers.
10861     if (SrcVal.getValueType() == MVT::i1 &&
10862         Register::isPhysicalRegister(DestReg->getReg())) {
10863       SDLoc SL(Node);
10864       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10865       SDValue VReg = DAG.getRegister(
10866         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10867 
10868       SDNode *Glued = Node->getGluedNode();
10869       SDValue ToVReg
10870         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10871                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10872       SDValue ToResultReg
10873         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10874                            VReg, ToVReg.getValue(1));
10875       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10876       DAG.RemoveDeadNode(Node);
10877       return ToResultReg.getNode();
10878     }
10879   }
10880 
10881   SmallVector<SDValue, 8> Ops;
10882   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10883     if (!isFrameIndexOp(Node->getOperand(i))) {
10884       Ops.push_back(Node->getOperand(i));
10885       continue;
10886     }
10887 
10888     SDLoc DL(Node);
10889     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10890                                      Node->getOperand(i).getValueType(),
10891                                      Node->getOperand(i)), 0));
10892   }
10893 
10894   return DAG.UpdateNodeOperands(Node, Ops);
10895 }
10896 
10897 /// Fold the instructions after selecting them.
10898 /// Returns null if users were already updated.
10899 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10900                                           SelectionDAG &DAG) const {
10901   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10902   unsigned Opcode = Node->getMachineOpcode();
10903 
10904   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10905       !TII->isGather4(Opcode)) {
10906     return adjustWritemask(Node, DAG);
10907   }
10908 
10909   if (Opcode == AMDGPU::INSERT_SUBREG ||
10910       Opcode == AMDGPU::REG_SEQUENCE) {
10911     legalizeTargetIndependentNode(Node, DAG);
10912     return Node;
10913   }
10914 
10915   switch (Opcode) {
10916   case AMDGPU::V_DIV_SCALE_F32:
10917   case AMDGPU::V_DIV_SCALE_F64: {
10918     // Satisfy the operand register constraint when one of the inputs is
10919     // undefined. Ordinarily each undef value will have its own implicit_def of
10920     // a vreg, so force these to use a single register.
10921     SDValue Src0 = Node->getOperand(0);
10922     SDValue Src1 = Node->getOperand(1);
10923     SDValue Src2 = Node->getOperand(2);
10924 
10925     if ((Src0.isMachineOpcode() &&
10926          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10927         (Src0 == Src1 || Src0 == Src2))
10928       break;
10929 
10930     MVT VT = Src0.getValueType().getSimpleVT();
10931     const TargetRegisterClass *RC =
10932         getRegClassFor(VT, Src0.getNode()->isDivergent());
10933 
10934     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10935     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10936 
10937     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10938                                       UndefReg, Src0, SDValue());
10939 
10940     // src0 must be the same register as src1 or src2, even if the value is
10941     // undefined, so make sure we don't violate this constraint.
10942     if (Src0.isMachineOpcode() &&
10943         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10944       if (Src1.isMachineOpcode() &&
10945           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10946         Src0 = Src1;
10947       else if (Src2.isMachineOpcode() &&
10948                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10949         Src0 = Src2;
10950       else {
10951         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10952         Src0 = UndefReg;
10953         Src1 = UndefReg;
10954       }
10955     } else
10956       break;
10957 
10958     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10959     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10960       Ops.push_back(Node->getOperand(I));
10961 
10962     Ops.push_back(ImpDef.getValue(1));
10963     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10964   }
10965   default:
10966     break;
10967   }
10968 
10969   return Node;
10970 }
10971 
10972 /// Assign the register class depending on the number of
10973 /// bits set in the writemask
10974 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10975                                                      SDNode *Node) const {
10976   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10977 
10978   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10979 
10980   if (TII->isVOP3(MI.getOpcode())) {
10981     // Make sure constant bus requirements are respected.
10982     TII->legalizeOperandsVOP3(MRI, MI);
10983 
10984     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10985     // This saves a chain-copy of registers and better ballance register
10986     // use between vgpr and agpr as agpr tuples tend to be big.
10987     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10988       unsigned Opc = MI.getOpcode();
10989       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10990       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10991                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10992         if (I == -1)
10993           break;
10994         MachineOperand &Op = MI.getOperand(I);
10995         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10996              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10997             !Register::isVirtualRegister(Op.getReg()) ||
10998             !TRI->isAGPR(MRI, Op.getReg()))
10999           continue;
11000         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11001         if (!Src || !Src->isCopy() ||
11002             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11003           continue;
11004         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11005         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11006         // All uses of agpr64 and agpr32 can also accept vgpr except for
11007         // v_accvgpr_read, but we do not produce agpr reads during selection,
11008         // so no use checks are needed.
11009         MRI.setRegClass(Op.getReg(), NewRC);
11010       }
11011     }
11012 
11013     return;
11014   }
11015 
11016   // Replace unused atomics with the no return version.
11017   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11018   if (NoRetAtomicOp != -1) {
11019     if (!Node->hasAnyUseOfValue(0)) {
11020       MI.setDesc(TII->get(NoRetAtomicOp));
11021       MI.RemoveOperand(0);
11022       return;
11023     }
11024 
11025     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11026     // instruction, because the return type of these instructions is a vec2 of
11027     // the memory type, so it can be tied to the input operand.
11028     // This means these instructions always have a use, so we need to add a
11029     // special case to check if the atomic has only one extract_subreg use,
11030     // which itself has no uses.
11031     if ((Node->hasNUsesOfValue(1, 0) &&
11032          Node->use_begin()->isMachineOpcode() &&
11033          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11034          !Node->use_begin()->hasAnyUseOfValue(0))) {
11035       Register Def = MI.getOperand(0).getReg();
11036 
11037       // Change this into a noret atomic.
11038       MI.setDesc(TII->get(NoRetAtomicOp));
11039       MI.RemoveOperand(0);
11040 
11041       // If we only remove the def operand from the atomic instruction, the
11042       // extract_subreg will be left with a use of a vreg without a def.
11043       // So we need to insert an implicit_def to avoid machine verifier
11044       // errors.
11045       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11046               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11047     }
11048     return;
11049   }
11050 }
11051 
11052 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11053                               uint64_t Val) {
11054   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11055   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11056 }
11057 
11058 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11059                                                 const SDLoc &DL,
11060                                                 SDValue Ptr) const {
11061   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11062 
11063   // Build the half of the subregister with the constants before building the
11064   // full 128-bit register. If we are building multiple resource descriptors,
11065   // this will allow CSEing of the 2-component register.
11066   const SDValue Ops0[] = {
11067     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11068     buildSMovImm32(DAG, DL, 0),
11069     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11070     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11071     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11072   };
11073 
11074   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11075                                                 MVT::v2i32, Ops0), 0);
11076 
11077   // Combine the constants and the pointer.
11078   const SDValue Ops1[] = {
11079     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11080     Ptr,
11081     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11082     SubRegHi,
11083     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11084   };
11085 
11086   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11087 }
11088 
11089 /// Return a resource descriptor with the 'Add TID' bit enabled
11090 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11091 ///        of the resource descriptor) to create an offset, which is added to
11092 ///        the resource pointer.
11093 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11094                                            SDValue Ptr, uint32_t RsrcDword1,
11095                                            uint64_t RsrcDword2And3) const {
11096   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11097   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11098   if (RsrcDword1) {
11099     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11100                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11101                     0);
11102   }
11103 
11104   SDValue DataLo = buildSMovImm32(DAG, DL,
11105                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11106   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11107 
11108   const SDValue Ops[] = {
11109     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11110     PtrLo,
11111     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11112     PtrHi,
11113     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11114     DataLo,
11115     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11116     DataHi,
11117     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11118   };
11119 
11120   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11121 }
11122 
11123 //===----------------------------------------------------------------------===//
11124 //                         SI Inline Assembly Support
11125 //===----------------------------------------------------------------------===//
11126 
11127 std::pair<unsigned, const TargetRegisterClass *>
11128 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11129                                                StringRef Constraint,
11130                                                MVT VT) const {
11131   const TargetRegisterClass *RC = nullptr;
11132   if (Constraint.size() == 1) {
11133     const unsigned BitWidth = VT.getSizeInBits();
11134     switch (Constraint[0]) {
11135     default:
11136       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11137     case 's':
11138     case 'r':
11139       switch (BitWidth) {
11140       case 16:
11141         RC = &AMDGPU::SReg_32RegClass;
11142         break;
11143       case 64:
11144         RC = &AMDGPU::SGPR_64RegClass;
11145         break;
11146       default:
11147         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11148         if (!RC)
11149           return std::make_pair(0U, nullptr);
11150         break;
11151       }
11152       break;
11153     case 'v':
11154       switch (BitWidth) {
11155       case 16:
11156         RC = &AMDGPU::VGPR_32RegClass;
11157         break;
11158       default:
11159         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11160         if (!RC)
11161           return std::make_pair(0U, nullptr);
11162         break;
11163       }
11164       break;
11165     case 'a':
11166       if (!Subtarget->hasMAIInsts())
11167         break;
11168       switch (BitWidth) {
11169       case 16:
11170         RC = &AMDGPU::AGPR_32RegClass;
11171         break;
11172       default:
11173         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11174         if (!RC)
11175           return std::make_pair(0U, nullptr);
11176         break;
11177       }
11178       break;
11179     }
11180     // We actually support i128, i16 and f16 as inline parameters
11181     // even if they are not reported as legal
11182     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11183                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11184       return std::make_pair(0U, RC);
11185   }
11186 
11187   if (Constraint.size() > 1) {
11188     if (Constraint[1] == 'v') {
11189       RC = &AMDGPU::VGPR_32RegClass;
11190     } else if (Constraint[1] == 's') {
11191       RC = &AMDGPU::SGPR_32RegClass;
11192     } else if (Constraint[1] == 'a') {
11193       RC = &AMDGPU::AGPR_32RegClass;
11194     }
11195 
11196     if (RC) {
11197       uint32_t Idx;
11198       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11199       if (!Failed && Idx < RC->getNumRegs())
11200         return std::make_pair(RC->getRegister(Idx), RC);
11201     }
11202   }
11203 
11204   // FIXME: Returns VS_32 for physical SGPR constraints
11205   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11206 }
11207 
11208 static bool isImmConstraint(StringRef Constraint) {
11209   if (Constraint.size() == 1) {
11210     switch (Constraint[0]) {
11211     default: break;
11212     case 'I':
11213     case 'J':
11214     case 'A':
11215     case 'B':
11216     case 'C':
11217       return true;
11218     }
11219   } else if (Constraint == "DA" ||
11220              Constraint == "DB") {
11221     return true;
11222   }
11223   return false;
11224 }
11225 
11226 SITargetLowering::ConstraintType
11227 SITargetLowering::getConstraintType(StringRef Constraint) const {
11228   if (Constraint.size() == 1) {
11229     switch (Constraint[0]) {
11230     default: break;
11231     case 's':
11232     case 'v':
11233     case 'a':
11234       return C_RegisterClass;
11235     }
11236   }
11237   if (isImmConstraint(Constraint)) {
11238     return C_Other;
11239   }
11240   return TargetLowering::getConstraintType(Constraint);
11241 }
11242 
11243 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11244   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11245     Val = Val & maskTrailingOnes<uint64_t>(Size);
11246   }
11247   return Val;
11248 }
11249 
11250 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11251                                                     std::string &Constraint,
11252                                                     std::vector<SDValue> &Ops,
11253                                                     SelectionDAG &DAG) const {
11254   if (isImmConstraint(Constraint)) {
11255     uint64_t Val;
11256     if (getAsmOperandConstVal(Op, Val) &&
11257         checkAsmConstraintVal(Op, Constraint, Val)) {
11258       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11259       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11260     }
11261   } else {
11262     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11263   }
11264 }
11265 
11266 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11267   unsigned Size = Op.getScalarValueSizeInBits();
11268   if (Size > 64)
11269     return false;
11270 
11271   if (Size == 16 && !Subtarget->has16BitInsts())
11272     return false;
11273 
11274   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11275     Val = C->getSExtValue();
11276     return true;
11277   }
11278   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11279     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11280     return true;
11281   }
11282   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11283     if (Size != 16 || Op.getNumOperands() != 2)
11284       return false;
11285     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11286       return false;
11287     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11288       Val = C->getSExtValue();
11289       return true;
11290     }
11291     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11292       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11293       return true;
11294     }
11295   }
11296 
11297   return false;
11298 }
11299 
11300 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11301                                              const std::string &Constraint,
11302                                              uint64_t Val) const {
11303   if (Constraint.size() == 1) {
11304     switch (Constraint[0]) {
11305     case 'I':
11306       return AMDGPU::isInlinableIntLiteral(Val);
11307     case 'J':
11308       return isInt<16>(Val);
11309     case 'A':
11310       return checkAsmConstraintValA(Op, Val);
11311     case 'B':
11312       return isInt<32>(Val);
11313     case 'C':
11314       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11315              AMDGPU::isInlinableIntLiteral(Val);
11316     default:
11317       break;
11318     }
11319   } else if (Constraint.size() == 2) {
11320     if (Constraint == "DA") {
11321       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11322       int64_t LoBits = static_cast<int32_t>(Val);
11323       return checkAsmConstraintValA(Op, HiBits, 32) &&
11324              checkAsmConstraintValA(Op, LoBits, 32);
11325     }
11326     if (Constraint == "DB") {
11327       return true;
11328     }
11329   }
11330   llvm_unreachable("Invalid asm constraint");
11331 }
11332 
11333 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11334                                               uint64_t Val,
11335                                               unsigned MaxSize) const {
11336   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11337   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11338   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11339       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11340       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11341     return true;
11342   }
11343   return false;
11344 }
11345 
11346 // Figure out which registers should be reserved for stack access. Only after
11347 // the function is legalized do we know all of the non-spill stack objects or if
11348 // calls are present.
11349 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11350   MachineRegisterInfo &MRI = MF.getRegInfo();
11351   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11352   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11353   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11354 
11355   if (Info->isEntryFunction()) {
11356     // Callable functions have fixed registers used for stack access.
11357     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11358   }
11359 
11360   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11361                              Info->getStackPtrOffsetReg()));
11362   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11363     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11364 
11365   // We need to worry about replacing the default register with itself in case
11366   // of MIR testcases missing the MFI.
11367   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11368     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11369 
11370   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11371     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11372 
11373   Info->limitOccupancy(MF);
11374 
11375   if (ST.isWave32() && !MF.empty()) {
11376     // Add VCC_HI def because many instructions marked as imp-use VCC where
11377     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11378     // having a use of undef.
11379 
11380     const SIInstrInfo *TII = ST.getInstrInfo();
11381     DebugLoc DL;
11382 
11383     MachineBasicBlock &MBB = MF.front();
11384     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11385     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11386 
11387     for (auto &MBB : MF) {
11388       for (auto &MI : MBB) {
11389         TII->fixImplicitOperands(MI);
11390       }
11391     }
11392   }
11393 
11394   TargetLoweringBase::finalizeLowering(MF);
11395 
11396   // Allocate a VGPR for future SGPR Spill if
11397   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11398   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11399   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11400       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11401     Info->reserveVGPRforSGPRSpills(MF);
11402 }
11403 
11404 void SITargetLowering::computeKnownBitsForFrameIndex(
11405   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11406   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11407 
11408   // Set the high bits to zero based on the maximum allowed scratch size per
11409   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11410   // calculation won't overflow, so assume the sign bit is never set.
11411   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11412 }
11413 
11414 Align SITargetLowering::computeKnownAlignForTargetInstr(
11415   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11416   unsigned Depth) const {
11417   const MachineInstr *MI = MRI.getVRegDef(R);
11418   switch (MI->getOpcode()) {
11419   case AMDGPU::G_INTRINSIC:
11420   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11421     // FIXME: Can this move to generic code? What about the case where the call
11422     // site specifies a lower alignment?
11423     Intrinsic::ID IID = MI->getIntrinsicID();
11424     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11425     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11426     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11427       return *RetAlign;
11428     return Align(1);
11429   }
11430   default:
11431     return Align(1);
11432   }
11433 }
11434 
11435 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11436   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11437   const Align CacheLineAlign = Align(64);
11438 
11439   // Pre-GFX10 target did not benefit from loop alignment
11440   if (!ML || DisableLoopAlignment ||
11441       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11442       getSubtarget()->hasInstFwdPrefetchBug())
11443     return PrefAlign;
11444 
11445   // On GFX10 I$ is 4 x 64 bytes cache lines.
11446   // By default prefetcher keeps one cache line behind and reads two ahead.
11447   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11448   // behind and one ahead.
11449   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11450   // If loop fits 64 bytes it always spans no more than two cache lines and
11451   // does not need an alignment.
11452   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11453   // Else if loop is less or equal 192 bytes we need two lines behind.
11454 
11455   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11456   const MachineBasicBlock *Header = ML->getHeader();
11457   if (Header->getAlignment() != PrefAlign)
11458     return Header->getAlignment(); // Already processed.
11459 
11460   unsigned LoopSize = 0;
11461   for (const MachineBasicBlock *MBB : ML->blocks()) {
11462     // If inner loop block is aligned assume in average half of the alignment
11463     // size to be added as nops.
11464     if (MBB != Header)
11465       LoopSize += MBB->getAlignment().value() / 2;
11466 
11467     for (const MachineInstr &MI : *MBB) {
11468       LoopSize += TII->getInstSizeInBytes(MI);
11469       if (LoopSize > 192)
11470         return PrefAlign;
11471     }
11472   }
11473 
11474   if (LoopSize <= 64)
11475     return PrefAlign;
11476 
11477   if (LoopSize <= 128)
11478     return CacheLineAlign;
11479 
11480   // If any of parent loops is surrounded by prefetch instructions do not
11481   // insert new for inner loop, which would reset parent's settings.
11482   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11483     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11484       auto I = Exit->getFirstNonDebugInstr();
11485       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11486         return CacheLineAlign;
11487     }
11488   }
11489 
11490   MachineBasicBlock *Pre = ML->getLoopPreheader();
11491   MachineBasicBlock *Exit = ML->getExitBlock();
11492 
11493   if (Pre && Exit) {
11494     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11495             TII->get(AMDGPU::S_INST_PREFETCH))
11496       .addImm(1); // prefetch 2 lines behind PC
11497 
11498     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11499             TII->get(AMDGPU::S_INST_PREFETCH))
11500       .addImm(2); // prefetch 1 line behind PC
11501   }
11502 
11503   return CacheLineAlign;
11504 }
11505 
11506 LLVM_ATTRIBUTE_UNUSED
11507 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11508   assert(N->getOpcode() == ISD::CopyFromReg);
11509   do {
11510     // Follow the chain until we find an INLINEASM node.
11511     N = N->getOperand(0).getNode();
11512     if (N->getOpcode() == ISD::INLINEASM ||
11513         N->getOpcode() == ISD::INLINEASM_BR)
11514       return true;
11515   } while (N->getOpcode() == ISD::CopyFromReg);
11516   return false;
11517 }
11518 
11519 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11520   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11521 {
11522   switch (N->getOpcode()) {
11523     case ISD::CopyFromReg:
11524     {
11525       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11526       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11527       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11528       Register Reg = R->getReg();
11529 
11530       // FIXME: Why does this need to consider isLiveIn?
11531       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11532         return !TRI->isSGPRReg(MRI, Reg);
11533 
11534       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11535         return KDA->isDivergent(V);
11536 
11537       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11538       return !TRI->isSGPRReg(MRI, Reg);
11539     }
11540     break;
11541     case ISD::LOAD: {
11542       const LoadSDNode *L = cast<LoadSDNode>(N);
11543       unsigned AS = L->getAddressSpace();
11544       // A flat load may access private memory.
11545       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11546     } break;
11547     case ISD::CALLSEQ_END:
11548     return true;
11549     break;
11550     case ISD::INTRINSIC_WO_CHAIN:
11551     {
11552 
11553     }
11554       return AMDGPU::isIntrinsicSourceOfDivergence(
11555       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11556     case ISD::INTRINSIC_W_CHAIN:
11557       return AMDGPU::isIntrinsicSourceOfDivergence(
11558       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11559   }
11560   return false;
11561 }
11562 
11563 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11564                                                EVT VT) const {
11565   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11566   case MVT::f32:
11567     return hasFP32Denormals(DAG.getMachineFunction());
11568   case MVT::f64:
11569   case MVT::f16:
11570     return hasFP64FP16Denormals(DAG.getMachineFunction());
11571   default:
11572     return false;
11573   }
11574 }
11575 
11576 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11577                                                     const SelectionDAG &DAG,
11578                                                     bool SNaN,
11579                                                     unsigned Depth) const {
11580   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11581     const MachineFunction &MF = DAG.getMachineFunction();
11582     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11583 
11584     if (Info->getMode().DX10Clamp)
11585       return true; // Clamped to 0.
11586     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11587   }
11588 
11589   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11590                                                             SNaN, Depth);
11591 }
11592 
11593 TargetLowering::AtomicExpansionKind
11594 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11595   switch (RMW->getOperation()) {
11596   case AtomicRMWInst::FAdd: {
11597     Type *Ty = RMW->getType();
11598 
11599     // We don't have a way to support 16-bit atomics now, so just leave them
11600     // as-is.
11601     if (Ty->isHalfTy())
11602       return AtomicExpansionKind::None;
11603 
11604     if (!Ty->isFloatTy())
11605       return AtomicExpansionKind::CmpXChg;
11606 
11607     // TODO: Do have these for flat. Older targets also had them for buffers.
11608     unsigned AS = RMW->getPointerAddressSpace();
11609 
11610     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11611       return RMW->use_empty() ? AtomicExpansionKind::None :
11612                                 AtomicExpansionKind::CmpXChg;
11613     }
11614 
11615     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11616       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11617   }
11618   default:
11619     break;
11620   }
11621 
11622   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11623 }
11624 
11625 const TargetRegisterClass *
11626 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11627   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11628   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11629   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11630     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11631                                                : &AMDGPU::SReg_32RegClass;
11632   if (!TRI->isSGPRClass(RC) && !isDivergent)
11633     return TRI->getEquivalentSGPRClass(RC);
11634   else if (TRI->isSGPRClass(RC) && isDivergent)
11635     return TRI->getEquivalentVGPRClass(RC);
11636 
11637   return RC;
11638 }
11639 
11640 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11641 // uniform values (as produced by the mask results of control flow intrinsics)
11642 // used outside of divergent blocks. The phi users need to also be treated as
11643 // always uniform.
11644 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11645                       unsigned WaveSize) {
11646   // FIXME: We asssume we never cast the mask results of a control flow
11647   // intrinsic.
11648   // Early exit if the type won't be consistent as a compile time hack.
11649   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11650   if (!IT || IT->getBitWidth() != WaveSize)
11651     return false;
11652 
11653   if (!isa<Instruction>(V))
11654     return false;
11655   if (!Visited.insert(V).second)
11656     return false;
11657   bool Result = false;
11658   for (auto U : V->users()) {
11659     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11660       if (V == U->getOperand(1)) {
11661         switch (Intrinsic->getIntrinsicID()) {
11662         default:
11663           Result = false;
11664           break;
11665         case Intrinsic::amdgcn_if_break:
11666         case Intrinsic::amdgcn_if:
11667         case Intrinsic::amdgcn_else:
11668           Result = true;
11669           break;
11670         }
11671       }
11672       if (V == U->getOperand(0)) {
11673         switch (Intrinsic->getIntrinsicID()) {
11674         default:
11675           Result = false;
11676           break;
11677         case Intrinsic::amdgcn_end_cf:
11678         case Intrinsic::amdgcn_loop:
11679           Result = true;
11680           break;
11681         }
11682       }
11683     } else {
11684       Result = hasCFUser(U, Visited, WaveSize);
11685     }
11686     if (Result)
11687       break;
11688   }
11689   return Result;
11690 }
11691 
11692 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11693                                                const Value *V) const {
11694   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11695     if (CI->isInlineAsm()) {
11696       // FIXME: This cannot give a correct answer. This should only trigger in
11697       // the case where inline asm returns mixed SGPR and VGPR results, used
11698       // outside the defining block. We don't have a specific result to
11699       // consider, so this assumes if any value is SGPR, the overall register
11700       // also needs to be SGPR.
11701       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11702       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11703           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11704       for (auto &TC : TargetConstraints) {
11705         if (TC.Type == InlineAsm::isOutput) {
11706           ComputeConstraintToUse(TC, SDValue());
11707           unsigned AssignedReg;
11708           const TargetRegisterClass *RC;
11709           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11710               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11711           if (RC) {
11712             MachineRegisterInfo &MRI = MF.getRegInfo();
11713             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11714               return true;
11715             else if (SIRI->isSGPRClass(RC))
11716               return true;
11717           }
11718         }
11719       }
11720     }
11721   }
11722   SmallPtrSet<const Value *, 16> Visited;
11723   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11724 }
11725 
11726 std::pair<int, MVT>
11727 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11728                                           Type *Ty) const {
11729   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11730   auto Size = DL.getTypeSizeInBits(Ty);
11731   // Maximum load or store can handle 8 dwords for scalar and 4 for
11732   // vector ALU. Let's assume anything above 8 dwords is expensive
11733   // even if legal.
11734   if (Size <= 256)
11735     return Cost;
11736 
11737   Cost.first = (Size + 255) / 256;
11738   return Cost;
11739 }
11740