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 #if defined(_MSC_VER) || defined(__MINGW32__)
15 // Provide M_PI.
16 #define _USE_MATH_DEFINES
17 #endif
18 
19 #include "SIISelLowering.h"
20 #include "AMDGPU.h"
21 #include "AMDGPUSubtarget.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
24 #include "SIDefines.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "Utils/AMDGPUBaseInfo.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/CallingConvLower.h"
41 #include "llvm/CodeGen/DAGCombine.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineLoopInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
93 static cl::opt<bool> DisableLoopAlignment(
94   "amdgpu-disable-loop-alignment",
95   cl::desc("Do not align and prefetch loops"),
96   cl::init(false));
97 
98 static cl::opt<bool> VGPRReserveforSGPRSpill(
99     "amdgpu-reserve-vgpr-for-sgpr-spill",
100     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
101 
102 static cl::opt<bool> UseDivergentRegisterIndexing(
103   "amdgpu-use-divergent-register-indexing",
104   cl::Hidden,
105   cl::desc("Use indirect register addressing for divergent indexes"),
106   cl::init(false));
107 
108 static bool hasFP32Denormals(const MachineFunction &MF) {
109   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
110   return Info->getMode().allFP32Denormals();
111 }
112 
113 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
114   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
115   return Info->getMode().allFP64FP16Denormals();
116 }
117 
118 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
119   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
120   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
121     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
122       return AMDGPU::SGPR0 + Reg;
123     }
124   }
125   llvm_unreachable("Cannot allocate sgpr");
126 }
127 
128 SITargetLowering::SITargetLowering(const TargetMachine &TM,
129                                    const GCNSubtarget &STI)
130     : AMDGPUTargetLowering(TM, STI),
131       Subtarget(&STI) {
132   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
133   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
134 
135   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
136   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
137 
138   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
139   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
140   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
141 
142   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
143   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
144 
145   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
146   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
147 
148   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
149   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
150 
151   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
152   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
153 
154   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
155   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
156 
157   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
158   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
159 
160   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
161   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
162 
163   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
164   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
165 
166   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
167   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
168 
169   if (Subtarget->has16BitInsts()) {
170     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
171     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
172 
173     // Unless there are also VOP3P operations, not operations are really legal.
174     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
175     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
176     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
177     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
178   }
179 
180   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
181   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
182 
183   computeRegisterProperties(Subtarget->getRegisterInfo());
184 
185   // The boolean content concept here is too inflexible. Compares only ever
186   // really produce a 1-bit result. Any copy/extend from these will turn into a
187   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
188   // it's what most targets use.
189   setBooleanContents(ZeroOrOneBooleanContent);
190   setBooleanVectorContents(ZeroOrOneBooleanContent);
191 
192   // We need to custom lower vector stores from local memory
193   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
196   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
197   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
198   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
199   setOperationAction(ISD::LOAD, MVT::i1, Custom);
200   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
201 
202   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
204   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
205   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
206   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
207   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
208   setOperationAction(ISD::STORE, MVT::i1, Custom);
209   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
210 
211   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
212   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
213   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
214   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
215   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
216   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
217   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
218   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
219   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
220   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
221   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
222   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
223   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
224   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
225   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
226   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
227 
228   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
229   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
230 
231   setOperationAction(ISD::SELECT, MVT::i1, Promote);
232   setOperationAction(ISD::SELECT, MVT::i64, Custom);
233   setOperationAction(ISD::SELECT, MVT::f64, Promote);
234   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
235 
236   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
237   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
238   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
239   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
241 
242   setOperationAction(ISD::SETCC, MVT::i1, Promote);
243   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
244   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
245   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
246 
247   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
248   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
249   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
250   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
251   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
252   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
253   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
254   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
255 
256   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
257   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
258   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
264 
265   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
266   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
267   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
268   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
269   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
270   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
271 
272   setOperationAction(ISD::UADDO, MVT::i32, Legal);
273   setOperationAction(ISD::USUBO, MVT::i32, Legal);
274 
275   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
276   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
277 
278   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
279   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
280   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
281 
282 #if 0
283   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
284   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
285 #endif
286 
287   // We only support LOAD/STORE and vector manipulation ops for vectors
288   // with > 4 elements.
289   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
290                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
291                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
292                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
293     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
294       switch (Op) {
295       case ISD::LOAD:
296       case ISD::STORE:
297       case ISD::BUILD_VECTOR:
298       case ISD::BITCAST:
299       case ISD::EXTRACT_VECTOR_ELT:
300       case ISD::INSERT_VECTOR_ELT:
301       case ISD::INSERT_SUBVECTOR:
302       case ISD::EXTRACT_SUBVECTOR:
303       case ISD::SCALAR_TO_VECTOR:
304         break;
305       case ISD::CONCAT_VECTORS:
306         setOperationAction(Op, VT, Custom);
307         break;
308       default:
309         setOperationAction(Op, VT, Expand);
310         break;
311       }
312     }
313   }
314 
315   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
316 
317   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
318   // is expanded to avoid having two separate loops in case the index is a VGPR.
319 
320   // Most operations are naturally 32-bit vector operations. We only support
321   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
322   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
323     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
324     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
325 
326     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
327     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
328 
329     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
330     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
331 
332     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
333     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
334   }
335 
336   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
337     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
338     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
339 
340     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
341     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
344     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
345 
346     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
347     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
348   }
349 
350   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
351     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
352     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
353 
354     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
355     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
358     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
359 
360     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
361     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
362   }
363 
364   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
365     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
366     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
367 
368     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
369     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
372     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
373 
374     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
375     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
376   }
377 
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
379   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
382 
383   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
384   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
385 
386   // Avoid stack access for these.
387   // TODO: Generalize to more vector types.
388   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
389   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
392 
393   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
394   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
395   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
398 
399   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
402 
403   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
404   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
405   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
406   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
407 
408   // Deal with vec3 vector operations when widened to vec4.
409   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
413 
414   // Deal with vec5 vector operations when widened to vec8.
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
419 
420   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
421   // and output demarshalling
422   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
423   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
424 
425   // We can't return success/failure, only the old value,
426   // let LLVM add the comparison
427   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
428   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
429 
430   if (Subtarget->hasFlatAddressSpace()) {
431     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
432     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
433   }
434 
435   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
436 
437   // FIXME: This should be narrowed to i32, but that only happens if i64 is
438   // illegal.
439   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
440   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
441   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
442 
443   // On SI this is s_memtime and s_memrealtime on VI.
444   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
445   setOperationAction(ISD::TRAP, MVT::Other, Custom);
446   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
447 
448   if (Subtarget->has16BitInsts()) {
449     setOperationAction(ISD::FPOW, MVT::f16, Promote);
450     setOperationAction(ISD::FLOG, MVT::f16, Custom);
451     setOperationAction(ISD::FEXP, MVT::f16, Custom);
452     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
453   }
454 
455   // v_mad_f32 does not support denormals. We report it as unconditionally
456   // legal, and the context where it is formed will disallow it when fp32
457   // denormals are enabled.
458   setOperationAction(ISD::FMAD, MVT::f32, Legal);
459 
460   if (!Subtarget->hasBFI()) {
461     // fcopysign can be done in a single instruction with BFI.
462     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
463     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
464   }
465 
466   if (!Subtarget->hasBCNT(32))
467     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
468 
469   if (!Subtarget->hasBCNT(64))
470     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
471 
472   if (Subtarget->hasFFBH())
473     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
474 
475   if (Subtarget->hasFFBL())
476     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
477 
478   // We only really have 32-bit BFE instructions (and 16-bit on VI).
479   //
480   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
481   // effort to match them now. We want this to be false for i64 cases when the
482   // extraction isn't restricted to the upper or lower half. Ideally we would
483   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
484   // span the midpoint are probably relatively rare, so don't worry about them
485   // for now.
486   if (Subtarget->hasBFE())
487     setHasExtractBitsInsn(true);
488 
489   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
490   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
491   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
492   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
493 
494 
495   // These are really only legal for ieee_mode functions. We should be avoiding
496   // them for functions that don't have ieee_mode enabled, so just say they are
497   // legal.
498   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
499   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
500   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
501   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
502 
503 
504   if (Subtarget->haveRoundOpsF64()) {
505     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
506     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
507     setOperationAction(ISD::FRINT, MVT::f64, Legal);
508   } else {
509     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
510     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
511     setOperationAction(ISD::FRINT, MVT::f64, Custom);
512     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
513   }
514 
515   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
516 
517   setOperationAction(ISD::FSIN, MVT::f32, Custom);
518   setOperationAction(ISD::FCOS, MVT::f32, Custom);
519   setOperationAction(ISD::FDIV, MVT::f32, Custom);
520   setOperationAction(ISD::FDIV, MVT::f64, Custom);
521 
522   if (Subtarget->has16BitInsts()) {
523     setOperationAction(ISD::Constant, MVT::i16, Legal);
524 
525     setOperationAction(ISD::SMIN, MVT::i16, Legal);
526     setOperationAction(ISD::SMAX, MVT::i16, Legal);
527 
528     setOperationAction(ISD::UMIN, MVT::i16, Legal);
529     setOperationAction(ISD::UMAX, MVT::i16, Legal);
530 
531     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
532     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
533 
534     setOperationAction(ISD::ROTR, MVT::i16, Promote);
535     setOperationAction(ISD::ROTL, MVT::i16, Promote);
536 
537     setOperationAction(ISD::SDIV, MVT::i16, Promote);
538     setOperationAction(ISD::UDIV, MVT::i16, Promote);
539     setOperationAction(ISD::SREM, MVT::i16, Promote);
540     setOperationAction(ISD::UREM, MVT::i16, Promote);
541 
542     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
543 
544     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
545     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
546     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
547     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
548     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
549 
550     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
551 
552     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
553 
554     setOperationAction(ISD::LOAD, MVT::i16, Custom);
555 
556     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
557 
558     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
559     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
560     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
561     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
562 
563     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
564     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
565 
566     // F16 - Constant Actions.
567     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
568 
569     // F16 - Load/Store Actions.
570     setOperationAction(ISD::LOAD, MVT::f16, Promote);
571     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
572     setOperationAction(ISD::STORE, MVT::f16, Promote);
573     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
574 
575     // F16 - VOP1 Actions.
576     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
577     setOperationAction(ISD::FCOS, MVT::f16, Custom);
578     setOperationAction(ISD::FSIN, MVT::f16, Custom);
579 
580     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
581     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
582 
583     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
584     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
585     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
586     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
587     setOperationAction(ISD::FROUND, MVT::f16, Custom);
588 
589     // F16 - VOP2 Actions.
590     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
591     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
592 
593     setOperationAction(ISD::FDIV, MVT::f16, Custom);
594 
595     // F16 - VOP3 Actions.
596     setOperationAction(ISD::FMA, MVT::f16, Legal);
597     if (STI.hasMadF16())
598       setOperationAction(ISD::FMAD, MVT::f16, Legal);
599 
600     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
601       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
602         switch (Op) {
603         case ISD::LOAD:
604         case ISD::STORE:
605         case ISD::BUILD_VECTOR:
606         case ISD::BITCAST:
607         case ISD::EXTRACT_VECTOR_ELT:
608         case ISD::INSERT_VECTOR_ELT:
609         case ISD::INSERT_SUBVECTOR:
610         case ISD::EXTRACT_SUBVECTOR:
611         case ISD::SCALAR_TO_VECTOR:
612           break;
613         case ISD::CONCAT_VECTORS:
614           setOperationAction(Op, VT, Custom);
615           break;
616         default:
617           setOperationAction(Op, VT, Expand);
618           break;
619         }
620       }
621     }
622 
623     // v_perm_b32 can handle either of these.
624     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
625     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
626     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
627 
628     // XXX - Do these do anything? Vector constants turn into build_vector.
629     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
630     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
631 
632     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
633     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
634 
635     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
636     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
637     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
638     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
639 
640     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
641     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
642     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
643     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
644 
645     setOperationAction(ISD::AND, MVT::v2i16, Promote);
646     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
647     setOperationAction(ISD::OR, MVT::v2i16, Promote);
648     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
649     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
650     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
651 
652     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
653     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
654     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
655     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
656 
657     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
658     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
659     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
660     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
661 
662     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
663     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
664     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
665     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
666 
667     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
668     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
669     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
670 
671     if (!Subtarget->hasVOP3PInsts()) {
672       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
673       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
674     }
675 
676     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
677     // This isn't really legal, but this avoids the legalizer unrolling it (and
678     // allows matching fneg (fabs x) patterns)
679     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
680 
681     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
682     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
683     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
684     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
685 
686     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
687     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
688 
689     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
690     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
691   }
692 
693   if (Subtarget->hasVOP3PInsts()) {
694     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
695     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
696     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
697     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
698     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
699     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
700     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
701     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
702     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
703     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
704 
705     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
706     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
707     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
708 
709     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
710     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
711 
712     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
713 
714     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
715     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
716 
717     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
718     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
719 
720     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
721     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
722     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
723     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
724     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
725     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
726 
727     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
728     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
729     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
730     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
731 
732     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
733     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
734     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
735 
736     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
737     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
738 
739     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
740     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
741     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
742 
743     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
744     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
745     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
746   }
747 
748   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
749   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
750 
751   if (Subtarget->has16BitInsts()) {
752     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
753     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
754     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
755     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
756   } else {
757     // Legalization hack.
758     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
759     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
760 
761     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
762     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
763   }
764 
765   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
766     setOperationAction(ISD::SELECT, VT, Custom);
767   }
768 
769   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
770   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
771   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
772   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
773   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
774   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
775   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
776 
777   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
778   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
779   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
780   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
783   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
784   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
785   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
786 
787   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
788   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
789   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
790   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
794   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
795 
796   setTargetDAGCombine(ISD::ADD);
797   setTargetDAGCombine(ISD::ADDCARRY);
798   setTargetDAGCombine(ISD::SUB);
799   setTargetDAGCombine(ISD::SUBCARRY);
800   setTargetDAGCombine(ISD::FADD);
801   setTargetDAGCombine(ISD::FSUB);
802   setTargetDAGCombine(ISD::FMINNUM);
803   setTargetDAGCombine(ISD::FMAXNUM);
804   setTargetDAGCombine(ISD::FMINNUM_IEEE);
805   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
806   setTargetDAGCombine(ISD::FMA);
807   setTargetDAGCombine(ISD::SMIN);
808   setTargetDAGCombine(ISD::SMAX);
809   setTargetDAGCombine(ISD::UMIN);
810   setTargetDAGCombine(ISD::UMAX);
811   setTargetDAGCombine(ISD::SETCC);
812   setTargetDAGCombine(ISD::AND);
813   setTargetDAGCombine(ISD::OR);
814   setTargetDAGCombine(ISD::XOR);
815   setTargetDAGCombine(ISD::SINT_TO_FP);
816   setTargetDAGCombine(ISD::UINT_TO_FP);
817   setTargetDAGCombine(ISD::FCANONICALIZE);
818   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
819   setTargetDAGCombine(ISD::ZERO_EXTEND);
820   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
821   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
822   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
823 
824   // All memory operations. Some folding on the pointer operand is done to help
825   // matching the constant offsets in the addressing modes.
826   setTargetDAGCombine(ISD::LOAD);
827   setTargetDAGCombine(ISD::STORE);
828   setTargetDAGCombine(ISD::ATOMIC_LOAD);
829   setTargetDAGCombine(ISD::ATOMIC_STORE);
830   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
831   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
832   setTargetDAGCombine(ISD::ATOMIC_SWAP);
833   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
834   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
835   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
836   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
843   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
844 
845   setSchedulingPreference(Sched::RegPressure);
846 }
847 
848 const GCNSubtarget *SITargetLowering::getSubtarget() const {
849   return Subtarget;
850 }
851 
852 //===----------------------------------------------------------------------===//
853 // TargetLowering queries
854 //===----------------------------------------------------------------------===//
855 
856 // v_mad_mix* support a conversion from f16 to f32.
857 //
858 // There is only one special case when denormals are enabled we don't currently,
859 // where this is OK to use.
860 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
861                                        EVT DestVT, EVT SrcVT) const {
862   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
863           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
864     DestVT.getScalarType() == MVT::f32 &&
865     SrcVT.getScalarType() == MVT::f16 &&
866     // TODO: This probably only requires no input flushing?
867     !hasFP32Denormals(DAG.getMachineFunction());
868 }
869 
870 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
871   // SI has some legal vector types, but no legal vector operations. Say no
872   // shuffles are legal in order to prefer scalarizing some vector operations.
873   return false;
874 }
875 
876 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
877                                                     CallingConv::ID CC,
878                                                     EVT VT) const {
879   if (CC == CallingConv::AMDGPU_KERNEL)
880     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
881 
882   if (VT.isVector()) {
883     EVT ScalarVT = VT.getScalarType();
884     unsigned Size = ScalarVT.getSizeInBits();
885     if (Size == 32)
886       return ScalarVT.getSimpleVT();
887 
888     if (Size > 32)
889       return MVT::i32;
890 
891     if (Size == 16 && Subtarget->has16BitInsts())
892       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
893   } else if (VT.getSizeInBits() > 32)
894     return MVT::i32;
895 
896   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
897 }
898 
899 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
900                                                          CallingConv::ID CC,
901                                                          EVT VT) const {
902   if (CC == CallingConv::AMDGPU_KERNEL)
903     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
904 
905   if (VT.isVector()) {
906     unsigned NumElts = VT.getVectorNumElements();
907     EVT ScalarVT = VT.getScalarType();
908     unsigned Size = ScalarVT.getSizeInBits();
909 
910     if (Size == 32)
911       return NumElts;
912 
913     if (Size > 32)
914       return NumElts * ((Size + 31) / 32);
915 
916     if (Size == 16 && Subtarget->has16BitInsts())
917       return (NumElts + 1) / 2;
918   } else if (VT.getSizeInBits() > 32)
919     return (VT.getSizeInBits() + 31) / 32;
920 
921   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
922 }
923 
924 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
925   LLVMContext &Context, CallingConv::ID CC,
926   EVT VT, EVT &IntermediateVT,
927   unsigned &NumIntermediates, MVT &RegisterVT) const {
928   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
929     unsigned NumElts = VT.getVectorNumElements();
930     EVT ScalarVT = VT.getScalarType();
931     unsigned Size = ScalarVT.getSizeInBits();
932     if (Size == 32) {
933       RegisterVT = ScalarVT.getSimpleVT();
934       IntermediateVT = RegisterVT;
935       NumIntermediates = NumElts;
936       return NumIntermediates;
937     }
938 
939     if (Size > 32) {
940       RegisterVT = MVT::i32;
941       IntermediateVT = RegisterVT;
942       NumIntermediates = NumElts * ((Size + 31) / 32);
943       return NumIntermediates;
944     }
945 
946     // FIXME: We should fix the ABI to be the same on targets without 16-bit
947     // support, but unless we can properly handle 3-vectors, it will be still be
948     // inconsistent.
949     if (Size == 16 && Subtarget->has16BitInsts()) {
950       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
951       IntermediateVT = RegisterVT;
952       NumIntermediates = (NumElts + 1) / 2;
953       return NumIntermediates;
954     }
955   }
956 
957   return TargetLowering::getVectorTypeBreakdownForCallingConv(
958     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
959 }
960 
961 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
962   assert(DMaskLanes != 0);
963 
964   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
965     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
966     return EVT::getVectorVT(Ty->getContext(),
967                             EVT::getEVT(VT->getElementType()),
968                             NumElts);
969   }
970 
971   return EVT::getEVT(Ty);
972 }
973 
974 // Peek through TFE struct returns to only use the data size.
975 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
976   auto *ST = dyn_cast<StructType>(Ty);
977   if (!ST)
978     return memVTFromImageData(Ty, DMaskLanes);
979 
980   // Some intrinsics return an aggregate type - special case to work out the
981   // correct memVT.
982   //
983   // Only limited forms of aggregate type currently expected.
984   if (ST->getNumContainedTypes() != 2 ||
985       !ST->getContainedType(1)->isIntegerTy(32))
986     return EVT();
987   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
988 }
989 
990 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
991                                           const CallInst &CI,
992                                           MachineFunction &MF,
993                                           unsigned IntrID) const {
994   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
995           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
996     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
997                                                   (Intrinsic::ID)IntrID);
998     if (Attr.hasFnAttribute(Attribute::ReadNone))
999       return false;
1000 
1001     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1002 
1003     if (RsrcIntr->IsImage) {
1004       Info.ptrVal = MFI->getImagePSV(
1005         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1006         CI.getArgOperand(RsrcIntr->RsrcArg));
1007       Info.align.reset();
1008     } else {
1009       Info.ptrVal = MFI->getBufferPSV(
1010         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1011         CI.getArgOperand(RsrcIntr->RsrcArg));
1012     }
1013 
1014     Info.flags = MachineMemOperand::MODereferenceable;
1015     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1016       unsigned DMaskLanes = 4;
1017 
1018       if (RsrcIntr->IsImage) {
1019         const AMDGPU::ImageDimIntrinsicInfo *Intr
1020           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1021         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1022           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1023 
1024         if (!BaseOpcode->Gather4) {
1025           // If this isn't a gather, we may have excess loaded elements in the
1026           // IR type. Check the dmask for the real number of elements loaded.
1027           unsigned DMask
1028             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1029           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1030         }
1031 
1032         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1033       } else
1034         Info.memVT = EVT::getEVT(CI.getType());
1035 
1036       // FIXME: What does alignment mean for an image?
1037       Info.opc = ISD::INTRINSIC_W_CHAIN;
1038       Info.flags |= MachineMemOperand::MOLoad;
1039     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1040       Info.opc = ISD::INTRINSIC_VOID;
1041 
1042       Type *DataTy = CI.getArgOperand(0)->getType();
1043       if (RsrcIntr->IsImage) {
1044         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1045         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1046         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1047       } else
1048         Info.memVT = EVT::getEVT(DataTy);
1049 
1050       Info.flags |= MachineMemOperand::MOStore;
1051     } else {
1052       // Atomic
1053       Info.opc = ISD::INTRINSIC_W_CHAIN;
1054       Info.memVT = MVT::getVT(CI.getType());
1055       Info.flags = MachineMemOperand::MOLoad |
1056                    MachineMemOperand::MOStore |
1057                    MachineMemOperand::MODereferenceable;
1058 
1059       // XXX - Should this be volatile without known ordering?
1060       Info.flags |= MachineMemOperand::MOVolatile;
1061     }
1062     return true;
1063   }
1064 
1065   switch (IntrID) {
1066   case Intrinsic::amdgcn_atomic_inc:
1067   case Intrinsic::amdgcn_atomic_dec:
1068   case Intrinsic::amdgcn_ds_ordered_add:
1069   case Intrinsic::amdgcn_ds_ordered_swap:
1070   case Intrinsic::amdgcn_ds_fadd:
1071   case Intrinsic::amdgcn_ds_fmin:
1072   case Intrinsic::amdgcn_ds_fmax: {
1073     Info.opc = ISD::INTRINSIC_W_CHAIN;
1074     Info.memVT = MVT::getVT(CI.getType());
1075     Info.ptrVal = CI.getOperand(0);
1076     Info.align.reset();
1077     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1078 
1079     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1080     if (!Vol->isZero())
1081       Info.flags |= MachineMemOperand::MOVolatile;
1082 
1083     return true;
1084   }
1085   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1086     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1087 
1088     Info.opc = ISD::INTRINSIC_VOID;
1089     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1090     Info.ptrVal = MFI->getBufferPSV(
1091       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1092       CI.getArgOperand(1));
1093     Info.align.reset();
1094     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1095 
1096     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1097     if (!Vol || !Vol->isZero())
1098       Info.flags |= MachineMemOperand::MOVolatile;
1099 
1100     return true;
1101   }
1102   case Intrinsic::amdgcn_global_atomic_fadd: {
1103     Info.opc = ISD::INTRINSIC_VOID;
1104     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1105                             ->getPointerElementType());
1106     Info.ptrVal = CI.getOperand(0);
1107     Info.align.reset();
1108     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1109 
1110     return true;
1111   }
1112   case Intrinsic::amdgcn_ds_append:
1113   case Intrinsic::amdgcn_ds_consume: {
1114     Info.opc = ISD::INTRINSIC_W_CHAIN;
1115     Info.memVT = MVT::getVT(CI.getType());
1116     Info.ptrVal = CI.getOperand(0);
1117     Info.align.reset();
1118     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1119 
1120     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1121     if (!Vol->isZero())
1122       Info.flags |= MachineMemOperand::MOVolatile;
1123 
1124     return true;
1125   }
1126   case Intrinsic::amdgcn_ds_gws_init:
1127   case Intrinsic::amdgcn_ds_gws_barrier:
1128   case Intrinsic::amdgcn_ds_gws_sema_v:
1129   case Intrinsic::amdgcn_ds_gws_sema_br:
1130   case Intrinsic::amdgcn_ds_gws_sema_p:
1131   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1132     Info.opc = ISD::INTRINSIC_VOID;
1133 
1134     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1135     Info.ptrVal =
1136         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1137 
1138     // This is an abstract access, but we need to specify a type and size.
1139     Info.memVT = MVT::i32;
1140     Info.size = 4;
1141     Info.align = Align(4);
1142 
1143     Info.flags = MachineMemOperand::MOStore;
1144     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1145       Info.flags = MachineMemOperand::MOLoad;
1146     return true;
1147   }
1148   default:
1149     return false;
1150   }
1151 }
1152 
1153 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1154                                             SmallVectorImpl<Value*> &Ops,
1155                                             Type *&AccessTy) const {
1156   switch (II->getIntrinsicID()) {
1157   case Intrinsic::amdgcn_atomic_inc:
1158   case Intrinsic::amdgcn_atomic_dec:
1159   case Intrinsic::amdgcn_ds_ordered_add:
1160   case Intrinsic::amdgcn_ds_ordered_swap:
1161   case Intrinsic::amdgcn_ds_fadd:
1162   case Intrinsic::amdgcn_ds_fmin:
1163   case Intrinsic::amdgcn_ds_fmax: {
1164     Value *Ptr = II->getArgOperand(0);
1165     AccessTy = II->getType();
1166     Ops.push_back(Ptr);
1167     return true;
1168   }
1169   default:
1170     return false;
1171   }
1172 }
1173 
1174 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1175   if (!Subtarget->hasFlatInstOffsets()) {
1176     // Flat instructions do not have offsets, and only have the register
1177     // address.
1178     return AM.BaseOffs == 0 && AM.Scale == 0;
1179   }
1180 
1181   return AM.Scale == 0 &&
1182          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1183                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1184                                   /*Signed=*/false));
1185 }
1186 
1187 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1188   if (Subtarget->hasFlatGlobalInsts())
1189     return AM.Scale == 0 &&
1190            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1191                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1192                                     /*Signed=*/true));
1193 
1194   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1195       // Assume the we will use FLAT for all global memory accesses
1196       // on VI.
1197       // FIXME: This assumption is currently wrong.  On VI we still use
1198       // MUBUF instructions for the r + i addressing mode.  As currently
1199       // implemented, the MUBUF instructions only work on buffer < 4GB.
1200       // It may be possible to support > 4GB buffers with MUBUF instructions,
1201       // by setting the stride value in the resource descriptor which would
1202       // increase the size limit to (stride * 4GB).  However, this is risky,
1203       // because it has never been validated.
1204     return isLegalFlatAddressingMode(AM);
1205   }
1206 
1207   return isLegalMUBUFAddressingMode(AM);
1208 }
1209 
1210 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1211   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1212   // additionally can do r + r + i with addr64. 32-bit has more addressing
1213   // mode options. Depending on the resource constant, it can also do
1214   // (i64 r0) + (i32 r1) * (i14 i).
1215   //
1216   // Private arrays end up using a scratch buffer most of the time, so also
1217   // assume those use MUBUF instructions. Scratch loads / stores are currently
1218   // implemented as mubuf instructions with offen bit set, so slightly
1219   // different than the normal addr64.
1220   if (!isUInt<12>(AM.BaseOffs))
1221     return false;
1222 
1223   // FIXME: Since we can split immediate into soffset and immediate offset,
1224   // would it make sense to allow any immediate?
1225 
1226   switch (AM.Scale) {
1227   case 0: // r + i or just i, depending on HasBaseReg.
1228     return true;
1229   case 1:
1230     return true; // We have r + r or r + i.
1231   case 2:
1232     if (AM.HasBaseReg) {
1233       // Reject 2 * r + r.
1234       return false;
1235     }
1236 
1237     // Allow 2 * r as r + r
1238     // Or  2 * r + i is allowed as r + r + i.
1239     return true;
1240   default: // Don't allow n * r
1241     return false;
1242   }
1243 }
1244 
1245 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1246                                              const AddrMode &AM, Type *Ty,
1247                                              unsigned AS, Instruction *I) const {
1248   // No global is ever allowed as a base.
1249   if (AM.BaseGV)
1250     return false;
1251 
1252   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1253     return isLegalGlobalAddressingMode(AM);
1254 
1255   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1256       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1257       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1258     // If the offset isn't a multiple of 4, it probably isn't going to be
1259     // correctly aligned.
1260     // FIXME: Can we get the real alignment here?
1261     if (AM.BaseOffs % 4 != 0)
1262       return isLegalMUBUFAddressingMode(AM);
1263 
1264     // There are no SMRD extloads, so if we have to do a small type access we
1265     // will use a MUBUF load.
1266     // FIXME?: We also need to do this if unaligned, but we don't know the
1267     // alignment here.
1268     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1269       return isLegalGlobalAddressingMode(AM);
1270 
1271     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1272       // SMRD instructions have an 8-bit, dword offset on SI.
1273       if (!isUInt<8>(AM.BaseOffs / 4))
1274         return false;
1275     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1276       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1277       // in 8-bits, it can use a smaller encoding.
1278       if (!isUInt<32>(AM.BaseOffs / 4))
1279         return false;
1280     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1281       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1282       if (!isUInt<20>(AM.BaseOffs))
1283         return false;
1284     } else
1285       llvm_unreachable("unhandled generation");
1286 
1287     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1288       return true;
1289 
1290     if (AM.Scale == 1 && AM.HasBaseReg)
1291       return true;
1292 
1293     return false;
1294 
1295   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1296     return isLegalMUBUFAddressingMode(AM);
1297   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1298              AS == AMDGPUAS::REGION_ADDRESS) {
1299     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1300     // field.
1301     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1302     // an 8-bit dword offset but we don't know the alignment here.
1303     if (!isUInt<16>(AM.BaseOffs))
1304       return false;
1305 
1306     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1307       return true;
1308 
1309     if (AM.Scale == 1 && AM.HasBaseReg)
1310       return true;
1311 
1312     return false;
1313   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1314              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1315     // For an unknown address space, this usually means that this is for some
1316     // reason being used for pure arithmetic, and not based on some addressing
1317     // computation. We don't have instructions that compute pointers with any
1318     // addressing modes, so treat them as having no offset like flat
1319     // instructions.
1320     return isLegalFlatAddressingMode(AM);
1321   }
1322 
1323   // Assume a user alias of global for unknown address spaces.
1324   return isLegalGlobalAddressingMode(AM);
1325 }
1326 
1327 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1328                                         const SelectionDAG &DAG) const {
1329   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1330     return (MemVT.getSizeInBits() <= 4 * 32);
1331   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1332     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1333     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1334   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1335     return (MemVT.getSizeInBits() <= 2 * 32);
1336   }
1337   return true;
1338 }
1339 
1340 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1341     unsigned Size, unsigned AddrSpace, unsigned Align,
1342     MachineMemOperand::Flags Flags, bool *IsFast) const {
1343   if (IsFast)
1344     *IsFast = false;
1345 
1346   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1347       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1348     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1349     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1350     // with adjacent offsets.
1351     bool AlignedBy4 = (Align % 4 == 0);
1352     if (IsFast)
1353       *IsFast = AlignedBy4;
1354 
1355     return AlignedBy4;
1356   }
1357 
1358   // FIXME: We have to be conservative here and assume that flat operations
1359   // will access scratch.  If we had access to the IR function, then we
1360   // could determine if any private memory was used in the function.
1361   if (!Subtarget->hasUnalignedScratchAccess() &&
1362       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1363        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1364     bool AlignedBy4 = Align >= 4;
1365     if (IsFast)
1366       *IsFast = AlignedBy4;
1367 
1368     return AlignedBy4;
1369   }
1370 
1371   if (Subtarget->hasUnalignedBufferAccess()) {
1372     // If we have an uniform constant load, it still requires using a slow
1373     // buffer instruction if unaligned.
1374     if (IsFast) {
1375       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1376       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1377       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1378                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1379         Align >= 4 : Align != 2;
1380     }
1381 
1382     return true;
1383   }
1384 
1385   // Smaller than dword value must be aligned.
1386   if (Size < 32)
1387     return false;
1388 
1389   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1390   // byte-address are ignored, thus forcing Dword alignment.
1391   // This applies to private, global, and constant memory.
1392   if (IsFast)
1393     *IsFast = true;
1394 
1395   return Size >= 32 && Align >= 4;
1396 }
1397 
1398 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1399     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1400     bool *IsFast) const {
1401   if (IsFast)
1402     *IsFast = false;
1403 
1404   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1405   // which isn't a simple VT.
1406   // Until MVT is extended to handle this, simply check for the size and
1407   // rely on the condition below: allow accesses if the size is a multiple of 4.
1408   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1409                            VT.getStoreSize() > 16)) {
1410     return false;
1411   }
1412 
1413   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1414                                             Align, Flags, IsFast);
1415 }
1416 
1417 EVT SITargetLowering::getOptimalMemOpType(
1418     const MemOp &Op, const AttributeList &FuncAttributes) const {
1419   // FIXME: Should account for address space here.
1420 
1421   // The default fallback uses the private pointer size as a guess for a type to
1422   // use. Make sure we switch these to 64-bit accesses.
1423 
1424   if (Op.size() >= 16 &&
1425       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1426     return MVT::v4i32;
1427 
1428   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1429     return MVT::v2i32;
1430 
1431   // Use the default.
1432   return MVT::Other;
1433 }
1434 
1435 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1436                                            unsigned DestAS) const {
1437   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1438 }
1439 
1440 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1441   const MemSDNode *MemNode = cast<MemSDNode>(N);
1442   const Value *Ptr = MemNode->getMemOperand()->getValue();
1443   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1444   return I && I->getMetadata("amdgpu.noclobber");
1445 }
1446 
1447 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1448                                            unsigned DestAS) const {
1449   // Flat -> private/local is a simple truncate.
1450   // Flat -> global is no-op
1451   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1452     return true;
1453 
1454   return isNoopAddrSpaceCast(SrcAS, DestAS);
1455 }
1456 
1457 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1458   const MemSDNode *MemNode = cast<MemSDNode>(N);
1459 
1460   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1461 }
1462 
1463 TargetLoweringBase::LegalizeTypeAction
1464 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1465   int NumElts = VT.getVectorNumElements();
1466   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1467     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1468   return TargetLoweringBase::getPreferredVectorAction(VT);
1469 }
1470 
1471 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1472                                                          Type *Ty) const {
1473   // FIXME: Could be smarter if called for vector constants.
1474   return true;
1475 }
1476 
1477 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1478   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1479     switch (Op) {
1480     case ISD::LOAD:
1481     case ISD::STORE:
1482 
1483     // These operations are done with 32-bit instructions anyway.
1484     case ISD::AND:
1485     case ISD::OR:
1486     case ISD::XOR:
1487     case ISD::SELECT:
1488       // TODO: Extensions?
1489       return true;
1490     default:
1491       return false;
1492     }
1493   }
1494 
1495   // SimplifySetCC uses this function to determine whether or not it should
1496   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1497   if (VT == MVT::i1 && Op == ISD::SETCC)
1498     return false;
1499 
1500   return TargetLowering::isTypeDesirableForOp(Op, VT);
1501 }
1502 
1503 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1504                                                    const SDLoc &SL,
1505                                                    SDValue Chain,
1506                                                    uint64_t Offset) const {
1507   const DataLayout &DL = DAG.getDataLayout();
1508   MachineFunction &MF = DAG.getMachineFunction();
1509   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1510 
1511   const ArgDescriptor *InputPtrReg;
1512   const TargetRegisterClass *RC;
1513 
1514   std::tie(InputPtrReg, RC)
1515     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1516 
1517   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1518   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1519   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1520     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1521 
1522   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1523 }
1524 
1525 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1526                                             const SDLoc &SL) const {
1527   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1528                                                FIRST_IMPLICIT);
1529   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1530 }
1531 
1532 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1533                                          const SDLoc &SL, SDValue Val,
1534                                          bool Signed,
1535                                          const ISD::InputArg *Arg) const {
1536   // First, if it is a widened vector, narrow it.
1537   if (VT.isVector() &&
1538       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1539     EVT NarrowedVT =
1540         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1541                          VT.getVectorNumElements());
1542     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1543                       DAG.getConstant(0, SL, MVT::i32));
1544   }
1545 
1546   // Then convert the vector elements or scalar value.
1547   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1548       VT.bitsLT(MemVT)) {
1549     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1550     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1551   }
1552 
1553   if (MemVT.isFloatingPoint())
1554     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1555   else if (Signed)
1556     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1557   else
1558     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1559 
1560   return Val;
1561 }
1562 
1563 SDValue SITargetLowering::lowerKernargMemParameter(
1564   SelectionDAG &DAG, EVT VT, EVT MemVT,
1565   const SDLoc &SL, SDValue Chain,
1566   uint64_t Offset, unsigned Align, bool Signed,
1567   const ISD::InputArg *Arg) const {
1568   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1569 
1570   // Try to avoid using an extload by loading earlier than the argument address,
1571   // and extracting the relevant bits. The load should hopefully be merged with
1572   // the previous argument.
1573   if (MemVT.getStoreSize() < 4 && Align < 4) {
1574     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1575     int64_t AlignDownOffset = alignDown(Offset, 4);
1576     int64_t OffsetDiff = Offset - AlignDownOffset;
1577 
1578     EVT IntVT = MemVT.changeTypeToInteger();
1579 
1580     // TODO: If we passed in the base kernel offset we could have a better
1581     // alignment than 4, but we don't really need it.
1582     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1583     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1584                                MachineMemOperand::MODereferenceable |
1585                                MachineMemOperand::MOInvariant);
1586 
1587     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1588     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1589 
1590     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1591     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1592     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1593 
1594 
1595     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1596   }
1597 
1598   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1599   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1600                              MachineMemOperand::MODereferenceable |
1601                              MachineMemOperand::MOInvariant);
1602 
1603   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1604   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1605 }
1606 
1607 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1608                                               const SDLoc &SL, SDValue Chain,
1609                                               const ISD::InputArg &Arg) const {
1610   MachineFunction &MF = DAG.getMachineFunction();
1611   MachineFrameInfo &MFI = MF.getFrameInfo();
1612 
1613   if (Arg.Flags.isByVal()) {
1614     unsigned Size = Arg.Flags.getByValSize();
1615     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1616     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1617   }
1618 
1619   unsigned ArgOffset = VA.getLocMemOffset();
1620   unsigned ArgSize = VA.getValVT().getStoreSize();
1621 
1622   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1623 
1624   // Create load nodes to retrieve arguments from the stack.
1625   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1626   SDValue ArgValue;
1627 
1628   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1629   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1630   MVT MemVT = VA.getValVT();
1631 
1632   switch (VA.getLocInfo()) {
1633   default:
1634     break;
1635   case CCValAssign::BCvt:
1636     MemVT = VA.getLocVT();
1637     break;
1638   case CCValAssign::SExt:
1639     ExtType = ISD::SEXTLOAD;
1640     break;
1641   case CCValAssign::ZExt:
1642     ExtType = ISD::ZEXTLOAD;
1643     break;
1644   case CCValAssign::AExt:
1645     ExtType = ISD::EXTLOAD;
1646     break;
1647   }
1648 
1649   ArgValue = DAG.getExtLoad(
1650     ExtType, SL, VA.getLocVT(), Chain, FIN,
1651     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1652     MemVT);
1653   return ArgValue;
1654 }
1655 
1656 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1657   const SIMachineFunctionInfo &MFI,
1658   EVT VT,
1659   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1660   const ArgDescriptor *Reg;
1661   const TargetRegisterClass *RC;
1662 
1663   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1664   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1665 }
1666 
1667 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1668                                    CallingConv::ID CallConv,
1669                                    ArrayRef<ISD::InputArg> Ins,
1670                                    BitVector &Skipped,
1671                                    FunctionType *FType,
1672                                    SIMachineFunctionInfo *Info) {
1673   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1674     const ISD::InputArg *Arg = &Ins[I];
1675 
1676     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1677            "vector type argument should have been split");
1678 
1679     // First check if it's a PS input addr.
1680     if (CallConv == CallingConv::AMDGPU_PS &&
1681         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1682       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1683 
1684       // Inconveniently only the first part of the split is marked as isSplit,
1685       // so skip to the end. We only want to increment PSInputNum once for the
1686       // entire split argument.
1687       if (Arg->Flags.isSplit()) {
1688         while (!Arg->Flags.isSplitEnd()) {
1689           assert((!Arg->VT.isVector() ||
1690                   Arg->VT.getScalarSizeInBits() == 16) &&
1691                  "unexpected vector split in ps argument type");
1692           if (!SkipArg)
1693             Splits.push_back(*Arg);
1694           Arg = &Ins[++I];
1695         }
1696       }
1697 
1698       if (SkipArg) {
1699         // We can safely skip PS inputs.
1700         Skipped.set(Arg->getOrigArgIndex());
1701         ++PSInputNum;
1702         continue;
1703       }
1704 
1705       Info->markPSInputAllocated(PSInputNum);
1706       if (Arg->Used)
1707         Info->markPSInputEnabled(PSInputNum);
1708 
1709       ++PSInputNum;
1710     }
1711 
1712     Splits.push_back(*Arg);
1713   }
1714 }
1715 
1716 // Allocate special inputs passed in VGPRs.
1717 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1718                                                       MachineFunction &MF,
1719                                                       const SIRegisterInfo &TRI,
1720                                                       SIMachineFunctionInfo &Info) const {
1721   const LLT S32 = LLT::scalar(32);
1722   MachineRegisterInfo &MRI = MF.getRegInfo();
1723 
1724   if (Info.hasWorkItemIDX()) {
1725     Register Reg = AMDGPU::VGPR0;
1726     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1727 
1728     CCInfo.AllocateReg(Reg);
1729     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1730   }
1731 
1732   if (Info.hasWorkItemIDY()) {
1733     Register Reg = AMDGPU::VGPR1;
1734     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1735 
1736     CCInfo.AllocateReg(Reg);
1737     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1738   }
1739 
1740   if (Info.hasWorkItemIDZ()) {
1741     Register Reg = AMDGPU::VGPR2;
1742     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1743 
1744     CCInfo.AllocateReg(Reg);
1745     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1746   }
1747 }
1748 
1749 // Try to allocate a VGPR at the end of the argument list, or if no argument
1750 // VGPRs are left allocating a stack slot.
1751 // If \p Mask is is given it indicates bitfield position in the register.
1752 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1753 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1754                                          ArgDescriptor Arg = ArgDescriptor()) {
1755   if (Arg.isSet())
1756     return ArgDescriptor::createArg(Arg, Mask);
1757 
1758   ArrayRef<MCPhysReg> ArgVGPRs
1759     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1760   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1761   if (RegIdx == ArgVGPRs.size()) {
1762     // Spill to stack required.
1763     int64_t Offset = CCInfo.AllocateStack(4, 4);
1764 
1765     return ArgDescriptor::createStack(Offset, Mask);
1766   }
1767 
1768   unsigned Reg = ArgVGPRs[RegIdx];
1769   Reg = CCInfo.AllocateReg(Reg);
1770   assert(Reg != AMDGPU::NoRegister);
1771 
1772   MachineFunction &MF = CCInfo.getMachineFunction();
1773   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1774   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1775   return ArgDescriptor::createRegister(Reg, Mask);
1776 }
1777 
1778 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1779                                              const TargetRegisterClass *RC,
1780                                              unsigned NumArgRegs) {
1781   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1782   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1783   if (RegIdx == ArgSGPRs.size())
1784     report_fatal_error("ran out of SGPRs for arguments");
1785 
1786   unsigned Reg = ArgSGPRs[RegIdx];
1787   Reg = CCInfo.AllocateReg(Reg);
1788   assert(Reg != AMDGPU::NoRegister);
1789 
1790   MachineFunction &MF = CCInfo.getMachineFunction();
1791   MF.addLiveIn(Reg, RC);
1792   return ArgDescriptor::createRegister(Reg);
1793 }
1794 
1795 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1796   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1797 }
1798 
1799 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1800   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1801 }
1802 
1803 /// Allocate implicit function VGPR arguments at the end of allocated user
1804 /// arguments.
1805 void SITargetLowering::allocateSpecialInputVGPRs(
1806   CCState &CCInfo, MachineFunction &MF,
1807   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1808   const unsigned Mask = 0x3ff;
1809   ArgDescriptor Arg;
1810 
1811   if (Info.hasWorkItemIDX()) {
1812     Arg = allocateVGPR32Input(CCInfo, Mask);
1813     Info.setWorkItemIDX(Arg);
1814   }
1815 
1816   if (Info.hasWorkItemIDY()) {
1817     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1818     Info.setWorkItemIDY(Arg);
1819   }
1820 
1821   if (Info.hasWorkItemIDZ())
1822     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1823 }
1824 
1825 /// Allocate implicit function VGPR arguments in fixed registers.
1826 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1827   CCState &CCInfo, MachineFunction &MF,
1828   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1829   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1830   if (!Reg)
1831     report_fatal_error("failed to allocated VGPR for implicit arguments");
1832 
1833   const unsigned Mask = 0x3ff;
1834   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1835   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1836   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1837 }
1838 
1839 void SITargetLowering::allocateSpecialInputSGPRs(
1840   CCState &CCInfo,
1841   MachineFunction &MF,
1842   const SIRegisterInfo &TRI,
1843   SIMachineFunctionInfo &Info) const {
1844   auto &ArgInfo = Info.getArgInfo();
1845 
1846   // TODO: Unify handling with private memory pointers.
1847 
1848   if (Info.hasDispatchPtr())
1849     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1850 
1851   if (Info.hasQueuePtr())
1852     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1853 
1854   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1855   // constant offset from the kernarg segment.
1856   if (Info.hasImplicitArgPtr())
1857     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1858 
1859   if (Info.hasDispatchID())
1860     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1861 
1862   // flat_scratch_init is not applicable for non-kernel functions.
1863 
1864   if (Info.hasWorkGroupIDX())
1865     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1866 
1867   if (Info.hasWorkGroupIDY())
1868     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1869 
1870   if (Info.hasWorkGroupIDZ())
1871     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1872 }
1873 
1874 // Allocate special inputs passed in user SGPRs.
1875 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1876                                             MachineFunction &MF,
1877                                             const SIRegisterInfo &TRI,
1878                                             SIMachineFunctionInfo &Info) const {
1879   if (Info.hasImplicitBufferPtr()) {
1880     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1881     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1882     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1883   }
1884 
1885   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1886   if (Info.hasPrivateSegmentBuffer()) {
1887     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1888     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1889     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1890   }
1891 
1892   if (Info.hasDispatchPtr()) {
1893     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1894     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1895     CCInfo.AllocateReg(DispatchPtrReg);
1896   }
1897 
1898   if (Info.hasQueuePtr()) {
1899     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1900     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1901     CCInfo.AllocateReg(QueuePtrReg);
1902   }
1903 
1904   if (Info.hasKernargSegmentPtr()) {
1905     MachineRegisterInfo &MRI = MF.getRegInfo();
1906     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1907     CCInfo.AllocateReg(InputPtrReg);
1908 
1909     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1910     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1911   }
1912 
1913   if (Info.hasDispatchID()) {
1914     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1915     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1916     CCInfo.AllocateReg(DispatchIDReg);
1917   }
1918 
1919   if (Info.hasFlatScratchInit()) {
1920     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1921     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1922     CCInfo.AllocateReg(FlatScratchInitReg);
1923   }
1924 
1925   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1926   // these from the dispatch pointer.
1927 }
1928 
1929 // Allocate special input registers that are initialized per-wave.
1930 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1931                                            MachineFunction &MF,
1932                                            SIMachineFunctionInfo &Info,
1933                                            CallingConv::ID CallConv,
1934                                            bool IsShader) const {
1935   if (Info.hasWorkGroupIDX()) {
1936     unsigned Reg = Info.addWorkGroupIDX();
1937     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1938     CCInfo.AllocateReg(Reg);
1939   }
1940 
1941   if (Info.hasWorkGroupIDY()) {
1942     unsigned Reg = Info.addWorkGroupIDY();
1943     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1944     CCInfo.AllocateReg(Reg);
1945   }
1946 
1947   if (Info.hasWorkGroupIDZ()) {
1948     unsigned Reg = Info.addWorkGroupIDZ();
1949     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1950     CCInfo.AllocateReg(Reg);
1951   }
1952 
1953   if (Info.hasWorkGroupInfo()) {
1954     unsigned Reg = Info.addWorkGroupInfo();
1955     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1956     CCInfo.AllocateReg(Reg);
1957   }
1958 
1959   if (Info.hasPrivateSegmentWaveByteOffset()) {
1960     // Scratch wave offset passed in system SGPR.
1961     unsigned PrivateSegmentWaveByteOffsetReg;
1962 
1963     if (IsShader) {
1964       PrivateSegmentWaveByteOffsetReg =
1965         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1966 
1967       // This is true if the scratch wave byte offset doesn't have a fixed
1968       // location.
1969       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1970         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1971         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1972       }
1973     } else
1974       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1975 
1976     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1977     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1978   }
1979 }
1980 
1981 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1982                                      MachineFunction &MF,
1983                                      const SIRegisterInfo &TRI,
1984                                      SIMachineFunctionInfo &Info) {
1985   // Now that we've figured out where the scratch register inputs are, see if
1986   // should reserve the arguments and use them directly.
1987   MachineFrameInfo &MFI = MF.getFrameInfo();
1988   bool HasStackObjects = MFI.hasStackObjects();
1989   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1990 
1991   // Record that we know we have non-spill stack objects so we don't need to
1992   // check all stack objects later.
1993   if (HasStackObjects)
1994     Info.setHasNonSpillStackObjects(true);
1995 
1996   // Everything live out of a block is spilled with fast regalloc, so it's
1997   // almost certain that spilling will be required.
1998   if (TM.getOptLevel() == CodeGenOpt::None)
1999     HasStackObjects = true;
2000 
2001   // For now assume stack access is needed in any callee functions, so we need
2002   // the scratch registers to pass in.
2003   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2004 
2005   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2006     // If we have stack objects, we unquestionably need the private buffer
2007     // resource. For the Code Object V2 ABI, this will be the first 4 user
2008     // SGPR inputs. We can reserve those and use them directly.
2009 
2010     Register PrivateSegmentBufferReg =
2011         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2012     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2013   } else {
2014     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2015     // We tentatively reserve the last registers (skipping the last registers
2016     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2017     // we'll replace these with the ones immediately after those which were
2018     // really allocated. In the prologue copies will be inserted from the
2019     // argument to these reserved registers.
2020 
2021     // Without HSA, relocations are used for the scratch pointer and the
2022     // buffer resource setup is always inserted in the prologue. Scratch wave
2023     // offset is still in an input SGPR.
2024     Info.setScratchRSrcReg(ReservedBufferReg);
2025   }
2026 
2027   MachineRegisterInfo &MRI = MF.getRegInfo();
2028 
2029   // For entry functions we have to set up the stack pointer if we use it,
2030   // whereas non-entry functions get this "for free". This means there is no
2031   // intrinsic advantage to using S32 over S34 in cases where we do not have
2032   // calls but do need a frame pointer (i.e. if we are requested to have one
2033   // because frame pointer elimination is disabled). To keep things simple we
2034   // only ever use S32 as the call ABI stack pointer, and so using it does not
2035   // imply we need a separate frame pointer.
2036   //
2037   // Try to use s32 as the SP, but move it if it would interfere with input
2038   // arguments. This won't work with calls though.
2039   //
2040   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2041   // registers.
2042   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2043     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2044   } else {
2045     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2046 
2047     if (MFI.hasCalls())
2048       report_fatal_error("call in graphics shader with too many input SGPRs");
2049 
2050     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2051       if (!MRI.isLiveIn(Reg)) {
2052         Info.setStackPtrOffsetReg(Reg);
2053         break;
2054       }
2055     }
2056 
2057     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2058       report_fatal_error("failed to find register for SP");
2059   }
2060 
2061   // hasFP should be accurate for entry functions even before the frame is
2062   // finalized, because it does not rely on the known stack size, only
2063   // properties like whether variable sized objects are present.
2064   if (ST.getFrameLowering()->hasFP(MF)) {
2065     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2066   }
2067 }
2068 
2069 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2070   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2071   return !Info->isEntryFunction();
2072 }
2073 
2074 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2075 
2076 }
2077 
2078 void SITargetLowering::insertCopiesSplitCSR(
2079   MachineBasicBlock *Entry,
2080   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2081   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2082 
2083   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2084   if (!IStart)
2085     return;
2086 
2087   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2088   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2089   MachineBasicBlock::iterator MBBI = Entry->begin();
2090   for (const MCPhysReg *I = IStart; *I; ++I) {
2091     const TargetRegisterClass *RC = nullptr;
2092     if (AMDGPU::SReg_64RegClass.contains(*I))
2093       RC = &AMDGPU::SGPR_64RegClass;
2094     else if (AMDGPU::SReg_32RegClass.contains(*I))
2095       RC = &AMDGPU::SGPR_32RegClass;
2096     else
2097       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2098 
2099     Register NewVR = MRI->createVirtualRegister(RC);
2100     // Create copy from CSR to a virtual register.
2101     Entry->addLiveIn(*I);
2102     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2103       .addReg(*I);
2104 
2105     // Insert the copy-back instructions right before the terminator.
2106     for (auto *Exit : Exits)
2107       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2108               TII->get(TargetOpcode::COPY), *I)
2109         .addReg(NewVR);
2110   }
2111 }
2112 
2113 SDValue SITargetLowering::LowerFormalArguments(
2114     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2115     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2116     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2117   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2118 
2119   MachineFunction &MF = DAG.getMachineFunction();
2120   const Function &Fn = MF.getFunction();
2121   FunctionType *FType = MF.getFunction().getFunctionType();
2122   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2123 
2124   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2125     DiagnosticInfoUnsupported NoGraphicsHSA(
2126         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2127     DAG.getContext()->diagnose(NoGraphicsHSA);
2128     return DAG.getEntryNode();
2129   }
2130 
2131   SmallVector<ISD::InputArg, 16> Splits;
2132   SmallVector<CCValAssign, 16> ArgLocs;
2133   BitVector Skipped(Ins.size());
2134   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2135                  *DAG.getContext());
2136 
2137   bool IsShader = AMDGPU::isShader(CallConv);
2138   bool IsKernel = AMDGPU::isKernel(CallConv);
2139   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2140 
2141   if (IsShader) {
2142     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2143 
2144     // At least one interpolation mode must be enabled or else the GPU will
2145     // hang.
2146     //
2147     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2148     // set PSInputAddr, the user wants to enable some bits after the compilation
2149     // based on run-time states. Since we can't know what the final PSInputEna
2150     // will look like, so we shouldn't do anything here and the user should take
2151     // responsibility for the correct programming.
2152     //
2153     // Otherwise, the following restrictions apply:
2154     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2155     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2156     //   enabled too.
2157     if (CallConv == CallingConv::AMDGPU_PS) {
2158       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2159            ((Info->getPSInputAddr() & 0xF) == 0 &&
2160             Info->isPSInputAllocated(11))) {
2161         CCInfo.AllocateReg(AMDGPU::VGPR0);
2162         CCInfo.AllocateReg(AMDGPU::VGPR1);
2163         Info->markPSInputAllocated(0);
2164         Info->markPSInputEnabled(0);
2165       }
2166       if (Subtarget->isAmdPalOS()) {
2167         // For isAmdPalOS, the user does not enable some bits after compilation
2168         // based on run-time states; the register values being generated here are
2169         // the final ones set in hardware. Therefore we need to apply the
2170         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2171         // a bit is set in PSInputAddr but not PSInputEnable is where the
2172         // frontend set up an input arg for a particular interpolation mode, but
2173         // nothing uses that input arg. Really we should have an earlier pass
2174         // that removes such an arg.)
2175         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2176         if ((PsInputBits & 0x7F) == 0 ||
2177             ((PsInputBits & 0xF) == 0 &&
2178              (PsInputBits >> 11 & 1)))
2179           Info->markPSInputEnabled(
2180               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2181       }
2182     }
2183 
2184     assert(!Info->hasDispatchPtr() &&
2185            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2186            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2187            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2188            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2189            !Info->hasWorkItemIDZ());
2190   } else if (IsKernel) {
2191     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2192   } else {
2193     Splits.append(Ins.begin(), Ins.end());
2194   }
2195 
2196   if (IsEntryFunc) {
2197     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2198     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2199   } else {
2200     // For the fixed ABI, pass workitem IDs in the last argument register.
2201     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2202       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2203   }
2204 
2205   if (IsKernel) {
2206     analyzeFormalArgumentsCompute(CCInfo, Ins);
2207   } else {
2208     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2209     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2210   }
2211 
2212   SmallVector<SDValue, 16> Chains;
2213 
2214   // FIXME: This is the minimum kernel argument alignment. We should improve
2215   // this to the maximum alignment of the arguments.
2216   //
2217   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2218   // kern arg offset.
2219   const unsigned KernelArgBaseAlign = 16;
2220 
2221    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2222     const ISD::InputArg &Arg = Ins[i];
2223     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2224       InVals.push_back(DAG.getUNDEF(Arg.VT));
2225       continue;
2226     }
2227 
2228     CCValAssign &VA = ArgLocs[ArgIdx++];
2229     MVT VT = VA.getLocVT();
2230 
2231     if (IsEntryFunc && VA.isMemLoc()) {
2232       VT = Ins[i].VT;
2233       EVT MemVT = VA.getLocVT();
2234 
2235       const uint64_t Offset = VA.getLocMemOffset();
2236       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2237 
2238       SDValue Arg = lowerKernargMemParameter(
2239         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2240       Chains.push_back(Arg.getValue(1));
2241 
2242       auto *ParamTy =
2243         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2244       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2245           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2246                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2247         // On SI local pointers are just offsets into LDS, so they are always
2248         // less than 16-bits.  On CI and newer they could potentially be
2249         // real pointers, so we can't guarantee their size.
2250         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2251                           DAG.getValueType(MVT::i16));
2252       }
2253 
2254       InVals.push_back(Arg);
2255       continue;
2256     } else if (!IsEntryFunc && VA.isMemLoc()) {
2257       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2258       InVals.push_back(Val);
2259       if (!Arg.Flags.isByVal())
2260         Chains.push_back(Val.getValue(1));
2261       continue;
2262     }
2263 
2264     assert(VA.isRegLoc() && "Parameter must be in a register!");
2265 
2266     Register Reg = VA.getLocReg();
2267     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2268     EVT ValVT = VA.getValVT();
2269 
2270     Reg = MF.addLiveIn(Reg, RC);
2271     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2272 
2273     if (Arg.Flags.isSRet()) {
2274       // The return object should be reasonably addressable.
2275 
2276       // FIXME: This helps when the return is a real sret. If it is a
2277       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2278       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2279       unsigned NumBits
2280         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2281       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2282         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2283     }
2284 
2285     // If this is an 8 or 16-bit value, it is really passed promoted
2286     // to 32 bits. Insert an assert[sz]ext to capture this, then
2287     // truncate to the right size.
2288     switch (VA.getLocInfo()) {
2289     case CCValAssign::Full:
2290       break;
2291     case CCValAssign::BCvt:
2292       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2293       break;
2294     case CCValAssign::SExt:
2295       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2296                         DAG.getValueType(ValVT));
2297       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2298       break;
2299     case CCValAssign::ZExt:
2300       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2301                         DAG.getValueType(ValVT));
2302       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2303       break;
2304     case CCValAssign::AExt:
2305       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2306       break;
2307     default:
2308       llvm_unreachable("Unknown loc info!");
2309     }
2310 
2311     InVals.push_back(Val);
2312   }
2313 
2314   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2315     // Special inputs come after user arguments.
2316     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2317   }
2318 
2319   // Start adding system SGPRs.
2320   if (IsEntryFunc) {
2321     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2322   } else {
2323     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2324     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2325   }
2326 
2327   auto &ArgUsageInfo =
2328     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2329   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2330 
2331   unsigned StackArgSize = CCInfo.getNextStackOffset();
2332   Info->setBytesInStackArgArea(StackArgSize);
2333 
2334   return Chains.empty() ? Chain :
2335     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2336 }
2337 
2338 // TODO: If return values can't fit in registers, we should return as many as
2339 // possible in registers before passing on stack.
2340 bool SITargetLowering::CanLowerReturn(
2341   CallingConv::ID CallConv,
2342   MachineFunction &MF, bool IsVarArg,
2343   const SmallVectorImpl<ISD::OutputArg> &Outs,
2344   LLVMContext &Context) const {
2345   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2346   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2347   // for shaders. Vector types should be explicitly handled by CC.
2348   if (AMDGPU::isEntryFunctionCC(CallConv))
2349     return true;
2350 
2351   SmallVector<CCValAssign, 16> RVLocs;
2352   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2353   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2354 }
2355 
2356 SDValue
2357 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2358                               bool isVarArg,
2359                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2360                               const SmallVectorImpl<SDValue> &OutVals,
2361                               const SDLoc &DL, SelectionDAG &DAG) const {
2362   MachineFunction &MF = DAG.getMachineFunction();
2363   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2364 
2365   if (AMDGPU::isKernel(CallConv)) {
2366     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2367                                              OutVals, DL, DAG);
2368   }
2369 
2370   bool IsShader = AMDGPU::isShader(CallConv);
2371 
2372   Info->setIfReturnsVoid(Outs.empty());
2373   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2374 
2375   // CCValAssign - represent the assignment of the return value to a location.
2376   SmallVector<CCValAssign, 48> RVLocs;
2377   SmallVector<ISD::OutputArg, 48> Splits;
2378 
2379   // CCState - Info about the registers and stack slots.
2380   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2381                  *DAG.getContext());
2382 
2383   // Analyze outgoing return values.
2384   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2385 
2386   SDValue Flag;
2387   SmallVector<SDValue, 48> RetOps;
2388   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2389 
2390   // Add return address for callable functions.
2391   if (!Info->isEntryFunction()) {
2392     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2393     SDValue ReturnAddrReg = CreateLiveInRegister(
2394       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2395 
2396     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2397         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2398         MVT::i64);
2399     Chain =
2400         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2401     Flag = Chain.getValue(1);
2402     RetOps.push_back(ReturnAddrVirtualReg);
2403   }
2404 
2405   // Copy the result values into the output registers.
2406   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2407        ++I, ++RealRVLocIdx) {
2408     CCValAssign &VA = RVLocs[I];
2409     assert(VA.isRegLoc() && "Can only return in registers!");
2410     // TODO: Partially return in registers if return values don't fit.
2411     SDValue Arg = OutVals[RealRVLocIdx];
2412 
2413     // Copied from other backends.
2414     switch (VA.getLocInfo()) {
2415     case CCValAssign::Full:
2416       break;
2417     case CCValAssign::BCvt:
2418       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2419       break;
2420     case CCValAssign::SExt:
2421       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2422       break;
2423     case CCValAssign::ZExt:
2424       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2425       break;
2426     case CCValAssign::AExt:
2427       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2428       break;
2429     default:
2430       llvm_unreachable("Unknown loc info!");
2431     }
2432 
2433     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2434     Flag = Chain.getValue(1);
2435     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2436   }
2437 
2438   // FIXME: Does sret work properly?
2439   if (!Info->isEntryFunction()) {
2440     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2441     const MCPhysReg *I =
2442       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2443     if (I) {
2444       for (; *I; ++I) {
2445         if (AMDGPU::SReg_64RegClass.contains(*I))
2446           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2447         else if (AMDGPU::SReg_32RegClass.contains(*I))
2448           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2449         else
2450           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2451       }
2452     }
2453   }
2454 
2455   // Update chain and glue.
2456   RetOps[0] = Chain;
2457   if (Flag.getNode())
2458     RetOps.push_back(Flag);
2459 
2460   unsigned Opc = AMDGPUISD::ENDPGM;
2461   if (!IsWaveEnd)
2462     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2463   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2464 }
2465 
2466 SDValue SITargetLowering::LowerCallResult(
2467     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2468     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2469     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2470     SDValue ThisVal) const {
2471   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2472 
2473   // Assign locations to each value returned by this call.
2474   SmallVector<CCValAssign, 16> RVLocs;
2475   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2476                  *DAG.getContext());
2477   CCInfo.AnalyzeCallResult(Ins, RetCC);
2478 
2479   // Copy all of the result registers out of their specified physreg.
2480   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2481     CCValAssign VA = RVLocs[i];
2482     SDValue Val;
2483 
2484     if (VA.isRegLoc()) {
2485       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2486       Chain = Val.getValue(1);
2487       InFlag = Val.getValue(2);
2488     } else if (VA.isMemLoc()) {
2489       report_fatal_error("TODO: return values in memory");
2490     } else
2491       llvm_unreachable("unknown argument location type");
2492 
2493     switch (VA.getLocInfo()) {
2494     case CCValAssign::Full:
2495       break;
2496     case CCValAssign::BCvt:
2497       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2498       break;
2499     case CCValAssign::ZExt:
2500       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2501                         DAG.getValueType(VA.getValVT()));
2502       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2503       break;
2504     case CCValAssign::SExt:
2505       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2506                         DAG.getValueType(VA.getValVT()));
2507       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2508       break;
2509     case CCValAssign::AExt:
2510       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2511       break;
2512     default:
2513       llvm_unreachable("Unknown loc info!");
2514     }
2515 
2516     InVals.push_back(Val);
2517   }
2518 
2519   return Chain;
2520 }
2521 
2522 // Add code to pass special inputs required depending on used features separate
2523 // from the explicit user arguments present in the IR.
2524 void SITargetLowering::passSpecialInputs(
2525     CallLoweringInfo &CLI,
2526     CCState &CCInfo,
2527     const SIMachineFunctionInfo &Info,
2528     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2529     SmallVectorImpl<SDValue> &MemOpChains,
2530     SDValue Chain) const {
2531   // If we don't have a call site, this was a call inserted by
2532   // legalization. These can never use special inputs.
2533   if (!CLI.CB)
2534     return;
2535 
2536   SelectionDAG &DAG = CLI.DAG;
2537   const SDLoc &DL = CLI.DL;
2538 
2539   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2540   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2541 
2542   const AMDGPUFunctionArgInfo *CalleeArgInfo
2543     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2544   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2545     auto &ArgUsageInfo =
2546       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2547     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2548   }
2549 
2550   // TODO: Unify with private memory register handling. This is complicated by
2551   // the fact that at least in kernels, the input argument is not necessarily
2552   // in the same location as the input.
2553   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2554     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2555     AMDGPUFunctionArgInfo::QUEUE_PTR,
2556     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2557     AMDGPUFunctionArgInfo::DISPATCH_ID,
2558     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2559     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2560     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2561   };
2562 
2563   for (auto InputID : InputRegs) {
2564     const ArgDescriptor *OutgoingArg;
2565     const TargetRegisterClass *ArgRC;
2566 
2567     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2568     if (!OutgoingArg)
2569       continue;
2570 
2571     const ArgDescriptor *IncomingArg;
2572     const TargetRegisterClass *IncomingArgRC;
2573     std::tie(IncomingArg, IncomingArgRC)
2574       = CallerArgInfo.getPreloadedValue(InputID);
2575     assert(IncomingArgRC == ArgRC);
2576 
2577     // All special arguments are ints for now.
2578     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2579     SDValue InputReg;
2580 
2581     if (IncomingArg) {
2582       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2583     } else {
2584       // The implicit arg ptr is special because it doesn't have a corresponding
2585       // input for kernels, and is computed from the kernarg segment pointer.
2586       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2587       InputReg = getImplicitArgPtr(DAG, DL);
2588     }
2589 
2590     if (OutgoingArg->isRegister()) {
2591       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2592       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2593         report_fatal_error("failed to allocate implicit input argument");
2594     } else {
2595       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2596       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2597                                               SpecialArgOffset);
2598       MemOpChains.push_back(ArgStore);
2599     }
2600   }
2601 
2602   // Pack workitem IDs into a single register or pass it as is if already
2603   // packed.
2604   const ArgDescriptor *OutgoingArg;
2605   const TargetRegisterClass *ArgRC;
2606 
2607   std::tie(OutgoingArg, ArgRC) =
2608     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2609   if (!OutgoingArg)
2610     std::tie(OutgoingArg, ArgRC) =
2611       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2612   if (!OutgoingArg)
2613     std::tie(OutgoingArg, ArgRC) =
2614       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2615   if (!OutgoingArg)
2616     return;
2617 
2618   const ArgDescriptor *IncomingArgX
2619     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2620   const ArgDescriptor *IncomingArgY
2621     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2622   const ArgDescriptor *IncomingArgZ
2623     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2624 
2625   SDValue InputReg;
2626   SDLoc SL;
2627 
2628   // If incoming ids are not packed we need to pack them.
2629   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2630     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2631 
2632   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2633     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2634     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2635                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2636     InputReg = InputReg.getNode() ?
2637                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2638   }
2639 
2640   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2641     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2642     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2643                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2644     InputReg = InputReg.getNode() ?
2645                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2646   }
2647 
2648   if (!InputReg.getNode()) {
2649     // Workitem ids are already packed, any of present incoming arguments
2650     // will carry all required fields.
2651     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2652       IncomingArgX ? *IncomingArgX :
2653       IncomingArgY ? *IncomingArgY :
2654                      *IncomingArgZ, ~0u);
2655     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2656   }
2657 
2658   if (OutgoingArg->isRegister()) {
2659     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2660     CCInfo.AllocateReg(OutgoingArg->getRegister());
2661   } else {
2662     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2663     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2664                                             SpecialArgOffset);
2665     MemOpChains.push_back(ArgStore);
2666   }
2667 }
2668 
2669 static bool canGuaranteeTCO(CallingConv::ID CC) {
2670   return CC == CallingConv::Fast;
2671 }
2672 
2673 /// Return true if we might ever do TCO for calls with this calling convention.
2674 static bool mayTailCallThisCC(CallingConv::ID CC) {
2675   switch (CC) {
2676   case CallingConv::C:
2677     return true;
2678   default:
2679     return canGuaranteeTCO(CC);
2680   }
2681 }
2682 
2683 bool SITargetLowering::isEligibleForTailCallOptimization(
2684     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2685     const SmallVectorImpl<ISD::OutputArg> &Outs,
2686     const SmallVectorImpl<SDValue> &OutVals,
2687     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2688   if (!mayTailCallThisCC(CalleeCC))
2689     return false;
2690 
2691   MachineFunction &MF = DAG.getMachineFunction();
2692   const Function &CallerF = MF.getFunction();
2693   CallingConv::ID CallerCC = CallerF.getCallingConv();
2694   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2695   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2696 
2697   // Kernels aren't callable, and don't have a live in return address so it
2698   // doesn't make sense to do a tail call with entry functions.
2699   if (!CallerPreserved)
2700     return false;
2701 
2702   bool CCMatch = CallerCC == CalleeCC;
2703 
2704   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2705     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2706       return true;
2707     return false;
2708   }
2709 
2710   // TODO: Can we handle var args?
2711   if (IsVarArg)
2712     return false;
2713 
2714   for (const Argument &Arg : CallerF.args()) {
2715     if (Arg.hasByValAttr())
2716       return false;
2717   }
2718 
2719   LLVMContext &Ctx = *DAG.getContext();
2720 
2721   // Check that the call results are passed in the same way.
2722   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2723                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2724                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2725     return false;
2726 
2727   // The callee has to preserve all registers the caller needs to preserve.
2728   if (!CCMatch) {
2729     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2730     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2731       return false;
2732   }
2733 
2734   // Nothing more to check if the callee is taking no arguments.
2735   if (Outs.empty())
2736     return true;
2737 
2738   SmallVector<CCValAssign, 16> ArgLocs;
2739   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2740 
2741   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2742 
2743   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2744   // If the stack arguments for this call do not fit into our own save area then
2745   // the call cannot be made tail.
2746   // TODO: Is this really necessary?
2747   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2748     return false;
2749 
2750   const MachineRegisterInfo &MRI = MF.getRegInfo();
2751   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2752 }
2753 
2754 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2755   if (!CI->isTailCall())
2756     return false;
2757 
2758   const Function *ParentFn = CI->getParent()->getParent();
2759   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2760     return false;
2761   return true;
2762 }
2763 
2764 // The wave scratch offset register is used as the global base pointer.
2765 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2766                                     SmallVectorImpl<SDValue> &InVals) const {
2767   SelectionDAG &DAG = CLI.DAG;
2768   const SDLoc &DL = CLI.DL;
2769   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2770   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2771   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2772   SDValue Chain = CLI.Chain;
2773   SDValue Callee = CLI.Callee;
2774   bool &IsTailCall = CLI.IsTailCall;
2775   CallingConv::ID CallConv = CLI.CallConv;
2776   bool IsVarArg = CLI.IsVarArg;
2777   bool IsSibCall = false;
2778   bool IsThisReturn = false;
2779   MachineFunction &MF = DAG.getMachineFunction();
2780 
2781   if (Callee.isUndef() || isNullConstant(Callee)) {
2782     if (!CLI.IsTailCall) {
2783       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2784         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2785     }
2786 
2787     return Chain;
2788   }
2789 
2790   if (IsVarArg) {
2791     return lowerUnhandledCall(CLI, InVals,
2792                               "unsupported call to variadic function ");
2793   }
2794 
2795   if (!CLI.CB)
2796     report_fatal_error("unsupported libcall legalization");
2797 
2798   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2799       !CLI.CB->getCalledFunction()) {
2800     return lowerUnhandledCall(CLI, InVals,
2801                               "unsupported indirect call to function ");
2802   }
2803 
2804   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2805     return lowerUnhandledCall(CLI, InVals,
2806                               "unsupported required tail call to function ");
2807   }
2808 
2809   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2810     // Note the issue is with the CC of the calling function, not of the call
2811     // itself.
2812     return lowerUnhandledCall(CLI, InVals,
2813                           "unsupported call from graphics shader of function ");
2814   }
2815 
2816   if (IsTailCall) {
2817     IsTailCall = isEligibleForTailCallOptimization(
2818       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2819     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2820       report_fatal_error("failed to perform tail call elimination on a call "
2821                          "site marked musttail");
2822     }
2823 
2824     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2825 
2826     // A sibling call is one where we're under the usual C ABI and not planning
2827     // to change that but can still do a tail call:
2828     if (!TailCallOpt && IsTailCall)
2829       IsSibCall = true;
2830 
2831     if (IsTailCall)
2832       ++NumTailCalls;
2833   }
2834 
2835   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2836   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2837   SmallVector<SDValue, 8> MemOpChains;
2838 
2839   // Analyze operands of the call, assigning locations to each operand.
2840   SmallVector<CCValAssign, 16> ArgLocs;
2841   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2842   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2843 
2844   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2845     // With a fixed ABI, allocate fixed registers before user arguments.
2846     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2847   }
2848 
2849   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2850 
2851   // Get a count of how many bytes are to be pushed on the stack.
2852   unsigned NumBytes = CCInfo.getNextStackOffset();
2853 
2854   if (IsSibCall) {
2855     // Since we're not changing the ABI to make this a tail call, the memory
2856     // operands are already available in the caller's incoming argument space.
2857     NumBytes = 0;
2858   }
2859 
2860   // FPDiff is the byte offset of the call's argument area from the callee's.
2861   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2862   // by this amount for a tail call. In a sibling call it must be 0 because the
2863   // caller will deallocate the entire stack and the callee still expects its
2864   // arguments to begin at SP+0. Completely unused for non-tail calls.
2865   int32_t FPDiff = 0;
2866   MachineFrameInfo &MFI = MF.getFrameInfo();
2867 
2868   // Adjust the stack pointer for the new arguments...
2869   // These operations are automatically eliminated by the prolog/epilog pass
2870   if (!IsSibCall) {
2871     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2872 
2873     SmallVector<SDValue, 4> CopyFromChains;
2874 
2875     // In the HSA case, this should be an identity copy.
2876     SDValue ScratchRSrcReg
2877       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2878     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2879     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2880     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2881   }
2882 
2883   MVT PtrVT = MVT::i32;
2884 
2885   // Walk the register/memloc assignments, inserting copies/loads.
2886   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2887     CCValAssign &VA = ArgLocs[i];
2888     SDValue Arg = OutVals[i];
2889 
2890     // Promote the value if needed.
2891     switch (VA.getLocInfo()) {
2892     case CCValAssign::Full:
2893       break;
2894     case CCValAssign::BCvt:
2895       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2896       break;
2897     case CCValAssign::ZExt:
2898       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2899       break;
2900     case CCValAssign::SExt:
2901       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2902       break;
2903     case CCValAssign::AExt:
2904       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2905       break;
2906     case CCValAssign::FPExt:
2907       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2908       break;
2909     default:
2910       llvm_unreachable("Unknown loc info!");
2911     }
2912 
2913     if (VA.isRegLoc()) {
2914       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2915     } else {
2916       assert(VA.isMemLoc());
2917 
2918       SDValue DstAddr;
2919       MachinePointerInfo DstInfo;
2920 
2921       unsigned LocMemOffset = VA.getLocMemOffset();
2922       int32_t Offset = LocMemOffset;
2923 
2924       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2925       MaybeAlign Alignment;
2926 
2927       if (IsTailCall) {
2928         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2929         unsigned OpSize = Flags.isByVal() ?
2930           Flags.getByValSize() : VA.getValVT().getStoreSize();
2931 
2932         // FIXME: We can have better than the minimum byval required alignment.
2933         Alignment =
2934             Flags.isByVal()
2935                 ? Flags.getNonZeroByValAlign()
2936                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2937 
2938         Offset = Offset + FPDiff;
2939         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2940 
2941         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2942         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2943 
2944         // Make sure any stack arguments overlapping with where we're storing
2945         // are loaded before this eventual operation. Otherwise they'll be
2946         // clobbered.
2947 
2948         // FIXME: Why is this really necessary? This seems to just result in a
2949         // lot of code to copy the stack and write them back to the same
2950         // locations, which are supposed to be immutable?
2951         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2952       } else {
2953         DstAddr = PtrOff;
2954         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2955         Alignment =
2956             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2957       }
2958 
2959       if (Outs[i].Flags.isByVal()) {
2960         SDValue SizeNode =
2961             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2962         SDValue Cpy =
2963             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2964                           Outs[i].Flags.getNonZeroByValAlign(),
2965                           /*isVol = */ false, /*AlwaysInline = */ true,
2966                           /*isTailCall = */ false, DstInfo,
2967                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2968 
2969         MemOpChains.push_back(Cpy);
2970       } else {
2971         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2972                                      Alignment ? Alignment->value() : 0);
2973         MemOpChains.push_back(Store);
2974       }
2975     }
2976   }
2977 
2978   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2979     // Copy special input registers after user input arguments.
2980     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2981   }
2982 
2983   if (!MemOpChains.empty())
2984     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2985 
2986   // Build a sequence of copy-to-reg nodes chained together with token chain
2987   // and flag operands which copy the outgoing args into the appropriate regs.
2988   SDValue InFlag;
2989   for (auto &RegToPass : RegsToPass) {
2990     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2991                              RegToPass.second, InFlag);
2992     InFlag = Chain.getValue(1);
2993   }
2994 
2995 
2996   SDValue PhysReturnAddrReg;
2997   if (IsTailCall) {
2998     // Since the return is being combined with the call, we need to pass on the
2999     // return address.
3000 
3001     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3002     SDValue ReturnAddrReg = CreateLiveInRegister(
3003       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3004 
3005     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3006                                         MVT::i64);
3007     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3008     InFlag = Chain.getValue(1);
3009   }
3010 
3011   // We don't usually want to end the call-sequence here because we would tidy
3012   // the frame up *after* the call, however in the ABI-changing tail-call case
3013   // we've carefully laid out the parameters so that when sp is reset they'll be
3014   // in the correct location.
3015   if (IsTailCall && !IsSibCall) {
3016     Chain = DAG.getCALLSEQ_END(Chain,
3017                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3018                                DAG.getTargetConstant(0, DL, MVT::i32),
3019                                InFlag, DL);
3020     InFlag = Chain.getValue(1);
3021   }
3022 
3023   std::vector<SDValue> Ops;
3024   Ops.push_back(Chain);
3025   Ops.push_back(Callee);
3026   // Add a redundant copy of the callee global which will not be legalized, as
3027   // we need direct access to the callee later.
3028   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3029     const GlobalValue *GV = GSD->getGlobal();
3030     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3031   } else {
3032     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3033   }
3034 
3035   if (IsTailCall) {
3036     // Each tail call may have to adjust the stack by a different amount, so
3037     // this information must travel along with the operation for eventual
3038     // consumption by emitEpilogue.
3039     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3040 
3041     Ops.push_back(PhysReturnAddrReg);
3042   }
3043 
3044   // Add argument registers to the end of the list so that they are known live
3045   // into the call.
3046   for (auto &RegToPass : RegsToPass) {
3047     Ops.push_back(DAG.getRegister(RegToPass.first,
3048                                   RegToPass.second.getValueType()));
3049   }
3050 
3051   // Add a register mask operand representing the call-preserved registers.
3052 
3053   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3054   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3055   assert(Mask && "Missing call preserved mask for calling convention");
3056   Ops.push_back(DAG.getRegisterMask(Mask));
3057 
3058   if (InFlag.getNode())
3059     Ops.push_back(InFlag);
3060 
3061   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3062 
3063   // If we're doing a tall call, use a TC_RETURN here rather than an
3064   // actual call instruction.
3065   if (IsTailCall) {
3066     MFI.setHasTailCall();
3067     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3068   }
3069 
3070   // Returns a chain and a flag for retval copy to use.
3071   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3072   Chain = Call.getValue(0);
3073   InFlag = Call.getValue(1);
3074 
3075   uint64_t CalleePopBytes = NumBytes;
3076   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3077                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3078                              InFlag, DL);
3079   if (!Ins.empty())
3080     InFlag = Chain.getValue(1);
3081 
3082   // Handle result values, copying them out of physregs into vregs that we
3083   // return.
3084   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3085                          InVals, IsThisReturn,
3086                          IsThisReturn ? OutVals[0] : SDValue());
3087 }
3088 
3089 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3090                                              const MachineFunction &MF) const {
3091   Register Reg = StringSwitch<Register>(RegName)
3092     .Case("m0", AMDGPU::M0)
3093     .Case("exec", AMDGPU::EXEC)
3094     .Case("exec_lo", AMDGPU::EXEC_LO)
3095     .Case("exec_hi", AMDGPU::EXEC_HI)
3096     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3097     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3098     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3099     .Default(Register());
3100 
3101   if (Reg == AMDGPU::NoRegister) {
3102     report_fatal_error(Twine("invalid register name \""
3103                              + StringRef(RegName)  + "\"."));
3104 
3105   }
3106 
3107   if (!Subtarget->hasFlatScrRegister() &&
3108        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3109     report_fatal_error(Twine("invalid register \""
3110                              + StringRef(RegName)  + "\" for subtarget."));
3111   }
3112 
3113   switch (Reg) {
3114   case AMDGPU::M0:
3115   case AMDGPU::EXEC_LO:
3116   case AMDGPU::EXEC_HI:
3117   case AMDGPU::FLAT_SCR_LO:
3118   case AMDGPU::FLAT_SCR_HI:
3119     if (VT.getSizeInBits() == 32)
3120       return Reg;
3121     break;
3122   case AMDGPU::EXEC:
3123   case AMDGPU::FLAT_SCR:
3124     if (VT.getSizeInBits() == 64)
3125       return Reg;
3126     break;
3127   default:
3128     llvm_unreachable("missing register type checking");
3129   }
3130 
3131   report_fatal_error(Twine("invalid type for register \""
3132                            + StringRef(RegName) + "\"."));
3133 }
3134 
3135 // If kill is not the last instruction, split the block so kill is always a
3136 // proper terminator.
3137 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3138                                                     MachineBasicBlock *BB) const {
3139   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3140 
3141   MachineBasicBlock::iterator SplitPoint(&MI);
3142   ++SplitPoint;
3143 
3144   if (SplitPoint == BB->end()) {
3145     // Don't bother with a new block.
3146     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3147     return BB;
3148   }
3149 
3150   MachineFunction *MF = BB->getParent();
3151   MachineBasicBlock *SplitBB
3152     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3153 
3154   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3155   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3156 
3157   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3158   BB->addSuccessor(SplitBB);
3159 
3160   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3161   return SplitBB;
3162 }
3163 
3164 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3165 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3166 // be the first instruction in the remainder block.
3167 //
3168 /// \returns { LoopBody, Remainder }
3169 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3170 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3171   MachineFunction *MF = MBB.getParent();
3172   MachineBasicBlock::iterator I(&MI);
3173 
3174   // To insert the loop we need to split the block. Move everything after this
3175   // point to a new block, and insert a new empty block between the two.
3176   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3177   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3178   MachineFunction::iterator MBBI(MBB);
3179   ++MBBI;
3180 
3181   MF->insert(MBBI, LoopBB);
3182   MF->insert(MBBI, RemainderBB);
3183 
3184   LoopBB->addSuccessor(LoopBB);
3185   LoopBB->addSuccessor(RemainderBB);
3186 
3187   // Move the rest of the block into a new block.
3188   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3189 
3190   if (InstInLoop) {
3191     auto Next = std::next(I);
3192 
3193     // Move instruction to loop body.
3194     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3195 
3196     // Move the rest of the block.
3197     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3198   } else {
3199     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3200   }
3201 
3202   MBB.addSuccessor(LoopBB);
3203 
3204   return std::make_pair(LoopBB, RemainderBB);
3205 }
3206 
3207 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3208 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3209   MachineBasicBlock *MBB = MI.getParent();
3210   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3211   auto I = MI.getIterator();
3212   auto E = std::next(I);
3213 
3214   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3215     .addImm(0);
3216 
3217   MIBundleBuilder Bundler(*MBB, I, E);
3218   finalizeBundle(*MBB, Bundler.begin());
3219 }
3220 
3221 MachineBasicBlock *
3222 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3223                                          MachineBasicBlock *BB) const {
3224   const DebugLoc &DL = MI.getDebugLoc();
3225 
3226   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3227 
3228   MachineBasicBlock *LoopBB;
3229   MachineBasicBlock *RemainderBB;
3230   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3231 
3232   // Apparently kill flags are only valid if the def is in the same block?
3233   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3234     Src->setIsKill(false);
3235 
3236   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3237 
3238   MachineBasicBlock::iterator I = LoopBB->end();
3239 
3240   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3241     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3242 
3243   // Clear TRAP_STS.MEM_VIOL
3244   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3245     .addImm(0)
3246     .addImm(EncodedReg);
3247 
3248   bundleInstWithWaitcnt(MI);
3249 
3250   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3251 
3252   // Load and check TRAP_STS.MEM_VIOL
3253   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3254     .addImm(EncodedReg);
3255 
3256   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3257   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3258     .addReg(Reg, RegState::Kill)
3259     .addImm(0);
3260   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3261     .addMBB(LoopBB);
3262 
3263   return RemainderBB;
3264 }
3265 
3266 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3267 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3268 // will only do one iteration. In the worst case, this will loop 64 times.
3269 //
3270 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3271 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3272   const SIInstrInfo *TII,
3273   MachineRegisterInfo &MRI,
3274   MachineBasicBlock &OrigBB,
3275   MachineBasicBlock &LoopBB,
3276   const DebugLoc &DL,
3277   const MachineOperand &IdxReg,
3278   unsigned InitReg,
3279   unsigned ResultReg,
3280   unsigned PhiReg,
3281   unsigned InitSaveExecReg,
3282   int Offset,
3283   bool UseGPRIdxMode,
3284   bool IsIndirectSrc) {
3285   MachineFunction *MF = OrigBB.getParent();
3286   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3287   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3288   MachineBasicBlock::iterator I = LoopBB.begin();
3289 
3290   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3291   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3292   Register NewExec = MRI.createVirtualRegister(BoolRC);
3293   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3294   Register CondReg = MRI.createVirtualRegister(BoolRC);
3295 
3296   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3297     .addReg(InitReg)
3298     .addMBB(&OrigBB)
3299     .addReg(ResultReg)
3300     .addMBB(&LoopBB);
3301 
3302   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3303     .addReg(InitSaveExecReg)
3304     .addMBB(&OrigBB)
3305     .addReg(NewExec)
3306     .addMBB(&LoopBB);
3307 
3308   // Read the next variant <- also loop target.
3309   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3310     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3311 
3312   // Compare the just read M0 value to all possible Idx values.
3313   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3314     .addReg(CurrentIdxReg)
3315     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3316 
3317   // Update EXEC, save the original EXEC value to VCC.
3318   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3319                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3320           NewExec)
3321     .addReg(CondReg, RegState::Kill);
3322 
3323   MRI.setSimpleHint(NewExec, CondReg);
3324 
3325   if (UseGPRIdxMode) {
3326     unsigned IdxReg;
3327     if (Offset == 0) {
3328       IdxReg = CurrentIdxReg;
3329     } else {
3330       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3331       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3332         .addReg(CurrentIdxReg, RegState::Kill)
3333         .addImm(Offset);
3334     }
3335     unsigned IdxMode = IsIndirectSrc ?
3336       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3337     MachineInstr *SetOn =
3338       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3339       .addReg(IdxReg, RegState::Kill)
3340       .addImm(IdxMode);
3341     SetOn->getOperand(3).setIsUndef();
3342   } else {
3343     // Move index from VCC into M0
3344     if (Offset == 0) {
3345       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3346         .addReg(CurrentIdxReg, RegState::Kill);
3347     } else {
3348       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3349         .addReg(CurrentIdxReg, RegState::Kill)
3350         .addImm(Offset);
3351     }
3352   }
3353 
3354   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3355   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3356   MachineInstr *InsertPt =
3357     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3358                                                   : AMDGPU::S_XOR_B64_term), Exec)
3359       .addReg(Exec)
3360       .addReg(NewExec);
3361 
3362   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3363   // s_cbranch_scc0?
3364 
3365   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3366   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3367     .addMBB(&LoopBB);
3368 
3369   return InsertPt->getIterator();
3370 }
3371 
3372 // This has slightly sub-optimal regalloc when the source vector is killed by
3373 // the read. The register allocator does not understand that the kill is
3374 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3375 // subregister from it, using 1 more VGPR than necessary. This was saved when
3376 // this was expanded after register allocation.
3377 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3378                                                   MachineBasicBlock &MBB,
3379                                                   MachineInstr &MI,
3380                                                   unsigned InitResultReg,
3381                                                   unsigned PhiReg,
3382                                                   int Offset,
3383                                                   bool UseGPRIdxMode,
3384                                                   bool IsIndirectSrc) {
3385   MachineFunction *MF = MBB.getParent();
3386   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3387   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3388   MachineRegisterInfo &MRI = MF->getRegInfo();
3389   const DebugLoc &DL = MI.getDebugLoc();
3390   MachineBasicBlock::iterator I(&MI);
3391 
3392   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3393   Register DstReg = MI.getOperand(0).getReg();
3394   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3395   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3396   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3397   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3398 
3399   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3400 
3401   // Save the EXEC mask
3402   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3403     .addReg(Exec);
3404 
3405   MachineBasicBlock *LoopBB;
3406   MachineBasicBlock *RemainderBB;
3407   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3408 
3409   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3410 
3411   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3412                                       InitResultReg, DstReg, PhiReg, TmpExec,
3413                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3414   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3415   MachineFunction::iterator MBBI(LoopBB);
3416   ++MBBI;
3417   MF->insert(MBBI, LandingPad);
3418   LoopBB->removeSuccessor(RemainderBB);
3419   LandingPad->addSuccessor(RemainderBB);
3420   LoopBB->addSuccessor(LandingPad);
3421   MachineBasicBlock::iterator First = LandingPad->begin();
3422   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3423     .addReg(SaveExec);
3424 
3425   return InsPt;
3426 }
3427 
3428 // Returns subreg index, offset
3429 static std::pair<unsigned, int>
3430 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3431                             const TargetRegisterClass *SuperRC,
3432                             unsigned VecReg,
3433                             int Offset) {
3434   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3435 
3436   // Skip out of bounds offsets, or else we would end up using an undefined
3437   // register.
3438   if (Offset >= NumElts || Offset < 0)
3439     return std::make_pair(AMDGPU::sub0, Offset);
3440 
3441   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3442 }
3443 
3444 // Return true if the index is an SGPR and was set.
3445 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3446                                  MachineRegisterInfo &MRI,
3447                                  MachineInstr &MI,
3448                                  int Offset,
3449                                  bool UseGPRIdxMode,
3450                                  bool IsIndirectSrc) {
3451   MachineBasicBlock *MBB = MI.getParent();
3452   const DebugLoc &DL = MI.getDebugLoc();
3453   MachineBasicBlock::iterator I(&MI);
3454 
3455   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3456   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3457 
3458   assert(Idx->getReg() != AMDGPU::NoRegister);
3459 
3460   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3461     return false;
3462 
3463   if (UseGPRIdxMode) {
3464     unsigned IdxMode = IsIndirectSrc ?
3465       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3466     if (Offset == 0) {
3467       MachineInstr *SetOn =
3468           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3469               .add(*Idx)
3470               .addImm(IdxMode);
3471 
3472       SetOn->getOperand(3).setIsUndef();
3473     } else {
3474       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3475       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3476           .add(*Idx)
3477           .addImm(Offset);
3478       MachineInstr *SetOn =
3479         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3480         .addReg(Tmp, RegState::Kill)
3481         .addImm(IdxMode);
3482 
3483       SetOn->getOperand(3).setIsUndef();
3484     }
3485 
3486     return true;
3487   }
3488 
3489   if (Offset == 0) {
3490     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3491       .add(*Idx);
3492   } else {
3493     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3494       .add(*Idx)
3495       .addImm(Offset);
3496   }
3497 
3498   return true;
3499 }
3500 
3501 // Control flow needs to be inserted if indexing with a VGPR.
3502 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3503                                           MachineBasicBlock &MBB,
3504                                           const GCNSubtarget &ST) {
3505   const SIInstrInfo *TII = ST.getInstrInfo();
3506   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3507   MachineFunction *MF = MBB.getParent();
3508   MachineRegisterInfo &MRI = MF->getRegInfo();
3509 
3510   Register Dst = MI.getOperand(0).getReg();
3511   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3512   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3513 
3514   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3515 
3516   unsigned SubReg;
3517   std::tie(SubReg, Offset)
3518     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3519 
3520   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3521 
3522   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3523     MachineBasicBlock::iterator I(&MI);
3524     const DebugLoc &DL = MI.getDebugLoc();
3525 
3526     if (UseGPRIdxMode) {
3527       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3528       // to avoid interfering with other uses, so probably requires a new
3529       // optimization pass.
3530       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3531         .addReg(SrcReg, RegState::Undef, SubReg)
3532         .addReg(SrcReg, RegState::Implicit)
3533         .addReg(AMDGPU::M0, RegState::Implicit);
3534       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3535     } else {
3536       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3537         .addReg(SrcReg, RegState::Undef, SubReg)
3538         .addReg(SrcReg, RegState::Implicit);
3539     }
3540 
3541     MI.eraseFromParent();
3542 
3543     return &MBB;
3544   }
3545 
3546   const DebugLoc &DL = MI.getDebugLoc();
3547   MachineBasicBlock::iterator I(&MI);
3548 
3549   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3550   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3551 
3552   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3553 
3554   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3555                               Offset, UseGPRIdxMode, true);
3556   MachineBasicBlock *LoopBB = InsPt->getParent();
3557 
3558   if (UseGPRIdxMode) {
3559     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3560       .addReg(SrcReg, RegState::Undef, SubReg)
3561       .addReg(SrcReg, RegState::Implicit)
3562       .addReg(AMDGPU::M0, RegState::Implicit);
3563     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3564   } else {
3565     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3566       .addReg(SrcReg, RegState::Undef, SubReg)
3567       .addReg(SrcReg, RegState::Implicit);
3568   }
3569 
3570   MI.eraseFromParent();
3571 
3572   return LoopBB;
3573 }
3574 
3575 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3576                                           MachineBasicBlock &MBB,
3577                                           const GCNSubtarget &ST) {
3578   const SIInstrInfo *TII = ST.getInstrInfo();
3579   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3580   MachineFunction *MF = MBB.getParent();
3581   MachineRegisterInfo &MRI = MF->getRegInfo();
3582 
3583   Register Dst = MI.getOperand(0).getReg();
3584   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3585   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3586   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3587   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3588   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3589 
3590   // This can be an immediate, but will be folded later.
3591   assert(Val->getReg());
3592 
3593   unsigned SubReg;
3594   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3595                                                          SrcVec->getReg(),
3596                                                          Offset);
3597   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3598 
3599   if (Idx->getReg() == AMDGPU::NoRegister) {
3600     MachineBasicBlock::iterator I(&MI);
3601     const DebugLoc &DL = MI.getDebugLoc();
3602 
3603     assert(Offset == 0);
3604 
3605     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3606         .add(*SrcVec)
3607         .add(*Val)
3608         .addImm(SubReg);
3609 
3610     MI.eraseFromParent();
3611     return &MBB;
3612   }
3613 
3614   const MCInstrDesc &MovRelDesc
3615     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3616 
3617   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3618     MachineBasicBlock::iterator I(&MI);
3619     const DebugLoc &DL = MI.getDebugLoc();
3620     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3621       .addReg(SrcVec->getReg())
3622       .add(*Val)
3623       .addImm(SubReg);
3624     if (UseGPRIdxMode)
3625       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3626 
3627     MI.eraseFromParent();
3628     return &MBB;
3629   }
3630 
3631   if (Val->isReg())
3632     MRI.clearKillFlags(Val->getReg());
3633 
3634   const DebugLoc &DL = MI.getDebugLoc();
3635 
3636   Register PhiReg = MRI.createVirtualRegister(VecRC);
3637 
3638   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3639                               Offset, UseGPRIdxMode, false);
3640   MachineBasicBlock *LoopBB = InsPt->getParent();
3641 
3642   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3643     .addReg(PhiReg)
3644     .add(*Val)
3645     .addImm(AMDGPU::sub0);
3646   if (UseGPRIdxMode)
3647     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3648 
3649   MI.eraseFromParent();
3650   return LoopBB;
3651 }
3652 
3653 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3654   MachineInstr &MI, MachineBasicBlock *BB) const {
3655 
3656   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3657   MachineFunction *MF = BB->getParent();
3658   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3659 
3660   if (TII->isMIMG(MI)) {
3661     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3662       report_fatal_error("missing mem operand from MIMG instruction");
3663     }
3664     // Add a memoperand for mimg instructions so that they aren't assumed to
3665     // be ordered memory instuctions.
3666 
3667     return BB;
3668   }
3669 
3670   switch (MI.getOpcode()) {
3671   case AMDGPU::S_UADDO_PSEUDO:
3672   case AMDGPU::S_USUBO_PSEUDO: {
3673     const DebugLoc &DL = MI.getDebugLoc();
3674     MachineOperand &Dest0 = MI.getOperand(0);
3675     MachineOperand &Dest1 = MI.getOperand(1);
3676     MachineOperand &Src0 = MI.getOperand(2);
3677     MachineOperand &Src1 = MI.getOperand(3);
3678 
3679     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3680                        ? AMDGPU::S_ADD_I32
3681                        : AMDGPU::S_SUB_I32;
3682     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3683 
3684     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3685         .addImm(1)
3686         .addImm(0);
3687 
3688     MI.eraseFromParent();
3689     return BB;
3690   }
3691   case AMDGPU::S_ADD_U64_PSEUDO:
3692   case AMDGPU::S_SUB_U64_PSEUDO: {
3693     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3694     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3695     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3696     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3697     const DebugLoc &DL = MI.getDebugLoc();
3698 
3699     MachineOperand &Dest = MI.getOperand(0);
3700     MachineOperand &Src0 = MI.getOperand(1);
3701     MachineOperand &Src1 = MI.getOperand(2);
3702 
3703     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3704     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3705 
3706     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3707         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3708     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3709         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3710 
3711     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3712         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3713     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3714         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3715 
3716     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3717 
3718     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3719     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3720     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3721     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3722     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3723         .addReg(DestSub0)
3724         .addImm(AMDGPU::sub0)
3725         .addReg(DestSub1)
3726         .addImm(AMDGPU::sub1);
3727     MI.eraseFromParent();
3728     return BB;
3729   }
3730   case AMDGPU::V_ADD_U64_PSEUDO:
3731   case AMDGPU::V_SUB_U64_PSEUDO: {
3732     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3733     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3734     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3735     const DebugLoc &DL = MI.getDebugLoc();
3736 
3737     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3738 
3739     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3740 
3741     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3742     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3743 
3744     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3745     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3746 
3747     MachineOperand &Dest = MI.getOperand(0);
3748     MachineOperand &Src0 = MI.getOperand(1);
3749     MachineOperand &Src1 = MI.getOperand(2);
3750 
3751     const TargetRegisterClass *Src0RC = Src0.isReg()
3752                                             ? MRI.getRegClass(Src0.getReg())
3753                                             : &AMDGPU::VReg_64RegClass;
3754     const TargetRegisterClass *Src1RC = Src1.isReg()
3755                                             ? MRI.getRegClass(Src1.getReg())
3756                                             : &AMDGPU::VReg_64RegClass;
3757 
3758     const TargetRegisterClass *Src0SubRC =
3759         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3760     const TargetRegisterClass *Src1SubRC =
3761         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3762 
3763     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3764         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3765     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3766         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3767 
3768     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3769         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3770     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3771         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3772 
3773     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
3774     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3775                                .addReg(CarryReg, RegState::Define)
3776                                .add(SrcReg0Sub0)
3777                                .add(SrcReg1Sub0)
3778                                .addImm(0); // clamp bit
3779 
3780     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3781     MachineInstr *HiHalf =
3782         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3783             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3784             .add(SrcReg0Sub1)
3785             .add(SrcReg1Sub1)
3786             .addReg(CarryReg, RegState::Kill)
3787             .addImm(0); // clamp bit
3788 
3789     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3790         .addReg(DestSub0)
3791         .addImm(AMDGPU::sub0)
3792         .addReg(DestSub1)
3793         .addImm(AMDGPU::sub1);
3794     TII->legalizeOperands(*LoHalf);
3795     TII->legalizeOperands(*HiHalf);
3796     MI.eraseFromParent();
3797     return BB;
3798   }
3799   case AMDGPU::S_ADD_CO_PSEUDO:
3800   case AMDGPU::S_SUB_CO_PSEUDO: {
3801     // This pseudo has a chance to be selected
3802     // only from uniform add/subcarry node. All the VGPR operands
3803     // therefore assumed to be splat vectors.
3804     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3805     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3806     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3807     MachineBasicBlock::iterator MII = MI;
3808     const DebugLoc &DL = MI.getDebugLoc();
3809     MachineOperand &Dest = MI.getOperand(0);
3810     MachineOperand &Src0 = MI.getOperand(2);
3811     MachineOperand &Src1 = MI.getOperand(3);
3812     MachineOperand &Src2 = MI.getOperand(4);
3813     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3814                        ? AMDGPU::S_ADDC_U32
3815                        : AMDGPU::S_SUBB_U32;
3816     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3817       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3818       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3819           .addReg(Src0.getReg());
3820       Src0.setReg(RegOp0);
3821     }
3822     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3823       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3824       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3825           .addReg(Src1.getReg());
3826       Src1.setReg(RegOp1);
3827     }
3828     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3829     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3830       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3831           .addReg(Src2.getReg());
3832       Src2.setReg(RegOp2);
3833     }
3834 
3835     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3836       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3837           .addReg(Src2.getReg())
3838           .addImm(0);
3839     } else {
3840       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3841           .addReg(Src2.getReg())
3842           .addImm(0);
3843     }
3844 
3845     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3846     MI.eraseFromParent();
3847     return BB;
3848   }
3849   case AMDGPU::SI_INIT_M0: {
3850     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3851             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3852         .add(MI.getOperand(0));
3853     MI.eraseFromParent();
3854     return BB;
3855   }
3856   case AMDGPU::SI_INIT_EXEC:
3857     // This should be before all vector instructions.
3858     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3859             AMDGPU::EXEC)
3860         .addImm(MI.getOperand(0).getImm());
3861     MI.eraseFromParent();
3862     return BB;
3863 
3864   case AMDGPU::SI_INIT_EXEC_LO:
3865     // This should be before all vector instructions.
3866     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3867             AMDGPU::EXEC_LO)
3868         .addImm(MI.getOperand(0).getImm());
3869     MI.eraseFromParent();
3870     return BB;
3871 
3872   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3873     // Extract the thread count from an SGPR input and set EXEC accordingly.
3874     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3875     //
3876     // S_BFE_U32 count, input, {shift, 7}
3877     // S_BFM_B64 exec, count, 0
3878     // S_CMP_EQ_U32 count, 64
3879     // S_CMOV_B64 exec, -1
3880     MachineInstr *FirstMI = &*BB->begin();
3881     MachineRegisterInfo &MRI = MF->getRegInfo();
3882     Register InputReg = MI.getOperand(0).getReg();
3883     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3884     bool Found = false;
3885 
3886     // Move the COPY of the input reg to the beginning, so that we can use it.
3887     for (auto I = BB->begin(); I != &MI; I++) {
3888       if (I->getOpcode() != TargetOpcode::COPY ||
3889           I->getOperand(0).getReg() != InputReg)
3890         continue;
3891 
3892       if (I == FirstMI) {
3893         FirstMI = &*++BB->begin();
3894       } else {
3895         I->removeFromParent();
3896         BB->insert(FirstMI, &*I);
3897       }
3898       Found = true;
3899       break;
3900     }
3901     assert(Found);
3902     (void)Found;
3903 
3904     // This should be before all vector instructions.
3905     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3906     bool isWave32 = getSubtarget()->isWave32();
3907     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3908     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3909         .addReg(InputReg)
3910         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3911     BuildMI(*BB, FirstMI, DebugLoc(),
3912             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3913             Exec)
3914         .addReg(CountReg)
3915         .addImm(0);
3916     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3917         .addReg(CountReg, RegState::Kill)
3918         .addImm(getSubtarget()->getWavefrontSize());
3919     BuildMI(*BB, FirstMI, DebugLoc(),
3920             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3921             Exec)
3922         .addImm(-1);
3923     MI.eraseFromParent();
3924     return BB;
3925   }
3926 
3927   case AMDGPU::GET_GROUPSTATICSIZE: {
3928     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3929            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3930     DebugLoc DL = MI.getDebugLoc();
3931     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3932         .add(MI.getOperand(0))
3933         .addImm(MFI->getLDSSize());
3934     MI.eraseFromParent();
3935     return BB;
3936   }
3937   case AMDGPU::SI_INDIRECT_SRC_V1:
3938   case AMDGPU::SI_INDIRECT_SRC_V2:
3939   case AMDGPU::SI_INDIRECT_SRC_V4:
3940   case AMDGPU::SI_INDIRECT_SRC_V8:
3941   case AMDGPU::SI_INDIRECT_SRC_V16:
3942   case AMDGPU::SI_INDIRECT_SRC_V32:
3943     return emitIndirectSrc(MI, *BB, *getSubtarget());
3944   case AMDGPU::SI_INDIRECT_DST_V1:
3945   case AMDGPU::SI_INDIRECT_DST_V2:
3946   case AMDGPU::SI_INDIRECT_DST_V4:
3947   case AMDGPU::SI_INDIRECT_DST_V8:
3948   case AMDGPU::SI_INDIRECT_DST_V16:
3949   case AMDGPU::SI_INDIRECT_DST_V32:
3950     return emitIndirectDst(MI, *BB, *getSubtarget());
3951   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3952   case AMDGPU::SI_KILL_I1_PSEUDO:
3953     return splitKillBlock(MI, BB);
3954   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3955     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3956     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3957     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3958 
3959     Register Dst = MI.getOperand(0).getReg();
3960     Register Src0 = MI.getOperand(1).getReg();
3961     Register Src1 = MI.getOperand(2).getReg();
3962     const DebugLoc &DL = MI.getDebugLoc();
3963     Register SrcCond = MI.getOperand(3).getReg();
3964 
3965     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3966     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3967     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3968     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3969 
3970     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3971       .addReg(SrcCond);
3972     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3973       .addImm(0)
3974       .addReg(Src0, 0, AMDGPU::sub0)
3975       .addImm(0)
3976       .addReg(Src1, 0, AMDGPU::sub0)
3977       .addReg(SrcCondCopy);
3978     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3979       .addImm(0)
3980       .addReg(Src0, 0, AMDGPU::sub1)
3981       .addImm(0)
3982       .addReg(Src1, 0, AMDGPU::sub1)
3983       .addReg(SrcCondCopy);
3984 
3985     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3986       .addReg(DstLo)
3987       .addImm(AMDGPU::sub0)
3988       .addReg(DstHi)
3989       .addImm(AMDGPU::sub1);
3990     MI.eraseFromParent();
3991     return BB;
3992   }
3993   case AMDGPU::SI_BR_UNDEF: {
3994     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3995     const DebugLoc &DL = MI.getDebugLoc();
3996     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3997                            .add(MI.getOperand(0));
3998     Br->getOperand(1).setIsUndef(true); // read undef SCC
3999     MI.eraseFromParent();
4000     return BB;
4001   }
4002   case AMDGPU::ADJCALLSTACKUP:
4003   case AMDGPU::ADJCALLSTACKDOWN: {
4004     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4005     MachineInstrBuilder MIB(*MF, &MI);
4006 
4007     // Add an implicit use of the frame offset reg to prevent the restore copy
4008     // inserted after the call from being reorderd after stack operations in the
4009     // the caller's frame.
4010     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4011         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4012         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4013     return BB;
4014   }
4015   case AMDGPU::SI_CALL_ISEL: {
4016     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4017     const DebugLoc &DL = MI.getDebugLoc();
4018 
4019     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4020 
4021     MachineInstrBuilder MIB;
4022     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4023 
4024     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4025       MIB.add(MI.getOperand(I));
4026 
4027     MIB.cloneMemRefs(MI);
4028     MI.eraseFromParent();
4029     return BB;
4030   }
4031   case AMDGPU::V_ADD_I32_e32:
4032   case AMDGPU::V_SUB_I32_e32:
4033   case AMDGPU::V_SUBREV_I32_e32: {
4034     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4035     const DebugLoc &DL = MI.getDebugLoc();
4036     unsigned Opc = MI.getOpcode();
4037 
4038     bool NeedClampOperand = false;
4039     if (TII->pseudoToMCOpcode(Opc) == -1) {
4040       Opc = AMDGPU::getVOPe64(Opc);
4041       NeedClampOperand = true;
4042     }
4043 
4044     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4045     if (TII->isVOP3(*I)) {
4046       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4047       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4048       I.addReg(TRI->getVCC(), RegState::Define);
4049     }
4050     I.add(MI.getOperand(1))
4051      .add(MI.getOperand(2));
4052     if (NeedClampOperand)
4053       I.addImm(0); // clamp bit for e64 encoding
4054 
4055     TII->legalizeOperands(*I);
4056 
4057     MI.eraseFromParent();
4058     return BB;
4059   }
4060   case AMDGPU::DS_GWS_INIT:
4061   case AMDGPU::DS_GWS_SEMA_V:
4062   case AMDGPU::DS_GWS_SEMA_BR:
4063   case AMDGPU::DS_GWS_SEMA_P:
4064   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4065   case AMDGPU::DS_GWS_BARRIER:
4066     // A s_waitcnt 0 is required to be the instruction immediately following.
4067     if (getSubtarget()->hasGWSAutoReplay()) {
4068       bundleInstWithWaitcnt(MI);
4069       return BB;
4070     }
4071 
4072     return emitGWSMemViolTestLoop(MI, BB);
4073   default:
4074     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4075   }
4076 }
4077 
4078 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4079   return isTypeLegal(VT.getScalarType());
4080 }
4081 
4082 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4083   // This currently forces unfolding various combinations of fsub into fma with
4084   // free fneg'd operands. As long as we have fast FMA (controlled by
4085   // isFMAFasterThanFMulAndFAdd), we should perform these.
4086 
4087   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4088   // most of these combines appear to be cycle neutral but save on instruction
4089   // count / code size.
4090   return true;
4091 }
4092 
4093 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4094                                          EVT VT) const {
4095   if (!VT.isVector()) {
4096     return MVT::i1;
4097   }
4098   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4099 }
4100 
4101 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4102   // TODO: Should i16 be used always if legal? For now it would force VALU
4103   // shifts.
4104   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4105 }
4106 
4107 // Answering this is somewhat tricky and depends on the specific device which
4108 // have different rates for fma or all f64 operations.
4109 //
4110 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4111 // regardless of which device (although the number of cycles differs between
4112 // devices), so it is always profitable for f64.
4113 //
4114 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4115 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4116 // which we can always do even without fused FP ops since it returns the same
4117 // result as the separate operations and since it is always full
4118 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4119 // however does not support denormals, so we do report fma as faster if we have
4120 // a fast fma device and require denormals.
4121 //
4122 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4123                                                   EVT VT) const {
4124   VT = VT.getScalarType();
4125 
4126   switch (VT.getSimpleVT().SimpleTy) {
4127   case MVT::f32: {
4128     // This is as fast on some subtargets. However, we always have full rate f32
4129     // mad available which returns the same result as the separate operations
4130     // which we should prefer over fma. We can't use this if we want to support
4131     // denormals, so only report this in these cases.
4132     if (hasFP32Denormals(MF))
4133       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4134 
4135     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4136     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4137   }
4138   case MVT::f64:
4139     return true;
4140   case MVT::f16:
4141     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4142   default:
4143     break;
4144   }
4145 
4146   return false;
4147 }
4148 
4149 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4150                                    const SDNode *N) const {
4151   // TODO: Check future ftz flag
4152   // v_mad_f32/v_mac_f32 do not support denormals.
4153   EVT VT = N->getValueType(0);
4154   if (VT == MVT::f32)
4155     return !hasFP32Denormals(DAG.getMachineFunction());
4156   if (VT == MVT::f16) {
4157     return Subtarget->hasMadF16() &&
4158            !hasFP64FP16Denormals(DAG.getMachineFunction());
4159   }
4160 
4161   return false;
4162 }
4163 
4164 //===----------------------------------------------------------------------===//
4165 // Custom DAG Lowering Operations
4166 //===----------------------------------------------------------------------===//
4167 
4168 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4169 // wider vector type is legal.
4170 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4171                                              SelectionDAG &DAG) const {
4172   unsigned Opc = Op.getOpcode();
4173   EVT VT = Op.getValueType();
4174   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4175 
4176   SDValue Lo, Hi;
4177   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4178 
4179   SDLoc SL(Op);
4180   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4181                              Op->getFlags());
4182   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4183                              Op->getFlags());
4184 
4185   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4186 }
4187 
4188 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4189 // wider vector type is legal.
4190 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4191                                               SelectionDAG &DAG) const {
4192   unsigned Opc = Op.getOpcode();
4193   EVT VT = Op.getValueType();
4194   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4195 
4196   SDValue Lo0, Hi0;
4197   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4198   SDValue Lo1, Hi1;
4199   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4200 
4201   SDLoc SL(Op);
4202 
4203   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4204                              Op->getFlags());
4205   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4206                              Op->getFlags());
4207 
4208   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4209 }
4210 
4211 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4212                                               SelectionDAG &DAG) const {
4213   unsigned Opc = Op.getOpcode();
4214   EVT VT = Op.getValueType();
4215   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4216 
4217   SDValue Lo0, Hi0;
4218   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4219   SDValue Lo1, Hi1;
4220   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4221   SDValue Lo2, Hi2;
4222   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4223 
4224   SDLoc SL(Op);
4225 
4226   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4227                              Op->getFlags());
4228   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4229                              Op->getFlags());
4230 
4231   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4232 }
4233 
4234 
4235 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4236   switch (Op.getOpcode()) {
4237   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4238   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4239   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4240   case ISD::LOAD: {
4241     SDValue Result = LowerLOAD(Op, DAG);
4242     assert((!Result.getNode() ||
4243             Result.getNode()->getNumValues() == 2) &&
4244            "Load should return a value and a chain");
4245     return Result;
4246   }
4247 
4248   case ISD::FSIN:
4249   case ISD::FCOS:
4250     return LowerTrig(Op, DAG);
4251   case ISD::SELECT: return LowerSELECT(Op, DAG);
4252   case ISD::FDIV: return LowerFDIV(Op, DAG);
4253   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4254   case ISD::STORE: return LowerSTORE(Op, DAG);
4255   case ISD::GlobalAddress: {
4256     MachineFunction &MF = DAG.getMachineFunction();
4257     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4258     return LowerGlobalAddress(MFI, Op, DAG);
4259   }
4260   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4261   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4262   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4263   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4264   case ISD::INSERT_SUBVECTOR:
4265     return lowerINSERT_SUBVECTOR(Op, DAG);
4266   case ISD::INSERT_VECTOR_ELT:
4267     return lowerINSERT_VECTOR_ELT(Op, DAG);
4268   case ISD::EXTRACT_VECTOR_ELT:
4269     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4270   case ISD::VECTOR_SHUFFLE:
4271     return lowerVECTOR_SHUFFLE(Op, DAG);
4272   case ISD::BUILD_VECTOR:
4273     return lowerBUILD_VECTOR(Op, DAG);
4274   case ISD::FP_ROUND:
4275     return lowerFP_ROUND(Op, DAG);
4276   case ISD::TRAP:
4277     return lowerTRAP(Op, DAG);
4278   case ISD::DEBUGTRAP:
4279     return lowerDEBUGTRAP(Op, DAG);
4280   case ISD::FABS:
4281   case ISD::FNEG:
4282   case ISD::FCANONICALIZE:
4283   case ISD::BSWAP:
4284     return splitUnaryVectorOp(Op, DAG);
4285   case ISD::FMINNUM:
4286   case ISD::FMAXNUM:
4287     return lowerFMINNUM_FMAXNUM(Op, DAG);
4288   case ISD::FMA:
4289     return splitTernaryVectorOp(Op, DAG);
4290   case ISD::SHL:
4291   case ISD::SRA:
4292   case ISD::SRL:
4293   case ISD::ADD:
4294   case ISD::SUB:
4295   case ISD::MUL:
4296   case ISD::SMIN:
4297   case ISD::SMAX:
4298   case ISD::UMIN:
4299   case ISD::UMAX:
4300   case ISD::FADD:
4301   case ISD::FMUL:
4302   case ISD::FMINNUM_IEEE:
4303   case ISD::FMAXNUM_IEEE:
4304     return splitBinaryVectorOp(Op, DAG);
4305   }
4306   return SDValue();
4307 }
4308 
4309 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4310                                        const SDLoc &DL,
4311                                        SelectionDAG &DAG, bool Unpacked) {
4312   if (!LoadVT.isVector())
4313     return Result;
4314 
4315   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4316     // Truncate to v2i16/v4i16.
4317     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4318 
4319     // Workaround legalizer not scalarizing truncate after vector op
4320     // legalization byt not creating intermediate vector trunc.
4321     SmallVector<SDValue, 4> Elts;
4322     DAG.ExtractVectorElements(Result, Elts);
4323     for (SDValue &Elt : Elts)
4324       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4325 
4326     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4327 
4328     // Bitcast to original type (v2f16/v4f16).
4329     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4330   }
4331 
4332   // Cast back to the original packed type.
4333   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4334 }
4335 
4336 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4337                                               MemSDNode *M,
4338                                               SelectionDAG &DAG,
4339                                               ArrayRef<SDValue> Ops,
4340                                               bool IsIntrinsic) const {
4341   SDLoc DL(M);
4342 
4343   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4344   EVT LoadVT = M->getValueType(0);
4345 
4346   EVT EquivLoadVT = LoadVT;
4347   if (Unpacked && LoadVT.isVector()) {
4348     EquivLoadVT = LoadVT.isVector() ?
4349       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4350                        LoadVT.getVectorNumElements()) : LoadVT;
4351   }
4352 
4353   // Change from v4f16/v2f16 to EquivLoadVT.
4354   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4355 
4356   SDValue Load
4357     = DAG.getMemIntrinsicNode(
4358       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4359       VTList, Ops, M->getMemoryVT(),
4360       M->getMemOperand());
4361   if (!Unpacked) // Just adjusted the opcode.
4362     return Load;
4363 
4364   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4365 
4366   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4367 }
4368 
4369 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4370                                              SelectionDAG &DAG,
4371                                              ArrayRef<SDValue> Ops) const {
4372   SDLoc DL(M);
4373   EVT LoadVT = M->getValueType(0);
4374   EVT EltType = LoadVT.getScalarType();
4375   EVT IntVT = LoadVT.changeTypeToInteger();
4376 
4377   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4378 
4379   unsigned Opc =
4380       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4381 
4382   if (IsD16) {
4383     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4384   }
4385 
4386   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4387   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4388     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4389 
4390   if (isTypeLegal(LoadVT)) {
4391     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4392                                M->getMemOperand(), DAG);
4393   }
4394 
4395   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4396   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4397   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4398                                         M->getMemOperand(), DAG);
4399   return DAG.getMergeValues(
4400       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4401       DL);
4402 }
4403 
4404 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4405                                   SDNode *N, SelectionDAG &DAG) {
4406   EVT VT = N->getValueType(0);
4407   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4408   int CondCode = CD->getSExtValue();
4409   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4410       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4411     return DAG.getUNDEF(VT);
4412 
4413   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4414 
4415   SDValue LHS = N->getOperand(1);
4416   SDValue RHS = N->getOperand(2);
4417 
4418   SDLoc DL(N);
4419 
4420   EVT CmpVT = LHS.getValueType();
4421   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4422     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4423       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4424     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4425     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4426   }
4427 
4428   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4429 
4430   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4431   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4432 
4433   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4434                               DAG.getCondCode(CCOpcode));
4435   if (VT.bitsEq(CCVT))
4436     return SetCC;
4437   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4438 }
4439 
4440 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4441                                   SDNode *N, SelectionDAG &DAG) {
4442   EVT VT = N->getValueType(0);
4443   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4444 
4445   int CondCode = CD->getSExtValue();
4446   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4447       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4448     return DAG.getUNDEF(VT);
4449   }
4450 
4451   SDValue Src0 = N->getOperand(1);
4452   SDValue Src1 = N->getOperand(2);
4453   EVT CmpVT = Src0.getValueType();
4454   SDLoc SL(N);
4455 
4456   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4457     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4458     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4459   }
4460 
4461   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4462   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4463   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4464   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4465   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4466                               Src1, DAG.getCondCode(CCOpcode));
4467   if (VT.bitsEq(CCVT))
4468     return SetCC;
4469   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4470 }
4471 
4472 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4473                                     SelectionDAG &DAG) {
4474   EVT VT = N->getValueType(0);
4475   SDValue Src = N->getOperand(1);
4476   SDLoc SL(N);
4477 
4478   if (Src.getOpcode() == ISD::SETCC) {
4479     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4480     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4481                        Src.getOperand(1), Src.getOperand(2));
4482   }
4483   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4484     // (ballot 0) -> 0
4485     if (Arg->isNullValue())
4486       return DAG.getConstant(0, SL, VT);
4487 
4488     // (ballot 1) -> EXEC/EXEC_LO
4489     if (Arg->isOne()) {
4490       Register Exec;
4491       if (VT.getScalarSizeInBits() == 32)
4492         Exec = AMDGPU::EXEC_LO;
4493       else if (VT.getScalarSizeInBits() == 64)
4494         Exec = AMDGPU::EXEC;
4495       else
4496         return SDValue();
4497 
4498       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4499     }
4500   }
4501 
4502   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4503   // ISD::SETNE)
4504   return DAG.getNode(
4505       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4506       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4507 }
4508 
4509 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4510                                           SmallVectorImpl<SDValue> &Results,
4511                                           SelectionDAG &DAG) const {
4512   switch (N->getOpcode()) {
4513   case ISD::INSERT_VECTOR_ELT: {
4514     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4515       Results.push_back(Res);
4516     return;
4517   }
4518   case ISD::EXTRACT_VECTOR_ELT: {
4519     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4520       Results.push_back(Res);
4521     return;
4522   }
4523   case ISD::INTRINSIC_WO_CHAIN: {
4524     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4525     switch (IID) {
4526     case Intrinsic::amdgcn_cvt_pkrtz: {
4527       SDValue Src0 = N->getOperand(1);
4528       SDValue Src1 = N->getOperand(2);
4529       SDLoc SL(N);
4530       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4531                                 Src0, Src1);
4532       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4533       return;
4534     }
4535     case Intrinsic::amdgcn_cvt_pknorm_i16:
4536     case Intrinsic::amdgcn_cvt_pknorm_u16:
4537     case Intrinsic::amdgcn_cvt_pk_i16:
4538     case Intrinsic::amdgcn_cvt_pk_u16: {
4539       SDValue Src0 = N->getOperand(1);
4540       SDValue Src1 = N->getOperand(2);
4541       SDLoc SL(N);
4542       unsigned Opcode;
4543 
4544       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4545         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4546       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4547         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4548       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4549         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4550       else
4551         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4552 
4553       EVT VT = N->getValueType(0);
4554       if (isTypeLegal(VT))
4555         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4556       else {
4557         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4558         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4559       }
4560       return;
4561     }
4562     }
4563     break;
4564   }
4565   case ISD::INTRINSIC_W_CHAIN: {
4566     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4567       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4568         // FIXME: Hacky
4569         Results.push_back(Res.getOperand(0));
4570         Results.push_back(Res.getOperand(1));
4571       } else {
4572         Results.push_back(Res);
4573         Results.push_back(Res.getValue(1));
4574       }
4575       return;
4576     }
4577 
4578     break;
4579   }
4580   case ISD::SELECT: {
4581     SDLoc SL(N);
4582     EVT VT = N->getValueType(0);
4583     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4584     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4585     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4586 
4587     EVT SelectVT = NewVT;
4588     if (NewVT.bitsLT(MVT::i32)) {
4589       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4590       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4591       SelectVT = MVT::i32;
4592     }
4593 
4594     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4595                                     N->getOperand(0), LHS, RHS);
4596 
4597     if (NewVT != SelectVT)
4598       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4599     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4600     return;
4601   }
4602   case ISD::FNEG: {
4603     if (N->getValueType(0) != MVT::v2f16)
4604       break;
4605 
4606     SDLoc SL(N);
4607     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4608 
4609     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4610                              BC,
4611                              DAG.getConstant(0x80008000, SL, MVT::i32));
4612     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4613     return;
4614   }
4615   case ISD::FABS: {
4616     if (N->getValueType(0) != MVT::v2f16)
4617       break;
4618 
4619     SDLoc SL(N);
4620     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4621 
4622     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4623                              BC,
4624                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4625     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4626     return;
4627   }
4628   default:
4629     break;
4630   }
4631 }
4632 
4633 /// Helper function for LowerBRCOND
4634 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4635 
4636   SDNode *Parent = Value.getNode();
4637   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4638        I != E; ++I) {
4639 
4640     if (I.getUse().get() != Value)
4641       continue;
4642 
4643     if (I->getOpcode() == Opcode)
4644       return *I;
4645   }
4646   return nullptr;
4647 }
4648 
4649 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4650   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4651     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4652     case Intrinsic::amdgcn_if:
4653       return AMDGPUISD::IF;
4654     case Intrinsic::amdgcn_else:
4655       return AMDGPUISD::ELSE;
4656     case Intrinsic::amdgcn_loop:
4657       return AMDGPUISD::LOOP;
4658     case Intrinsic::amdgcn_end_cf:
4659       llvm_unreachable("should not occur");
4660     default:
4661       return 0;
4662     }
4663   }
4664 
4665   // break, if_break, else_break are all only used as inputs to loop, not
4666   // directly as branch conditions.
4667   return 0;
4668 }
4669 
4670 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4671   const Triple &TT = getTargetMachine().getTargetTriple();
4672   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4673           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4674          AMDGPU::shouldEmitConstantsToTextSection(TT);
4675 }
4676 
4677 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4678   // FIXME: Either avoid relying on address space here or change the default
4679   // address space for functions to avoid the explicit check.
4680   return (GV->getValueType()->isFunctionTy() ||
4681           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4682          !shouldEmitFixup(GV) &&
4683          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4684 }
4685 
4686 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4687   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4688 }
4689 
4690 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4691   if (!GV->hasExternalLinkage())
4692     return true;
4693 
4694   const auto OS = getTargetMachine().getTargetTriple().getOS();
4695   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4696 }
4697 
4698 /// This transforms the control flow intrinsics to get the branch destination as
4699 /// last parameter, also switches branch target with BR if the need arise
4700 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4701                                       SelectionDAG &DAG) const {
4702   SDLoc DL(BRCOND);
4703 
4704   SDNode *Intr = BRCOND.getOperand(1).getNode();
4705   SDValue Target = BRCOND.getOperand(2);
4706   SDNode *BR = nullptr;
4707   SDNode *SetCC = nullptr;
4708 
4709   if (Intr->getOpcode() == ISD::SETCC) {
4710     // As long as we negate the condition everything is fine
4711     SetCC = Intr;
4712     Intr = SetCC->getOperand(0).getNode();
4713 
4714   } else {
4715     // Get the target from BR if we don't negate the condition
4716     BR = findUser(BRCOND, ISD::BR);
4717     assert(BR && "brcond missing unconditional branch user");
4718     Target = BR->getOperand(1);
4719   }
4720 
4721   unsigned CFNode = isCFIntrinsic(Intr);
4722   if (CFNode == 0) {
4723     // This is a uniform branch so we don't need to legalize.
4724     return BRCOND;
4725   }
4726 
4727   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4728                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4729 
4730   assert(!SetCC ||
4731         (SetCC->getConstantOperandVal(1) == 1 &&
4732          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4733                                                              ISD::SETNE));
4734 
4735   // operands of the new intrinsic call
4736   SmallVector<SDValue, 4> Ops;
4737   if (HaveChain)
4738     Ops.push_back(BRCOND.getOperand(0));
4739 
4740   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4741   Ops.push_back(Target);
4742 
4743   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4744 
4745   // build the new intrinsic call
4746   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4747 
4748   if (!HaveChain) {
4749     SDValue Ops[] =  {
4750       SDValue(Result, 0),
4751       BRCOND.getOperand(0)
4752     };
4753 
4754     Result = DAG.getMergeValues(Ops, DL).getNode();
4755   }
4756 
4757   if (BR) {
4758     // Give the branch instruction our target
4759     SDValue Ops[] = {
4760       BR->getOperand(0),
4761       BRCOND.getOperand(2)
4762     };
4763     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4764     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4765   }
4766 
4767   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4768 
4769   // Copy the intrinsic results to registers
4770   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4771     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4772     if (!CopyToReg)
4773       continue;
4774 
4775     Chain = DAG.getCopyToReg(
4776       Chain, DL,
4777       CopyToReg->getOperand(1),
4778       SDValue(Result, i - 1),
4779       SDValue());
4780 
4781     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4782   }
4783 
4784   // Remove the old intrinsic from the chain
4785   DAG.ReplaceAllUsesOfValueWith(
4786     SDValue(Intr, Intr->getNumValues() - 1),
4787     Intr->getOperand(0));
4788 
4789   return Chain;
4790 }
4791 
4792 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4793                                           SelectionDAG &DAG) const {
4794   MVT VT = Op.getSimpleValueType();
4795   SDLoc DL(Op);
4796   // Checking the depth
4797   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4798     return DAG.getConstant(0, DL, VT);
4799 
4800   MachineFunction &MF = DAG.getMachineFunction();
4801   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4802   // Check for kernel and shader functions
4803   if (Info->isEntryFunction())
4804     return DAG.getConstant(0, DL, VT);
4805 
4806   MachineFrameInfo &MFI = MF.getFrameInfo();
4807   // There is a call to @llvm.returnaddress in this function
4808   MFI.setReturnAddressIsTaken(true);
4809 
4810   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4811   // Get the return address reg and mark it as an implicit live-in
4812   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4813 
4814   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4815 }
4816 
4817 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4818                                             SDValue Op,
4819                                             const SDLoc &DL,
4820                                             EVT VT) const {
4821   return Op.getValueType().bitsLE(VT) ?
4822       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4823     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4824                 DAG.getTargetConstant(0, DL, MVT::i32));
4825 }
4826 
4827 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4828   assert(Op.getValueType() == MVT::f16 &&
4829          "Do not know how to custom lower FP_ROUND for non-f16 type");
4830 
4831   SDValue Src = Op.getOperand(0);
4832   EVT SrcVT = Src.getValueType();
4833   if (SrcVT != MVT::f64)
4834     return Op;
4835 
4836   SDLoc DL(Op);
4837 
4838   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4839   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4840   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4841 }
4842 
4843 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4844                                                SelectionDAG &DAG) const {
4845   EVT VT = Op.getValueType();
4846   const MachineFunction &MF = DAG.getMachineFunction();
4847   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4848   bool IsIEEEMode = Info->getMode().IEEE;
4849 
4850   // FIXME: Assert during selection that this is only selected for
4851   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4852   // mode functions, but this happens to be OK since it's only done in cases
4853   // where there is known no sNaN.
4854   if (IsIEEEMode)
4855     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4856 
4857   if (VT == MVT::v4f16)
4858     return splitBinaryVectorOp(Op, DAG);
4859   return Op;
4860 }
4861 
4862 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4863   SDLoc SL(Op);
4864   SDValue Chain = Op.getOperand(0);
4865 
4866   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4867       !Subtarget->isTrapHandlerEnabled())
4868     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4869 
4870   MachineFunction &MF = DAG.getMachineFunction();
4871   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4872   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4873   assert(UserSGPR != AMDGPU::NoRegister);
4874   SDValue QueuePtr = CreateLiveInRegister(
4875     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4876   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4877   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4878                                    QueuePtr, SDValue());
4879   SDValue Ops[] = {
4880     ToReg,
4881     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4882     SGPR01,
4883     ToReg.getValue(1)
4884   };
4885   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4886 }
4887 
4888 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4889   SDLoc SL(Op);
4890   SDValue Chain = Op.getOperand(0);
4891   MachineFunction &MF = DAG.getMachineFunction();
4892 
4893   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4894       !Subtarget->isTrapHandlerEnabled()) {
4895     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4896                                      "debugtrap handler not supported",
4897                                      Op.getDebugLoc(),
4898                                      DS_Warning);
4899     LLVMContext &Ctx = MF.getFunction().getContext();
4900     Ctx.diagnose(NoTrap);
4901     return Chain;
4902   }
4903 
4904   SDValue Ops[] = {
4905     Chain,
4906     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4907   };
4908   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4909 }
4910 
4911 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4912                                              SelectionDAG &DAG) const {
4913   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4914   if (Subtarget->hasApertureRegs()) {
4915     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4916         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4917         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4918     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4919         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4920         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4921     unsigned Encoding =
4922         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4923         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4924         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4925 
4926     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4927     SDValue ApertureReg = SDValue(
4928         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4929     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4930     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4931   }
4932 
4933   MachineFunction &MF = DAG.getMachineFunction();
4934   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4935   Register UserSGPR = Info->getQueuePtrUserSGPR();
4936   assert(UserSGPR != AMDGPU::NoRegister);
4937 
4938   SDValue QueuePtr = CreateLiveInRegister(
4939     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4940 
4941   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4942   // private_segment_aperture_base_hi.
4943   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4944 
4945   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4946 
4947   // TODO: Use custom target PseudoSourceValue.
4948   // TODO: We should use the value from the IR intrinsic call, but it might not
4949   // be available and how do we get it?
4950   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4951   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4952                      MinAlign(64, StructOffset),
4953                      MachineMemOperand::MODereferenceable |
4954                          MachineMemOperand::MOInvariant);
4955 }
4956 
4957 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4958                                              SelectionDAG &DAG) const {
4959   SDLoc SL(Op);
4960   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4961 
4962   SDValue Src = ASC->getOperand(0);
4963   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4964 
4965   const AMDGPUTargetMachine &TM =
4966     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4967 
4968   // flat -> local/private
4969   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4970     unsigned DestAS = ASC->getDestAddressSpace();
4971 
4972     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4973         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4974       unsigned NullVal = TM.getNullPointerValue(DestAS);
4975       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4976       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4977       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4978 
4979       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4980                          NonNull, Ptr, SegmentNullPtr);
4981     }
4982   }
4983 
4984   // local/private -> flat
4985   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4986     unsigned SrcAS = ASC->getSrcAddressSpace();
4987 
4988     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4989         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4990       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4991       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4992 
4993       SDValue NonNull
4994         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4995 
4996       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4997       SDValue CvtPtr
4998         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4999 
5000       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5001                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5002                          FlatNullPtr);
5003     }
5004   }
5005 
5006   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5007       Src.getValueType() == MVT::i64)
5008     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5009 
5010   // global <-> flat are no-ops and never emitted.
5011 
5012   const MachineFunction &MF = DAG.getMachineFunction();
5013   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5014     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5015   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5016 
5017   return DAG.getUNDEF(ASC->getValueType(0));
5018 }
5019 
5020 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5021 // the small vector and inserting them into the big vector. That is better than
5022 // the default expansion of doing it via a stack slot. Even though the use of
5023 // the stack slot would be optimized away afterwards, the stack slot itself
5024 // remains.
5025 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5026                                                 SelectionDAG &DAG) const {
5027   SDValue Vec = Op.getOperand(0);
5028   SDValue Ins = Op.getOperand(1);
5029   SDValue Idx = Op.getOperand(2);
5030   EVT VecVT = Vec.getValueType();
5031   EVT InsVT = Ins.getValueType();
5032   EVT EltVT = VecVT.getVectorElementType();
5033   unsigned InsNumElts = InsVT.getVectorNumElements();
5034   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5035   SDLoc SL(Op);
5036 
5037   for (unsigned I = 0; I != InsNumElts; ++I) {
5038     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5039                               DAG.getConstant(I, SL, MVT::i32));
5040     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5041                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5042   }
5043   return Vec;
5044 }
5045 
5046 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5047                                                  SelectionDAG &DAG) const {
5048   SDValue Vec = Op.getOperand(0);
5049   SDValue InsVal = Op.getOperand(1);
5050   SDValue Idx = Op.getOperand(2);
5051   EVT VecVT = Vec.getValueType();
5052   EVT EltVT = VecVT.getVectorElementType();
5053   unsigned VecSize = VecVT.getSizeInBits();
5054   unsigned EltSize = EltVT.getSizeInBits();
5055 
5056 
5057   assert(VecSize <= 64);
5058 
5059   unsigned NumElts = VecVT.getVectorNumElements();
5060   SDLoc SL(Op);
5061   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5062 
5063   if (NumElts == 4 && EltSize == 16 && KIdx) {
5064     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5065 
5066     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5067                                  DAG.getConstant(0, SL, MVT::i32));
5068     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5069                                  DAG.getConstant(1, SL, MVT::i32));
5070 
5071     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5072     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5073 
5074     unsigned Idx = KIdx->getZExtValue();
5075     bool InsertLo = Idx < 2;
5076     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5077       InsertLo ? LoVec : HiVec,
5078       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5079       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5080 
5081     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5082 
5083     SDValue Concat = InsertLo ?
5084       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5085       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5086 
5087     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5088   }
5089 
5090   if (isa<ConstantSDNode>(Idx))
5091     return SDValue();
5092 
5093   MVT IntVT = MVT::getIntegerVT(VecSize);
5094 
5095   // Avoid stack access for dynamic indexing.
5096   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5097 
5098   // Create a congruent vector with the target value in each element so that
5099   // the required element can be masked and ORed into the target vector.
5100   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5101                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5102 
5103   assert(isPowerOf2_32(EltSize));
5104   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5105 
5106   // Convert vector index to bit-index.
5107   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5108 
5109   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5110   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5111                             DAG.getConstant(0xffff, SL, IntVT),
5112                             ScaledIdx);
5113 
5114   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5115   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5116                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5117 
5118   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5119   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5120 }
5121 
5122 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5123                                                   SelectionDAG &DAG) const {
5124   SDLoc SL(Op);
5125 
5126   EVT ResultVT = Op.getValueType();
5127   SDValue Vec = Op.getOperand(0);
5128   SDValue Idx = Op.getOperand(1);
5129   EVT VecVT = Vec.getValueType();
5130   unsigned VecSize = VecVT.getSizeInBits();
5131   EVT EltVT = VecVT.getVectorElementType();
5132   assert(VecSize <= 64);
5133 
5134   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5135 
5136   // Make sure we do any optimizations that will make it easier to fold
5137   // source modifiers before obscuring it with bit operations.
5138 
5139   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5140   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5141     return Combined;
5142 
5143   unsigned EltSize = EltVT.getSizeInBits();
5144   assert(isPowerOf2_32(EltSize));
5145 
5146   MVT IntVT = MVT::getIntegerVT(VecSize);
5147   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5148 
5149   // Convert vector index to bit-index (* EltSize)
5150   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5151 
5152   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5153   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5154 
5155   if (ResultVT == MVT::f16) {
5156     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5157     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5158   }
5159 
5160   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5161 }
5162 
5163 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5164   assert(Elt % 2 == 0);
5165   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5166 }
5167 
5168 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5169                                               SelectionDAG &DAG) const {
5170   SDLoc SL(Op);
5171   EVT ResultVT = Op.getValueType();
5172   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5173 
5174   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5175   EVT EltVT = PackVT.getVectorElementType();
5176   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5177 
5178   // vector_shuffle <0,1,6,7> lhs, rhs
5179   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5180   //
5181   // vector_shuffle <6,7,2,3> lhs, rhs
5182   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5183   //
5184   // vector_shuffle <6,7,0,1> lhs, rhs
5185   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5186 
5187   // Avoid scalarizing when both halves are reading from consecutive elements.
5188   SmallVector<SDValue, 4> Pieces;
5189   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5190     if (elementPairIsContiguous(SVN->getMask(), I)) {
5191       const int Idx = SVN->getMaskElt(I);
5192       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5193       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5194       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5195                                     PackVT, SVN->getOperand(VecIdx),
5196                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5197       Pieces.push_back(SubVec);
5198     } else {
5199       const int Idx0 = SVN->getMaskElt(I);
5200       const int Idx1 = SVN->getMaskElt(I + 1);
5201       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5202       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5203       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5204       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5205 
5206       SDValue Vec0 = SVN->getOperand(VecIdx0);
5207       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5208                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5209 
5210       SDValue Vec1 = SVN->getOperand(VecIdx1);
5211       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5212                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5213       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5214     }
5215   }
5216 
5217   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5218 }
5219 
5220 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5221                                             SelectionDAG &DAG) const {
5222   SDLoc SL(Op);
5223   EVT VT = Op.getValueType();
5224 
5225   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5226     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5227 
5228     // Turn into pair of packed build_vectors.
5229     // TODO: Special case for constants that can be materialized with s_mov_b64.
5230     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5231                                     { Op.getOperand(0), Op.getOperand(1) });
5232     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5233                                     { Op.getOperand(2), Op.getOperand(3) });
5234 
5235     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5236     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5237 
5238     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5239     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5240   }
5241 
5242   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5243   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5244 
5245   SDValue Lo = Op.getOperand(0);
5246   SDValue Hi = Op.getOperand(1);
5247 
5248   // Avoid adding defined bits with the zero_extend.
5249   if (Hi.isUndef()) {
5250     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5251     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5252     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5253   }
5254 
5255   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5256   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5257 
5258   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5259                               DAG.getConstant(16, SL, MVT::i32));
5260   if (Lo.isUndef())
5261     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5262 
5263   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5264   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5265 
5266   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5267   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5268 }
5269 
5270 bool
5271 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5272   // We can fold offsets for anything that doesn't require a GOT relocation.
5273   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5274           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5275           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5276          !shouldEmitGOTReloc(GA->getGlobal());
5277 }
5278 
5279 static SDValue
5280 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5281                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5282                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5283   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5284   // lowered to the following code sequence:
5285   //
5286   // For constant address space:
5287   //   s_getpc_b64 s[0:1]
5288   //   s_add_u32 s0, s0, $symbol
5289   //   s_addc_u32 s1, s1, 0
5290   //
5291   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5292   //   a fixup or relocation is emitted to replace $symbol with a literal
5293   //   constant, which is a pc-relative offset from the encoding of the $symbol
5294   //   operand to the global variable.
5295   //
5296   // For global address space:
5297   //   s_getpc_b64 s[0:1]
5298   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5299   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5300   //
5301   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5302   //   fixups or relocations are emitted to replace $symbol@*@lo and
5303   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5304   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5305   //   operand to the global variable.
5306   //
5307   // What we want here is an offset from the value returned by s_getpc
5308   // (which is the address of the s_add_u32 instruction) to the global
5309   // variable, but since the encoding of $symbol starts 4 bytes after the start
5310   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5311   // small. This requires us to add 4 to the global variable offset in order to
5312   // compute the correct address.
5313   SDValue PtrLo =
5314       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5315   SDValue PtrHi;
5316   if (GAFlags == SIInstrInfo::MO_NONE) {
5317     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5318   } else {
5319     PtrHi =
5320         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5321   }
5322   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5323 }
5324 
5325 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5326                                              SDValue Op,
5327                                              SelectionDAG &DAG) const {
5328   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5329   const GlobalValue *GV = GSD->getGlobal();
5330   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5331        shouldUseLDSConstAddress(GV)) ||
5332       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5333       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5334     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5335 
5336   SDLoc DL(GSD);
5337   EVT PtrVT = Op.getValueType();
5338 
5339   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5340     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5341                                             SIInstrInfo::MO_ABS32_LO);
5342     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5343   }
5344 
5345   if (shouldEmitFixup(GV))
5346     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5347   else if (shouldEmitPCReloc(GV))
5348     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5349                                    SIInstrInfo::MO_REL32);
5350 
5351   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5352                                             SIInstrInfo::MO_GOTPCREL32);
5353 
5354   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5355   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5356   const DataLayout &DataLayout = DAG.getDataLayout();
5357   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5358   MachinePointerInfo PtrInfo
5359     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5360 
5361   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5362                      MachineMemOperand::MODereferenceable |
5363                          MachineMemOperand::MOInvariant);
5364 }
5365 
5366 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5367                                    const SDLoc &DL, SDValue V) const {
5368   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5369   // the destination register.
5370   //
5371   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5372   // so we will end up with redundant moves to m0.
5373   //
5374   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5375 
5376   // A Null SDValue creates a glue result.
5377   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5378                                   V, Chain);
5379   return SDValue(M0, 0);
5380 }
5381 
5382 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5383                                                  SDValue Op,
5384                                                  MVT VT,
5385                                                  unsigned Offset) const {
5386   SDLoc SL(Op);
5387   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5388                                            DAG.getEntryNode(), Offset, 4, false);
5389   // The local size values will have the hi 16-bits as zero.
5390   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5391                      DAG.getValueType(VT));
5392 }
5393 
5394 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5395                                         EVT VT) {
5396   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5397                                       "non-hsa intrinsic with hsa target",
5398                                       DL.getDebugLoc());
5399   DAG.getContext()->diagnose(BadIntrin);
5400   return DAG.getUNDEF(VT);
5401 }
5402 
5403 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5404                                          EVT VT) {
5405   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5406                                       "intrinsic not supported on subtarget",
5407                                       DL.getDebugLoc());
5408   DAG.getContext()->diagnose(BadIntrin);
5409   return DAG.getUNDEF(VT);
5410 }
5411 
5412 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5413                                     ArrayRef<SDValue> Elts) {
5414   assert(!Elts.empty());
5415   MVT Type;
5416   unsigned NumElts;
5417 
5418   if (Elts.size() == 1) {
5419     Type = MVT::f32;
5420     NumElts = 1;
5421   } else if (Elts.size() == 2) {
5422     Type = MVT::v2f32;
5423     NumElts = 2;
5424   } else if (Elts.size() == 3) {
5425     Type = MVT::v3f32;
5426     NumElts = 3;
5427   } else if (Elts.size() <= 4) {
5428     Type = MVT::v4f32;
5429     NumElts = 4;
5430   } else if (Elts.size() <= 8) {
5431     Type = MVT::v8f32;
5432     NumElts = 8;
5433   } else {
5434     assert(Elts.size() <= 16);
5435     Type = MVT::v16f32;
5436     NumElts = 16;
5437   }
5438 
5439   SmallVector<SDValue, 16> VecElts(NumElts);
5440   for (unsigned i = 0; i < Elts.size(); ++i) {
5441     SDValue Elt = Elts[i];
5442     if (Elt.getValueType() != MVT::f32)
5443       Elt = DAG.getBitcast(MVT::f32, Elt);
5444     VecElts[i] = Elt;
5445   }
5446   for (unsigned i = Elts.size(); i < NumElts; ++i)
5447     VecElts[i] = DAG.getUNDEF(MVT::f32);
5448 
5449   if (NumElts == 1)
5450     return VecElts[0];
5451   return DAG.getBuildVector(Type, DL, VecElts);
5452 }
5453 
5454 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5455                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5456   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5457 
5458   uint64_t Value = CachePolicyConst->getZExtValue();
5459   SDLoc DL(CachePolicy);
5460   if (GLC) {
5461     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5462     Value &= ~(uint64_t)0x1;
5463   }
5464   if (SLC) {
5465     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5466     Value &= ~(uint64_t)0x2;
5467   }
5468   if (DLC) {
5469     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5470     Value &= ~(uint64_t)0x4;
5471   }
5472 
5473   return Value == 0;
5474 }
5475 
5476 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5477                               SDValue Src, int ExtraElts) {
5478   EVT SrcVT = Src.getValueType();
5479 
5480   SmallVector<SDValue, 8> Elts;
5481 
5482   if (SrcVT.isVector())
5483     DAG.ExtractVectorElements(Src, Elts);
5484   else
5485     Elts.push_back(Src);
5486 
5487   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5488   while (ExtraElts--)
5489     Elts.push_back(Undef);
5490 
5491   return DAG.getBuildVector(CastVT, DL, Elts);
5492 }
5493 
5494 // Re-construct the required return value for a image load intrinsic.
5495 // This is more complicated due to the optional use TexFailCtrl which means the required
5496 // return type is an aggregate
5497 static SDValue constructRetValue(SelectionDAG &DAG,
5498                                  MachineSDNode *Result,
5499                                  ArrayRef<EVT> ResultTypes,
5500                                  bool IsTexFail, bool Unpacked, bool IsD16,
5501                                  int DMaskPop, int NumVDataDwords,
5502                                  const SDLoc &DL, LLVMContext &Context) {
5503   // Determine the required return type. This is the same regardless of IsTexFail flag
5504   EVT ReqRetVT = ResultTypes[0];
5505   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5506   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5507     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5508 
5509   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5510     DMaskPop : (DMaskPop + 1) / 2;
5511 
5512   MVT DataDwordVT = NumDataDwords == 1 ?
5513     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5514 
5515   MVT MaskPopVT = MaskPopDwords == 1 ?
5516     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5517 
5518   SDValue Data(Result, 0);
5519   SDValue TexFail;
5520 
5521   if (IsTexFail) {
5522     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5523     if (MaskPopVT.isVector()) {
5524       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5525                          SDValue(Result, 0), ZeroIdx);
5526     } else {
5527       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5528                          SDValue(Result, 0), ZeroIdx);
5529     }
5530 
5531     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5532                           SDValue(Result, 0),
5533                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5534   }
5535 
5536   if (DataDwordVT.isVector())
5537     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5538                           NumDataDwords - MaskPopDwords);
5539 
5540   if (IsD16)
5541     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5542 
5543   if (!ReqRetVT.isVector())
5544     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5545 
5546   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5547 
5548   if (TexFail)
5549     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5550 
5551   if (Result->getNumValues() == 1)
5552     return Data;
5553 
5554   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5555 }
5556 
5557 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5558                          SDValue *LWE, bool &IsTexFail) {
5559   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5560 
5561   uint64_t Value = TexFailCtrlConst->getZExtValue();
5562   if (Value) {
5563     IsTexFail = true;
5564   }
5565 
5566   SDLoc DL(TexFailCtrlConst);
5567   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5568   Value &= ~(uint64_t)0x1;
5569   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5570   Value &= ~(uint64_t)0x2;
5571 
5572   return Value == 0;
5573 }
5574 
5575 SDValue SITargetLowering::lowerImage(SDValue Op,
5576                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5577                                      SelectionDAG &DAG) const {
5578   SDLoc DL(Op);
5579   MachineFunction &MF = DAG.getMachineFunction();
5580   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5581   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5582       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5583   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5584   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5585       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5586   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5587       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5588   unsigned IntrOpcode = Intr->BaseOpcode;
5589   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5590 
5591   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5592   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5593   bool IsD16 = false;
5594   bool IsA16 = false;
5595   SDValue VData;
5596   int NumVDataDwords;
5597   bool AdjustRetType = false;
5598 
5599   unsigned AddrIdx; // Index of first address argument
5600   unsigned DMask;
5601   unsigned DMaskLanes = 0;
5602 
5603   if (BaseOpcode->Atomic) {
5604     VData = Op.getOperand(2);
5605 
5606     bool Is64Bit = VData.getValueType() == MVT::i64;
5607     if (BaseOpcode->AtomicX2) {
5608       SDValue VData2 = Op.getOperand(3);
5609       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5610                                  {VData, VData2});
5611       if (Is64Bit)
5612         VData = DAG.getBitcast(MVT::v4i32, VData);
5613 
5614       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5615       DMask = Is64Bit ? 0xf : 0x3;
5616       NumVDataDwords = Is64Bit ? 4 : 2;
5617       AddrIdx = 4;
5618     } else {
5619       DMask = Is64Bit ? 0x3 : 0x1;
5620       NumVDataDwords = Is64Bit ? 2 : 1;
5621       AddrIdx = 3;
5622     }
5623   } else {
5624     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5625     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5626     DMask = DMaskConst->getZExtValue();
5627     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5628 
5629     if (BaseOpcode->Store) {
5630       VData = Op.getOperand(2);
5631 
5632       MVT StoreVT = VData.getSimpleValueType();
5633       if (StoreVT.getScalarType() == MVT::f16) {
5634         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5635           return Op; // D16 is unsupported for this instruction
5636 
5637         IsD16 = true;
5638         VData = handleD16VData(VData, DAG);
5639       }
5640 
5641       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5642     } else {
5643       // Work out the num dwords based on the dmask popcount and underlying type
5644       // and whether packing is supported.
5645       MVT LoadVT = ResultTypes[0].getSimpleVT();
5646       if (LoadVT.getScalarType() == MVT::f16) {
5647         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5648           return Op; // D16 is unsupported for this instruction
5649 
5650         IsD16 = true;
5651       }
5652 
5653       // Confirm that the return type is large enough for the dmask specified
5654       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5655           (!LoadVT.isVector() && DMaskLanes > 1))
5656           return Op;
5657 
5658       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5659         NumVDataDwords = (DMaskLanes + 1) / 2;
5660       else
5661         NumVDataDwords = DMaskLanes;
5662 
5663       AdjustRetType = true;
5664     }
5665 
5666     AddrIdx = DMaskIdx + 1;
5667   }
5668 
5669   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5670   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5671   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5672   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5673                        NumCoords + NumLCM;
5674   unsigned NumMIVAddrs = NumVAddrs;
5675 
5676   SmallVector<SDValue, 4> VAddrs;
5677 
5678   // Optimize _L to _LZ when _L is zero
5679   if (LZMappingInfo) {
5680     if (auto ConstantLod =
5681          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5682       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5683         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5684         NumMIVAddrs--;               // remove 'lod'
5685       }
5686     }
5687   }
5688 
5689   // Optimize _mip away, when 'lod' is zero
5690   if (MIPMappingInfo) {
5691     if (auto ConstantLod =
5692          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5693       if (ConstantLod->isNullValue()) {
5694         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5695         NumMIVAddrs--;               // remove 'lod'
5696       }
5697     }
5698   }
5699 
5700   // Check for 16 bit addresses and pack if true.
5701   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5702   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5703   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5704   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5705     // Illegal to use a16 images
5706     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5707       return Op;
5708 
5709     IsA16 = true;
5710     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5711     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5712       SDValue AddrLo;
5713       // Push back extra arguments.
5714       if (i < DimIdx) {
5715         AddrLo = Op.getOperand(i);
5716       } else {
5717         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5718         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5719         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5720             ((NumGradients / 2) % 2 == 1 &&
5721             (i == DimIdx + (NumGradients / 2) - 1 ||
5722              i == DimIdx + NumGradients - 1))) {
5723           AddrLo = Op.getOperand(i);
5724           if (AddrLo.getValueType() != MVT::i16)
5725             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5726           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5727         } else {
5728           AddrLo = DAG.getBuildVector(VectorVT, DL,
5729                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5730           i++;
5731         }
5732         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5733       }
5734       VAddrs.push_back(AddrLo);
5735     }
5736   } else {
5737     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5738       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5739   }
5740 
5741   // If the register allocator cannot place the address registers contiguously
5742   // without introducing moves, then using the non-sequential address encoding
5743   // is always preferable, since it saves VALU instructions and is usually a
5744   // wash in terms of code size or even better.
5745   //
5746   // However, we currently have no way of hinting to the register allocator that
5747   // MIMG addresses should be placed contiguously when it is possible to do so,
5748   // so force non-NSA for the common 2-address case as a heuristic.
5749   //
5750   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5751   // allocation when possible.
5752   bool UseNSA =
5753       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5754   SDValue VAddr;
5755   if (!UseNSA)
5756     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5757 
5758   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5759   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5760   unsigned CtrlIdx; // Index of texfailctrl argument
5761   SDValue Unorm;
5762   if (!BaseOpcode->Sampler) {
5763     Unorm = True;
5764     CtrlIdx = AddrIdx + NumVAddrs + 1;
5765   } else {
5766     auto UnormConst =
5767         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5768 
5769     Unorm = UnormConst->getZExtValue() ? True : False;
5770     CtrlIdx = AddrIdx + NumVAddrs + 3;
5771   }
5772 
5773   SDValue TFE;
5774   SDValue LWE;
5775   SDValue TexFail = Op.getOperand(CtrlIdx);
5776   bool IsTexFail = false;
5777   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5778     return Op;
5779 
5780   if (IsTexFail) {
5781     if (!DMaskLanes) {
5782       // Expecting to get an error flag since TFC is on - and dmask is 0
5783       // Force dmask to be at least 1 otherwise the instruction will fail
5784       DMask = 0x1;
5785       DMaskLanes = 1;
5786       NumVDataDwords = 1;
5787     }
5788     NumVDataDwords += 1;
5789     AdjustRetType = true;
5790   }
5791 
5792   // Has something earlier tagged that the return type needs adjusting
5793   // This happens if the instruction is a load or has set TexFailCtrl flags
5794   if (AdjustRetType) {
5795     // NumVDataDwords reflects the true number of dwords required in the return type
5796     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5797       // This is a no-op load. This can be eliminated
5798       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5799       if (isa<MemSDNode>(Op))
5800         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5801       return Undef;
5802     }
5803 
5804     EVT NewVT = NumVDataDwords > 1 ?
5805                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5806                 : MVT::i32;
5807 
5808     ResultTypes[0] = NewVT;
5809     if (ResultTypes.size() == 3) {
5810       // Original result was aggregate type used for TexFailCtrl results
5811       // The actual instruction returns as a vector type which has now been
5812       // created. Remove the aggregate result.
5813       ResultTypes.erase(&ResultTypes[1]);
5814     }
5815   }
5816 
5817   SDValue GLC;
5818   SDValue SLC;
5819   SDValue DLC;
5820   if (BaseOpcode->Atomic) {
5821     GLC = True; // TODO no-return optimization
5822     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5823                           IsGFX10 ? &DLC : nullptr))
5824       return Op;
5825   } else {
5826     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5827                           IsGFX10 ? &DLC : nullptr))
5828       return Op;
5829   }
5830 
5831   SmallVector<SDValue, 26> Ops;
5832   if (BaseOpcode->Store || BaseOpcode->Atomic)
5833     Ops.push_back(VData); // vdata
5834   if (UseNSA) {
5835     for (const SDValue &Addr : VAddrs)
5836       Ops.push_back(Addr);
5837   } else {
5838     Ops.push_back(VAddr);
5839   }
5840   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5841   if (BaseOpcode->Sampler)
5842     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5843   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5844   if (IsGFX10)
5845     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5846   Ops.push_back(Unorm);
5847   if (IsGFX10)
5848     Ops.push_back(DLC);
5849   Ops.push_back(GLC);
5850   Ops.push_back(SLC);
5851   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5852                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5853   if (IsGFX10)
5854     Ops.push_back(IsA16 ? True : False);
5855   Ops.push_back(TFE);
5856   Ops.push_back(LWE);
5857   if (!IsGFX10)
5858     Ops.push_back(DimInfo->DA ? True : False);
5859   if (BaseOpcode->HasD16)
5860     Ops.push_back(IsD16 ? True : False);
5861   if (isa<MemSDNode>(Op))
5862     Ops.push_back(Op.getOperand(0)); // chain
5863 
5864   int NumVAddrDwords =
5865       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5866   int Opcode = -1;
5867 
5868   if (IsGFX10) {
5869     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5870                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5871                                           : AMDGPU::MIMGEncGfx10Default,
5872                                    NumVDataDwords, NumVAddrDwords);
5873   } else {
5874     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5875       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5876                                      NumVDataDwords, NumVAddrDwords);
5877     if (Opcode == -1)
5878       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5879                                      NumVDataDwords, NumVAddrDwords);
5880   }
5881   assert(Opcode != -1);
5882 
5883   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5884   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5885     MachineMemOperand *MemRef = MemOp->getMemOperand();
5886     DAG.setNodeMemRefs(NewNode, {MemRef});
5887   }
5888 
5889   if (BaseOpcode->AtomicX2) {
5890     SmallVector<SDValue, 1> Elt;
5891     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5892     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5893   } else if (!BaseOpcode->Store) {
5894     return constructRetValue(DAG, NewNode,
5895                              OrigResultTypes, IsTexFail,
5896                              Subtarget->hasUnpackedD16VMem(), IsD16,
5897                              DMaskLanes, NumVDataDwords, DL,
5898                              *DAG.getContext());
5899   }
5900 
5901   return SDValue(NewNode, 0);
5902 }
5903 
5904 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5905                                        SDValue Offset, SDValue CachePolicy,
5906                                        SelectionDAG &DAG) const {
5907   MachineFunction &MF = DAG.getMachineFunction();
5908 
5909   const DataLayout &DataLayout = DAG.getDataLayout();
5910   Align Alignment =
5911       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
5912 
5913   MachineMemOperand *MMO = MF.getMachineMemOperand(
5914       MachinePointerInfo(),
5915       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5916           MachineMemOperand::MOInvariant,
5917       VT.getStoreSize(), Alignment);
5918 
5919   if (!Offset->isDivergent()) {
5920     SDValue Ops[] = {
5921         Rsrc,
5922         Offset, // Offset
5923         CachePolicy
5924     };
5925 
5926     // Widen vec3 load to vec4.
5927     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5928       EVT WidenedVT =
5929           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5930       auto WidenedOp = DAG.getMemIntrinsicNode(
5931           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5932           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5933       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5934                                    DAG.getVectorIdxConstant(0, DL));
5935       return Subvector;
5936     }
5937 
5938     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5939                                    DAG.getVTList(VT), Ops, VT, MMO);
5940   }
5941 
5942   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5943   // assume that the buffer is unswizzled.
5944   SmallVector<SDValue, 4> Loads;
5945   unsigned NumLoads = 1;
5946   MVT LoadVT = VT.getSimpleVT();
5947   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5948   assert((LoadVT.getScalarType() == MVT::i32 ||
5949           LoadVT.getScalarType() == MVT::f32));
5950 
5951   if (NumElts == 8 || NumElts == 16) {
5952     NumLoads = NumElts / 4;
5953     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5954   }
5955 
5956   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5957   SDValue Ops[] = {
5958       DAG.getEntryNode(),                               // Chain
5959       Rsrc,                                             // rsrc
5960       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5961       {},                                               // voffset
5962       {},                                               // soffset
5963       {},                                               // offset
5964       CachePolicy,                                      // cachepolicy
5965       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5966   };
5967 
5968   // Use the alignment to ensure that the required offsets will fit into the
5969   // immediate offsets.
5970   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5971 
5972   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5973   for (unsigned i = 0; i < NumLoads; ++i) {
5974     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5975     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5976                                         LoadVT, MMO, DAG));
5977   }
5978 
5979   if (NumElts == 8 || NumElts == 16)
5980     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5981 
5982   return Loads[0];
5983 }
5984 
5985 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5986                                                   SelectionDAG &DAG) const {
5987   MachineFunction &MF = DAG.getMachineFunction();
5988   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5989 
5990   EVT VT = Op.getValueType();
5991   SDLoc DL(Op);
5992   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5993 
5994   // TODO: Should this propagate fast-math-flags?
5995 
5996   switch (IntrinsicID) {
5997   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5998     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5999       return emitNonHSAIntrinsicError(DAG, DL, VT);
6000     return getPreloadedValue(DAG, *MFI, VT,
6001                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6002   }
6003   case Intrinsic::amdgcn_dispatch_ptr:
6004   case Intrinsic::amdgcn_queue_ptr: {
6005     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6006       DiagnosticInfoUnsupported BadIntrin(
6007           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6008           DL.getDebugLoc());
6009       DAG.getContext()->diagnose(BadIntrin);
6010       return DAG.getUNDEF(VT);
6011     }
6012 
6013     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6014       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6015     return getPreloadedValue(DAG, *MFI, VT, RegID);
6016   }
6017   case Intrinsic::amdgcn_implicitarg_ptr: {
6018     if (MFI->isEntryFunction())
6019       return getImplicitArgPtr(DAG, DL);
6020     return getPreloadedValue(DAG, *MFI, VT,
6021                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6022   }
6023   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6024     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6025       // This only makes sense to call in a kernel, so just lower to null.
6026       return DAG.getConstant(0, DL, VT);
6027     }
6028 
6029     return getPreloadedValue(DAG, *MFI, VT,
6030                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6031   }
6032   case Intrinsic::amdgcn_dispatch_id: {
6033     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6034   }
6035   case Intrinsic::amdgcn_rcp:
6036     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6037   case Intrinsic::amdgcn_rsq:
6038     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6039   case Intrinsic::amdgcn_rsq_legacy:
6040     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6041       return emitRemovedIntrinsicError(DAG, DL, VT);
6042     return SDValue();
6043   case Intrinsic::amdgcn_rcp_legacy:
6044     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6045       return emitRemovedIntrinsicError(DAG, DL, VT);
6046     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6047   case Intrinsic::amdgcn_rsq_clamp: {
6048     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6049       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6050 
6051     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6052     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6053     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6054 
6055     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6056     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6057                               DAG.getConstantFP(Max, DL, VT));
6058     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6059                        DAG.getConstantFP(Min, DL, VT));
6060   }
6061   case Intrinsic::r600_read_ngroups_x:
6062     if (Subtarget->isAmdHsaOS())
6063       return emitNonHSAIntrinsicError(DAG, DL, VT);
6064 
6065     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6066                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6067   case Intrinsic::r600_read_ngroups_y:
6068     if (Subtarget->isAmdHsaOS())
6069       return emitNonHSAIntrinsicError(DAG, DL, VT);
6070 
6071     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6072                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6073   case Intrinsic::r600_read_ngroups_z:
6074     if (Subtarget->isAmdHsaOS())
6075       return emitNonHSAIntrinsicError(DAG, DL, VT);
6076 
6077     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6078                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6079   case Intrinsic::r600_read_global_size_x:
6080     if (Subtarget->isAmdHsaOS())
6081       return emitNonHSAIntrinsicError(DAG, DL, VT);
6082 
6083     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6084                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6085   case Intrinsic::r600_read_global_size_y:
6086     if (Subtarget->isAmdHsaOS())
6087       return emitNonHSAIntrinsicError(DAG, DL, VT);
6088 
6089     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6090                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6091   case Intrinsic::r600_read_global_size_z:
6092     if (Subtarget->isAmdHsaOS())
6093       return emitNonHSAIntrinsicError(DAG, DL, VT);
6094 
6095     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6096                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6097   case Intrinsic::r600_read_local_size_x:
6098     if (Subtarget->isAmdHsaOS())
6099       return emitNonHSAIntrinsicError(DAG, DL, VT);
6100 
6101     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6102                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6103   case Intrinsic::r600_read_local_size_y:
6104     if (Subtarget->isAmdHsaOS())
6105       return emitNonHSAIntrinsicError(DAG, DL, VT);
6106 
6107     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6108                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6109   case Intrinsic::r600_read_local_size_z:
6110     if (Subtarget->isAmdHsaOS())
6111       return emitNonHSAIntrinsicError(DAG, DL, VT);
6112 
6113     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6114                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6115   case Intrinsic::amdgcn_workgroup_id_x:
6116     return getPreloadedValue(DAG, *MFI, VT,
6117                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6118   case Intrinsic::amdgcn_workgroup_id_y:
6119     return getPreloadedValue(DAG, *MFI, VT,
6120                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6121   case Intrinsic::amdgcn_workgroup_id_z:
6122     return getPreloadedValue(DAG, *MFI, VT,
6123                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6124   case Intrinsic::amdgcn_workitem_id_x:
6125     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6126                           SDLoc(DAG.getEntryNode()),
6127                           MFI->getArgInfo().WorkItemIDX);
6128   case Intrinsic::amdgcn_workitem_id_y:
6129     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6130                           SDLoc(DAG.getEntryNode()),
6131                           MFI->getArgInfo().WorkItemIDY);
6132   case Intrinsic::amdgcn_workitem_id_z:
6133     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6134                           SDLoc(DAG.getEntryNode()),
6135                           MFI->getArgInfo().WorkItemIDZ);
6136   case Intrinsic::amdgcn_wavefrontsize:
6137     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6138                            SDLoc(Op), MVT::i32);
6139   case Intrinsic::amdgcn_s_buffer_load: {
6140     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6141     SDValue GLC;
6142     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6143     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6144                           IsGFX10 ? &DLC : nullptr))
6145       return Op;
6146     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6147                         DAG);
6148   }
6149   case Intrinsic::amdgcn_fdiv_fast:
6150     return lowerFDIV_FAST(Op, DAG);
6151   case Intrinsic::amdgcn_sin:
6152     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6153 
6154   case Intrinsic::amdgcn_cos:
6155     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6156 
6157   case Intrinsic::amdgcn_mul_u24:
6158     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6159   case Intrinsic::amdgcn_mul_i24:
6160     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6161 
6162   case Intrinsic::amdgcn_log_clamp: {
6163     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6164       return SDValue();
6165 
6166     DiagnosticInfoUnsupported BadIntrin(
6167       MF.getFunction(), "intrinsic not supported on subtarget",
6168       DL.getDebugLoc());
6169       DAG.getContext()->diagnose(BadIntrin);
6170       return DAG.getUNDEF(VT);
6171   }
6172   case Intrinsic::amdgcn_ldexp:
6173     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6174                        Op.getOperand(1), Op.getOperand(2));
6175 
6176   case Intrinsic::amdgcn_fract:
6177     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6178 
6179   case Intrinsic::amdgcn_class:
6180     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6181                        Op.getOperand(1), Op.getOperand(2));
6182   case Intrinsic::amdgcn_div_fmas:
6183     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6184                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6185                        Op.getOperand(4));
6186 
6187   case Intrinsic::amdgcn_div_fixup:
6188     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6189                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6190 
6191   case Intrinsic::amdgcn_trig_preop:
6192     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
6193                        Op.getOperand(1), Op.getOperand(2));
6194   case Intrinsic::amdgcn_div_scale: {
6195     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6196 
6197     // Translate to the operands expected by the machine instruction. The
6198     // first parameter must be the same as the first instruction.
6199     SDValue Numerator = Op.getOperand(1);
6200     SDValue Denominator = Op.getOperand(2);
6201 
6202     // Note this order is opposite of the machine instruction's operations,
6203     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6204     // intrinsic has the numerator as the first operand to match a normal
6205     // division operation.
6206 
6207     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6208 
6209     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6210                        Denominator, Numerator);
6211   }
6212   case Intrinsic::amdgcn_icmp: {
6213     // There is a Pat that handles this variant, so return it as-is.
6214     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6215         Op.getConstantOperandVal(2) == 0 &&
6216         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6217       return Op;
6218     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6219   }
6220   case Intrinsic::amdgcn_fcmp: {
6221     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6222   }
6223   case Intrinsic::amdgcn_ballot:
6224     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6225   case Intrinsic::amdgcn_fmed3:
6226     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6227                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6228   case Intrinsic::amdgcn_fdot2:
6229     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6230                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6231                        Op.getOperand(4));
6232   case Intrinsic::amdgcn_fmul_legacy:
6233     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6234                        Op.getOperand(1), Op.getOperand(2));
6235   case Intrinsic::amdgcn_sffbh:
6236     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6237   case Intrinsic::amdgcn_sbfe:
6238     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6239                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6240   case Intrinsic::amdgcn_ubfe:
6241     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6242                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6243   case Intrinsic::amdgcn_cvt_pkrtz:
6244   case Intrinsic::amdgcn_cvt_pknorm_i16:
6245   case Intrinsic::amdgcn_cvt_pknorm_u16:
6246   case Intrinsic::amdgcn_cvt_pk_i16:
6247   case Intrinsic::amdgcn_cvt_pk_u16: {
6248     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6249     EVT VT = Op.getValueType();
6250     unsigned Opcode;
6251 
6252     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6253       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6254     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6255       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6256     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6257       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6258     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6259       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6260     else
6261       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6262 
6263     if (isTypeLegal(VT))
6264       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6265 
6266     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6267                                Op.getOperand(1), Op.getOperand(2));
6268     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6269   }
6270   case Intrinsic::amdgcn_fmad_ftz:
6271     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6272                        Op.getOperand(2), Op.getOperand(3));
6273 
6274   case Intrinsic::amdgcn_if_break:
6275     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6276                                       Op->getOperand(1), Op->getOperand(2)), 0);
6277 
6278   case Intrinsic::amdgcn_groupstaticsize: {
6279     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6280     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6281       return Op;
6282 
6283     const Module *M = MF.getFunction().getParent();
6284     const GlobalValue *GV =
6285         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6286     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6287                                             SIInstrInfo::MO_ABS32_LO);
6288     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6289   }
6290   case Intrinsic::amdgcn_is_shared:
6291   case Intrinsic::amdgcn_is_private: {
6292     SDLoc SL(Op);
6293     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6294       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6295     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6296     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6297                                  Op.getOperand(1));
6298 
6299     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6300                                 DAG.getConstant(1, SL, MVT::i32));
6301     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6302   }
6303   case Intrinsic::amdgcn_alignbit:
6304     return DAG.getNode(ISD::FSHR, DL, VT,
6305                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6306   case Intrinsic::amdgcn_reloc_constant: {
6307     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6308     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6309     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6310     auto RelocSymbol = cast<GlobalVariable>(
6311         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6312     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6313                                             SIInstrInfo::MO_ABS32_LO);
6314     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6315   }
6316   default:
6317     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6318             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6319       return lowerImage(Op, ImageDimIntr, DAG);
6320 
6321     return Op;
6322   }
6323 }
6324 
6325 // This function computes an appropriate offset to pass to
6326 // MachineMemOperand::setOffset() based on the offset inputs to
6327 // an intrinsic.  If any of the offsets are non-contstant or
6328 // if VIndex is non-zero then this function returns 0.  Otherwise,
6329 // it returns the sum of VOffset, SOffset, and Offset.
6330 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6331                                       SDValue SOffset,
6332                                       SDValue Offset,
6333                                       SDValue VIndex = SDValue()) {
6334 
6335   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6336       !isa<ConstantSDNode>(Offset))
6337     return 0;
6338 
6339   if (VIndex) {
6340     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6341       return 0;
6342   }
6343 
6344   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6345          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6346          cast<ConstantSDNode>(Offset)->getSExtValue();
6347 }
6348 
6349 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6350   switch (MF.getFunction().getCallingConv()) {
6351   case CallingConv::AMDGPU_PS:
6352     return 1;
6353   case CallingConv::AMDGPU_VS:
6354     return 2;
6355   case CallingConv::AMDGPU_GS:
6356     return 3;
6357   case CallingConv::AMDGPU_HS:
6358   case CallingConv::AMDGPU_LS:
6359   case CallingConv::AMDGPU_ES:
6360     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6361   case CallingConv::AMDGPU_CS:
6362   case CallingConv::AMDGPU_KERNEL:
6363   case CallingConv::C:
6364   case CallingConv::Fast:
6365   default:
6366     // Assume other calling conventions are various compute callable functions
6367     return 0;
6368   }
6369 }
6370 
6371 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6372                                                  SelectionDAG &DAG) const {
6373   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6374   SDLoc DL(Op);
6375 
6376   switch (IntrID) {
6377   case Intrinsic::amdgcn_ds_ordered_add:
6378   case Intrinsic::amdgcn_ds_ordered_swap: {
6379     MemSDNode *M = cast<MemSDNode>(Op);
6380     SDValue Chain = M->getOperand(0);
6381     SDValue M0 = M->getOperand(2);
6382     SDValue Value = M->getOperand(3);
6383     unsigned IndexOperand = M->getConstantOperandVal(7);
6384     unsigned WaveRelease = M->getConstantOperandVal(8);
6385     unsigned WaveDone = M->getConstantOperandVal(9);
6386 
6387     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6388     IndexOperand &= ~0x3f;
6389     unsigned CountDw = 0;
6390 
6391     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6392       CountDw = (IndexOperand >> 24) & 0xf;
6393       IndexOperand &= ~(0xf << 24);
6394 
6395       if (CountDw < 1 || CountDw > 4) {
6396         report_fatal_error(
6397             "ds_ordered_count: dword count must be between 1 and 4");
6398       }
6399     }
6400 
6401     if (IndexOperand)
6402       report_fatal_error("ds_ordered_count: bad index operand");
6403 
6404     if (WaveDone && !WaveRelease)
6405       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6406 
6407     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6408     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6409     unsigned Offset0 = OrderedCountIndex << 2;
6410     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6411                        (Instruction << 4);
6412 
6413     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6414       Offset1 |= (CountDw - 1) << 6;
6415 
6416     unsigned Offset = Offset0 | (Offset1 << 8);
6417 
6418     SDValue Ops[] = {
6419       Chain,
6420       Value,
6421       DAG.getTargetConstant(Offset, DL, MVT::i16),
6422       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6423     };
6424     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6425                                    M->getVTList(), Ops, M->getMemoryVT(),
6426                                    M->getMemOperand());
6427   }
6428   case Intrinsic::amdgcn_ds_fadd: {
6429     MemSDNode *M = cast<MemSDNode>(Op);
6430     unsigned Opc;
6431     switch (IntrID) {
6432     case Intrinsic::amdgcn_ds_fadd:
6433       Opc = ISD::ATOMIC_LOAD_FADD;
6434       break;
6435     }
6436 
6437     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6438                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6439                          M->getMemOperand());
6440   }
6441   case Intrinsic::amdgcn_atomic_inc:
6442   case Intrinsic::amdgcn_atomic_dec:
6443   case Intrinsic::amdgcn_ds_fmin:
6444   case Intrinsic::amdgcn_ds_fmax: {
6445     MemSDNode *M = cast<MemSDNode>(Op);
6446     unsigned Opc;
6447     switch (IntrID) {
6448     case Intrinsic::amdgcn_atomic_inc:
6449       Opc = AMDGPUISD::ATOMIC_INC;
6450       break;
6451     case Intrinsic::amdgcn_atomic_dec:
6452       Opc = AMDGPUISD::ATOMIC_DEC;
6453       break;
6454     case Intrinsic::amdgcn_ds_fmin:
6455       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6456       break;
6457     case Intrinsic::amdgcn_ds_fmax:
6458       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6459       break;
6460     default:
6461       llvm_unreachable("Unknown intrinsic!");
6462     }
6463     SDValue Ops[] = {
6464       M->getOperand(0), // Chain
6465       M->getOperand(2), // Ptr
6466       M->getOperand(3)  // Value
6467     };
6468 
6469     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6470                                    M->getMemoryVT(), M->getMemOperand());
6471   }
6472   case Intrinsic::amdgcn_buffer_load:
6473   case Intrinsic::amdgcn_buffer_load_format: {
6474     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6475     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6476     unsigned IdxEn = 1;
6477     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6478       IdxEn = Idx->getZExtValue() != 0;
6479     SDValue Ops[] = {
6480       Op.getOperand(0), // Chain
6481       Op.getOperand(2), // rsrc
6482       Op.getOperand(3), // vindex
6483       SDValue(),        // voffset -- will be set by setBufferOffsets
6484       SDValue(),        // soffset -- will be set by setBufferOffsets
6485       SDValue(),        // offset -- will be set by setBufferOffsets
6486       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6487       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6488     };
6489 
6490     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6491     // We don't know the offset if vindex is non-zero, so clear it.
6492     if (IdxEn)
6493       Offset = 0;
6494 
6495     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6496         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6497 
6498     EVT VT = Op.getValueType();
6499     EVT IntVT = VT.changeTypeToInteger();
6500     auto *M = cast<MemSDNode>(Op);
6501     M->getMemOperand()->setOffset(Offset);
6502     EVT LoadVT = Op.getValueType();
6503 
6504     if (LoadVT.getScalarType() == MVT::f16)
6505       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6506                                  M, DAG, Ops);
6507 
6508     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6509     if (LoadVT.getScalarType() == MVT::i8 ||
6510         LoadVT.getScalarType() == MVT::i16)
6511       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6512 
6513     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6514                                M->getMemOperand(), DAG);
6515   }
6516   case Intrinsic::amdgcn_raw_buffer_load:
6517   case Intrinsic::amdgcn_raw_buffer_load_format: {
6518     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6519 
6520     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6521     SDValue Ops[] = {
6522       Op.getOperand(0), // Chain
6523       Op.getOperand(2), // rsrc
6524       DAG.getConstant(0, DL, MVT::i32), // vindex
6525       Offsets.first,    // voffset
6526       Op.getOperand(4), // soffset
6527       Offsets.second,   // offset
6528       Op.getOperand(5), // cachepolicy, swizzled buffer
6529       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6530     };
6531 
6532     auto *M = cast<MemSDNode>(Op);
6533     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6534     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6535   }
6536   case Intrinsic::amdgcn_struct_buffer_load:
6537   case Intrinsic::amdgcn_struct_buffer_load_format: {
6538     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6539 
6540     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6541     SDValue Ops[] = {
6542       Op.getOperand(0), // Chain
6543       Op.getOperand(2), // rsrc
6544       Op.getOperand(3), // vindex
6545       Offsets.first,    // voffset
6546       Op.getOperand(5), // soffset
6547       Offsets.second,   // offset
6548       Op.getOperand(6), // cachepolicy, swizzled buffer
6549       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6550     };
6551 
6552     auto *M = cast<MemSDNode>(Op);
6553     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6554                                                         Ops[2]));
6555     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6556   }
6557   case Intrinsic::amdgcn_tbuffer_load: {
6558     MemSDNode *M = cast<MemSDNode>(Op);
6559     EVT LoadVT = Op.getValueType();
6560 
6561     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6562     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6563     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6564     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6565     unsigned IdxEn = 1;
6566     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6567       IdxEn = Idx->getZExtValue() != 0;
6568     SDValue Ops[] = {
6569       Op.getOperand(0),  // Chain
6570       Op.getOperand(2),  // rsrc
6571       Op.getOperand(3),  // vindex
6572       Op.getOperand(4),  // voffset
6573       Op.getOperand(5),  // soffset
6574       Op.getOperand(6),  // offset
6575       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6576       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6577       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6578     };
6579 
6580     if (LoadVT.getScalarType() == MVT::f16)
6581       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6582                                  M, DAG, Ops);
6583     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6584                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6585                                DAG);
6586   }
6587   case Intrinsic::amdgcn_raw_tbuffer_load: {
6588     MemSDNode *M = cast<MemSDNode>(Op);
6589     EVT LoadVT = Op.getValueType();
6590     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6591 
6592     SDValue Ops[] = {
6593       Op.getOperand(0),  // Chain
6594       Op.getOperand(2),  // rsrc
6595       DAG.getConstant(0, DL, MVT::i32), // vindex
6596       Offsets.first,     // voffset
6597       Op.getOperand(4),  // soffset
6598       Offsets.second,    // offset
6599       Op.getOperand(5),  // format
6600       Op.getOperand(6),  // cachepolicy, swizzled buffer
6601       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6602     };
6603 
6604     if (LoadVT.getScalarType() == MVT::f16)
6605       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6606                                  M, DAG, Ops);
6607     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6608                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6609                                DAG);
6610   }
6611   case Intrinsic::amdgcn_struct_tbuffer_load: {
6612     MemSDNode *M = cast<MemSDNode>(Op);
6613     EVT LoadVT = Op.getValueType();
6614     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6615 
6616     SDValue Ops[] = {
6617       Op.getOperand(0),  // Chain
6618       Op.getOperand(2),  // rsrc
6619       Op.getOperand(3),  // vindex
6620       Offsets.first,     // voffset
6621       Op.getOperand(5),  // soffset
6622       Offsets.second,    // offset
6623       Op.getOperand(6),  // format
6624       Op.getOperand(7),  // cachepolicy, swizzled buffer
6625       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6626     };
6627 
6628     if (LoadVT.getScalarType() == MVT::f16)
6629       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6630                                  M, DAG, Ops);
6631     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6632                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6633                                DAG);
6634   }
6635   case Intrinsic::amdgcn_buffer_atomic_swap:
6636   case Intrinsic::amdgcn_buffer_atomic_add:
6637   case Intrinsic::amdgcn_buffer_atomic_sub:
6638   case Intrinsic::amdgcn_buffer_atomic_smin:
6639   case Intrinsic::amdgcn_buffer_atomic_umin:
6640   case Intrinsic::amdgcn_buffer_atomic_smax:
6641   case Intrinsic::amdgcn_buffer_atomic_umax:
6642   case Intrinsic::amdgcn_buffer_atomic_and:
6643   case Intrinsic::amdgcn_buffer_atomic_or:
6644   case Intrinsic::amdgcn_buffer_atomic_xor: {
6645     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6646     unsigned IdxEn = 1;
6647     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6648       IdxEn = Idx->getZExtValue() != 0;
6649     SDValue Ops[] = {
6650       Op.getOperand(0), // Chain
6651       Op.getOperand(2), // vdata
6652       Op.getOperand(3), // rsrc
6653       Op.getOperand(4), // vindex
6654       SDValue(),        // voffset -- will be set by setBufferOffsets
6655       SDValue(),        // soffset -- will be set by setBufferOffsets
6656       SDValue(),        // offset -- will be set by setBufferOffsets
6657       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6658       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6659     };
6660     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6661     // We don't know the offset if vindex is non-zero, so clear it.
6662     if (IdxEn)
6663       Offset = 0;
6664     EVT VT = Op.getValueType();
6665 
6666     auto *M = cast<MemSDNode>(Op);
6667     M->getMemOperand()->setOffset(Offset);
6668     unsigned Opcode = 0;
6669 
6670     switch (IntrID) {
6671     case Intrinsic::amdgcn_buffer_atomic_swap:
6672       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6673       break;
6674     case Intrinsic::amdgcn_buffer_atomic_add:
6675       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6676       break;
6677     case Intrinsic::amdgcn_buffer_atomic_sub:
6678       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6679       break;
6680     case Intrinsic::amdgcn_buffer_atomic_smin:
6681       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6682       break;
6683     case Intrinsic::amdgcn_buffer_atomic_umin:
6684       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6685       break;
6686     case Intrinsic::amdgcn_buffer_atomic_smax:
6687       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6688       break;
6689     case Intrinsic::amdgcn_buffer_atomic_umax:
6690       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6691       break;
6692     case Intrinsic::amdgcn_buffer_atomic_and:
6693       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6694       break;
6695     case Intrinsic::amdgcn_buffer_atomic_or:
6696       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6697       break;
6698     case Intrinsic::amdgcn_buffer_atomic_xor:
6699       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6700       break;
6701     default:
6702       llvm_unreachable("unhandled atomic opcode");
6703     }
6704 
6705     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6706                                    M->getMemOperand());
6707   }
6708   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6709   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6710   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6711   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6712   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6713   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6714   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6715   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6716   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6717   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6718   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6719   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6720     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6721     SDValue Ops[] = {
6722       Op.getOperand(0), // Chain
6723       Op.getOperand(2), // vdata
6724       Op.getOperand(3), // rsrc
6725       DAG.getConstant(0, DL, MVT::i32), // vindex
6726       Offsets.first,    // voffset
6727       Op.getOperand(5), // soffset
6728       Offsets.second,   // offset
6729       Op.getOperand(6), // cachepolicy
6730       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6731     };
6732     EVT VT = Op.getValueType();
6733 
6734     auto *M = cast<MemSDNode>(Op);
6735     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6736     unsigned Opcode = 0;
6737 
6738     switch (IntrID) {
6739     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6740       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6741       break;
6742     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6743       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6744       break;
6745     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6746       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6747       break;
6748     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6749       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6750       break;
6751     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6752       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6753       break;
6754     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6755       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6756       break;
6757     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6758       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6759       break;
6760     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6761       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6762       break;
6763     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6764       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6765       break;
6766     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6767       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6768       break;
6769     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6770       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6771       break;
6772     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6773       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6774       break;
6775     default:
6776       llvm_unreachable("unhandled atomic opcode");
6777     }
6778 
6779     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6780                                    M->getMemOperand());
6781   }
6782   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6783   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6784   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6785   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6786   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6787   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6788   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6789   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6790   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6791   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6792   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6793   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6794     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6795     SDValue Ops[] = {
6796       Op.getOperand(0), // Chain
6797       Op.getOperand(2), // vdata
6798       Op.getOperand(3), // rsrc
6799       Op.getOperand(4), // vindex
6800       Offsets.first,    // voffset
6801       Op.getOperand(6), // soffset
6802       Offsets.second,   // offset
6803       Op.getOperand(7), // cachepolicy
6804       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6805     };
6806     EVT VT = Op.getValueType();
6807 
6808     auto *M = cast<MemSDNode>(Op);
6809     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6810                                                         Ops[3]));
6811     unsigned Opcode = 0;
6812 
6813     switch (IntrID) {
6814     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6815       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6816       break;
6817     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6818       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6819       break;
6820     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6821       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6822       break;
6823     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6824       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6825       break;
6826     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6827       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6828       break;
6829     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6830       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6831       break;
6832     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6833       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6834       break;
6835     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6836       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6837       break;
6838     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6839       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6840       break;
6841     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6842       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6843       break;
6844     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6845       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6846       break;
6847     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6848       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6849       break;
6850     default:
6851       llvm_unreachable("unhandled atomic opcode");
6852     }
6853 
6854     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6855                                    M->getMemOperand());
6856   }
6857   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6858     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6859     unsigned IdxEn = 1;
6860     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6861       IdxEn = Idx->getZExtValue() != 0;
6862     SDValue Ops[] = {
6863       Op.getOperand(0), // Chain
6864       Op.getOperand(2), // src
6865       Op.getOperand(3), // cmp
6866       Op.getOperand(4), // rsrc
6867       Op.getOperand(5), // vindex
6868       SDValue(),        // voffset -- will be set by setBufferOffsets
6869       SDValue(),        // soffset -- will be set by setBufferOffsets
6870       SDValue(),        // offset -- will be set by setBufferOffsets
6871       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6872       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6873     };
6874     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6875     // We don't know the offset if vindex is non-zero, so clear it.
6876     if (IdxEn)
6877       Offset = 0;
6878     EVT VT = Op.getValueType();
6879     auto *M = cast<MemSDNode>(Op);
6880     M->getMemOperand()->setOffset(Offset);
6881 
6882     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6883                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6884   }
6885   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6886     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6887     SDValue Ops[] = {
6888       Op.getOperand(0), // Chain
6889       Op.getOperand(2), // src
6890       Op.getOperand(3), // cmp
6891       Op.getOperand(4), // rsrc
6892       DAG.getConstant(0, DL, MVT::i32), // vindex
6893       Offsets.first,    // voffset
6894       Op.getOperand(6), // soffset
6895       Offsets.second,   // offset
6896       Op.getOperand(7), // cachepolicy
6897       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6898     };
6899     EVT VT = Op.getValueType();
6900     auto *M = cast<MemSDNode>(Op);
6901     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6902 
6903     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6904                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6905   }
6906   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6907     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6908     SDValue Ops[] = {
6909       Op.getOperand(0), // Chain
6910       Op.getOperand(2), // src
6911       Op.getOperand(3), // cmp
6912       Op.getOperand(4), // rsrc
6913       Op.getOperand(5), // vindex
6914       Offsets.first,    // voffset
6915       Op.getOperand(7), // soffset
6916       Offsets.second,   // offset
6917       Op.getOperand(8), // cachepolicy
6918       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6919     };
6920     EVT VT = Op.getValueType();
6921     auto *M = cast<MemSDNode>(Op);
6922     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6923                                                         Ops[4]));
6924 
6925     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6926                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6927   }
6928 
6929   default:
6930     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6931             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6932       return lowerImage(Op, ImageDimIntr, DAG);
6933 
6934     return SDValue();
6935   }
6936 }
6937 
6938 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6939 // dwordx4 if on SI.
6940 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6941                                               SDVTList VTList,
6942                                               ArrayRef<SDValue> Ops, EVT MemVT,
6943                                               MachineMemOperand *MMO,
6944                                               SelectionDAG &DAG) const {
6945   EVT VT = VTList.VTs[0];
6946   EVT WidenedVT = VT;
6947   EVT WidenedMemVT = MemVT;
6948   if (!Subtarget->hasDwordx3LoadStores() &&
6949       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6950     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6951                                  WidenedVT.getVectorElementType(), 4);
6952     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6953                                     WidenedMemVT.getVectorElementType(), 4);
6954     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6955   }
6956 
6957   assert(VTList.NumVTs == 2);
6958   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6959 
6960   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6961                                        WidenedMemVT, MMO);
6962   if (WidenedVT != VT) {
6963     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6964                                DAG.getVectorIdxConstant(0, DL));
6965     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6966   }
6967   return NewOp;
6968 }
6969 
6970 SDValue SITargetLowering::handleD16VData(SDValue VData,
6971                                          SelectionDAG &DAG) const {
6972   EVT StoreVT = VData.getValueType();
6973 
6974   // No change for f16 and legal vector D16 types.
6975   if (!StoreVT.isVector())
6976     return VData;
6977 
6978   SDLoc DL(VData);
6979   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6980 
6981   if (Subtarget->hasUnpackedD16VMem()) {
6982     // We need to unpack the packed data to store.
6983     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6984     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6985 
6986     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6987                                         StoreVT.getVectorNumElements());
6988     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6989     return DAG.UnrollVectorOp(ZExt.getNode());
6990   }
6991 
6992   assert(isTypeLegal(StoreVT));
6993   return VData;
6994 }
6995 
6996 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6997                                               SelectionDAG &DAG) const {
6998   SDLoc DL(Op);
6999   SDValue Chain = Op.getOperand(0);
7000   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7001   MachineFunction &MF = DAG.getMachineFunction();
7002 
7003   switch (IntrinsicID) {
7004   case Intrinsic::amdgcn_exp_compr: {
7005     SDValue Src0 = Op.getOperand(4);
7006     SDValue Src1 = Op.getOperand(5);
7007     // Hack around illegal type on SI by directly selecting it.
7008     if (isTypeLegal(Src0.getValueType()))
7009       return SDValue();
7010 
7011     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7012     SDValue Undef = DAG.getUNDEF(MVT::f32);
7013     const SDValue Ops[] = {
7014       Op.getOperand(2), // tgt
7015       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7016       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7017       Undef, // src2
7018       Undef, // src3
7019       Op.getOperand(7), // vm
7020       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7021       Op.getOperand(3), // en
7022       Op.getOperand(0) // Chain
7023     };
7024 
7025     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7026     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7027   }
7028   case Intrinsic::amdgcn_s_barrier: {
7029     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7030       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7031       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7032       if (WGSize <= ST.getWavefrontSize())
7033         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7034                                           Op.getOperand(0)), 0);
7035     }
7036     return SDValue();
7037   };
7038   case Intrinsic::amdgcn_tbuffer_store: {
7039     SDValue VData = Op.getOperand(2);
7040     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7041     if (IsD16)
7042       VData = handleD16VData(VData, DAG);
7043     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7044     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7045     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7046     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7047     unsigned IdxEn = 1;
7048     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7049       IdxEn = Idx->getZExtValue() != 0;
7050     SDValue Ops[] = {
7051       Chain,
7052       VData,             // vdata
7053       Op.getOperand(3),  // rsrc
7054       Op.getOperand(4),  // vindex
7055       Op.getOperand(5),  // voffset
7056       Op.getOperand(6),  // soffset
7057       Op.getOperand(7),  // offset
7058       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7059       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7060       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7061     };
7062     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7063                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7064     MemSDNode *M = cast<MemSDNode>(Op);
7065     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7066                                    M->getMemoryVT(), M->getMemOperand());
7067   }
7068 
7069   case Intrinsic::amdgcn_struct_tbuffer_store: {
7070     SDValue VData = Op.getOperand(2);
7071     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7072     if (IsD16)
7073       VData = handleD16VData(VData, DAG);
7074     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7075     SDValue Ops[] = {
7076       Chain,
7077       VData,             // vdata
7078       Op.getOperand(3),  // rsrc
7079       Op.getOperand(4),  // vindex
7080       Offsets.first,     // voffset
7081       Op.getOperand(6),  // soffset
7082       Offsets.second,    // offset
7083       Op.getOperand(7),  // format
7084       Op.getOperand(8),  // cachepolicy, swizzled buffer
7085       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7086     };
7087     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7088                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7089     MemSDNode *M = cast<MemSDNode>(Op);
7090     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7091                                    M->getMemoryVT(), M->getMemOperand());
7092   }
7093 
7094   case Intrinsic::amdgcn_raw_tbuffer_store: {
7095     SDValue VData = Op.getOperand(2);
7096     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7097     if (IsD16)
7098       VData = handleD16VData(VData, DAG);
7099     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7100     SDValue Ops[] = {
7101       Chain,
7102       VData,             // vdata
7103       Op.getOperand(3),  // rsrc
7104       DAG.getConstant(0, DL, MVT::i32), // vindex
7105       Offsets.first,     // voffset
7106       Op.getOperand(5),  // soffset
7107       Offsets.second,    // offset
7108       Op.getOperand(6),  // format
7109       Op.getOperand(7),  // cachepolicy, swizzled buffer
7110       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7111     };
7112     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7113                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7114     MemSDNode *M = cast<MemSDNode>(Op);
7115     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7116                                    M->getMemoryVT(), M->getMemOperand());
7117   }
7118 
7119   case Intrinsic::amdgcn_buffer_store:
7120   case Intrinsic::amdgcn_buffer_store_format: {
7121     SDValue VData = Op.getOperand(2);
7122     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7123     if (IsD16)
7124       VData = handleD16VData(VData, DAG);
7125     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7126     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7127     unsigned IdxEn = 1;
7128     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7129       IdxEn = Idx->getZExtValue() != 0;
7130     SDValue Ops[] = {
7131       Chain,
7132       VData,
7133       Op.getOperand(3), // rsrc
7134       Op.getOperand(4), // vindex
7135       SDValue(), // voffset -- will be set by setBufferOffsets
7136       SDValue(), // soffset -- will be set by setBufferOffsets
7137       SDValue(), // offset -- will be set by setBufferOffsets
7138       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7139       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7140     };
7141     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7142     // We don't know the offset if vindex is non-zero, so clear it.
7143     if (IdxEn)
7144       Offset = 0;
7145     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7146                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7147     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7148     MemSDNode *M = cast<MemSDNode>(Op);
7149     M->getMemOperand()->setOffset(Offset);
7150 
7151     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7152     EVT VDataType = VData.getValueType().getScalarType();
7153     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7154       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7155 
7156     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7157                                    M->getMemoryVT(), M->getMemOperand());
7158   }
7159 
7160   case Intrinsic::amdgcn_raw_buffer_store:
7161   case Intrinsic::amdgcn_raw_buffer_store_format: {
7162     const bool IsFormat =
7163         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7164 
7165     SDValue VData = Op.getOperand(2);
7166     EVT VDataVT = VData.getValueType();
7167     EVT EltType = VDataVT.getScalarType();
7168     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7169     if (IsD16)
7170       VData = handleD16VData(VData, DAG);
7171 
7172     if (!isTypeLegal(VDataVT)) {
7173       VData =
7174           DAG.getNode(ISD::BITCAST, DL,
7175                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7176     }
7177 
7178     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7179     SDValue Ops[] = {
7180       Chain,
7181       VData,
7182       Op.getOperand(3), // rsrc
7183       DAG.getConstant(0, DL, MVT::i32), // vindex
7184       Offsets.first,    // voffset
7185       Op.getOperand(5), // soffset
7186       Offsets.second,   // offset
7187       Op.getOperand(6), // cachepolicy, swizzled buffer
7188       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7189     };
7190     unsigned Opc =
7191         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7192     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7193     MemSDNode *M = cast<MemSDNode>(Op);
7194     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7195 
7196     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7197     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7198       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7199 
7200     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7201                                    M->getMemoryVT(), M->getMemOperand());
7202   }
7203 
7204   case Intrinsic::amdgcn_struct_buffer_store:
7205   case Intrinsic::amdgcn_struct_buffer_store_format: {
7206     const bool IsFormat =
7207         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7208 
7209     SDValue VData = Op.getOperand(2);
7210     EVT VDataVT = VData.getValueType();
7211     EVT EltType = VDataVT.getScalarType();
7212     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7213 
7214     if (IsD16)
7215       VData = handleD16VData(VData, DAG);
7216 
7217     if (!isTypeLegal(VDataVT)) {
7218       VData =
7219           DAG.getNode(ISD::BITCAST, DL,
7220                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7221     }
7222 
7223     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7224     SDValue Ops[] = {
7225       Chain,
7226       VData,
7227       Op.getOperand(3), // rsrc
7228       Op.getOperand(4), // vindex
7229       Offsets.first,    // voffset
7230       Op.getOperand(6), // soffset
7231       Offsets.second,   // offset
7232       Op.getOperand(7), // cachepolicy, swizzled buffer
7233       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7234     };
7235     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7236                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7237     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7238     MemSDNode *M = cast<MemSDNode>(Op);
7239     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7240                                                         Ops[3]));
7241 
7242     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7243     EVT VDataType = VData.getValueType().getScalarType();
7244     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7245       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7246 
7247     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7248                                    M->getMemoryVT(), M->getMemOperand());
7249   }
7250 
7251   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7252     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7253     unsigned IdxEn = 1;
7254     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7255       IdxEn = Idx->getZExtValue() != 0;
7256     SDValue Ops[] = {
7257       Chain,
7258       Op.getOperand(2), // vdata
7259       Op.getOperand(3), // rsrc
7260       Op.getOperand(4), // vindex
7261       SDValue(),        // voffset -- will be set by setBufferOffsets
7262       SDValue(),        // soffset -- will be set by setBufferOffsets
7263       SDValue(),        // offset -- will be set by setBufferOffsets
7264       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7265       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7266     };
7267     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7268     // We don't know the offset if vindex is non-zero, so clear it.
7269     if (IdxEn)
7270       Offset = 0;
7271     EVT VT = Op.getOperand(2).getValueType();
7272 
7273     auto *M = cast<MemSDNode>(Op);
7274     M->getMemOperand()->setOffset(Offset);
7275     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7276                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7277 
7278     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7279                                    M->getMemOperand());
7280   }
7281 
7282   case Intrinsic::amdgcn_global_atomic_fadd: {
7283     SDValue Ops[] = {
7284       Chain,
7285       Op.getOperand(2), // ptr
7286       Op.getOperand(3)  // vdata
7287     };
7288     EVT VT = Op.getOperand(3).getValueType();
7289 
7290     auto *M = cast<MemSDNode>(Op);
7291     if (VT.isVector()) {
7292       return DAG.getMemIntrinsicNode(
7293         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7294         M->getMemOperand());
7295     }
7296 
7297     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7298                          DAG.getVTList(VT, MVT::Other), Ops,
7299                          M->getMemOperand()).getValue(1);
7300   }
7301   case Intrinsic::amdgcn_end_cf:
7302     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7303                                       Op->getOperand(2), Chain), 0);
7304 
7305   default: {
7306     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7307             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7308       return lowerImage(Op, ImageDimIntr, DAG);
7309 
7310     return Op;
7311   }
7312   }
7313 }
7314 
7315 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7316 // offset (the offset that is included in bounds checking and swizzling, to be
7317 // split between the instruction's voffset and immoffset fields) and soffset
7318 // (the offset that is excluded from bounds checking and swizzling, to go in
7319 // the instruction's soffset field).  This function takes the first kind of
7320 // offset and figures out how to split it between voffset and immoffset.
7321 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7322     SDValue Offset, SelectionDAG &DAG) const {
7323   SDLoc DL(Offset);
7324   const unsigned MaxImm = 4095;
7325   SDValue N0 = Offset;
7326   ConstantSDNode *C1 = nullptr;
7327 
7328   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7329     N0 = SDValue();
7330   else if (DAG.isBaseWithConstantOffset(N0)) {
7331     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7332     N0 = N0.getOperand(0);
7333   }
7334 
7335   if (C1) {
7336     unsigned ImmOffset = C1->getZExtValue();
7337     // If the immediate value is too big for the immoffset field, put the value
7338     // and -4096 into the immoffset field so that the value that is copied/added
7339     // for the voffset field is a multiple of 4096, and it stands more chance
7340     // of being CSEd with the copy/add for another similar load/store.
7341     // However, do not do that rounding down to a multiple of 4096 if that is a
7342     // negative number, as it appears to be illegal to have a negative offset
7343     // in the vgpr, even if adding the immediate offset makes it positive.
7344     unsigned Overflow = ImmOffset & ~MaxImm;
7345     ImmOffset -= Overflow;
7346     if ((int32_t)Overflow < 0) {
7347       Overflow += ImmOffset;
7348       ImmOffset = 0;
7349     }
7350     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7351     if (Overflow) {
7352       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7353       if (!N0)
7354         N0 = OverflowVal;
7355       else {
7356         SDValue Ops[] = { N0, OverflowVal };
7357         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7358       }
7359     }
7360   }
7361   if (!N0)
7362     N0 = DAG.getConstant(0, DL, MVT::i32);
7363   if (!C1)
7364     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7365   return {N0, SDValue(C1, 0)};
7366 }
7367 
7368 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7369 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7370 // pointed to by Offsets.
7371 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7372                                         SelectionDAG &DAG, SDValue *Offsets,
7373                                         unsigned Align) const {
7374   SDLoc DL(CombinedOffset);
7375   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7376     uint32_t Imm = C->getZExtValue();
7377     uint32_t SOffset, ImmOffset;
7378     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7379       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7380       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7381       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7382       return SOffset + ImmOffset;
7383     }
7384   }
7385   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7386     SDValue N0 = CombinedOffset.getOperand(0);
7387     SDValue N1 = CombinedOffset.getOperand(1);
7388     uint32_t SOffset, ImmOffset;
7389     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7390     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7391                                                 Subtarget, Align)) {
7392       Offsets[0] = N0;
7393       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7394       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7395       return 0;
7396     }
7397   }
7398   Offsets[0] = CombinedOffset;
7399   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7400   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7401   return 0;
7402 }
7403 
7404 // Handle 8 bit and 16 bit buffer loads
7405 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7406                                                      EVT LoadVT, SDLoc DL,
7407                                                      ArrayRef<SDValue> Ops,
7408                                                      MemSDNode *M) const {
7409   EVT IntVT = LoadVT.changeTypeToInteger();
7410   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7411          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7412 
7413   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7414   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7415                                                Ops, IntVT,
7416                                                M->getMemOperand());
7417   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7418   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7419 
7420   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7421 }
7422 
7423 // Handle 8 bit and 16 bit buffer stores
7424 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7425                                                       EVT VDataType, SDLoc DL,
7426                                                       SDValue Ops[],
7427                                                       MemSDNode *M) const {
7428   if (VDataType == MVT::f16)
7429     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7430 
7431   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7432   Ops[1] = BufferStoreExt;
7433   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7434                                  AMDGPUISD::BUFFER_STORE_SHORT;
7435   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7436   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7437                                      M->getMemOperand());
7438 }
7439 
7440 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7441                                  ISD::LoadExtType ExtType, SDValue Op,
7442                                  const SDLoc &SL, EVT VT) {
7443   if (VT.bitsLT(Op.getValueType()))
7444     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7445 
7446   switch (ExtType) {
7447   case ISD::SEXTLOAD:
7448     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7449   case ISD::ZEXTLOAD:
7450     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7451   case ISD::EXTLOAD:
7452     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7453   case ISD::NON_EXTLOAD:
7454     return Op;
7455   }
7456 
7457   llvm_unreachable("invalid ext type");
7458 }
7459 
7460 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7461   SelectionDAG &DAG = DCI.DAG;
7462   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7463     return SDValue();
7464 
7465   // FIXME: Constant loads should all be marked invariant.
7466   unsigned AS = Ld->getAddressSpace();
7467   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7468       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7469       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7470     return SDValue();
7471 
7472   // Don't do this early, since it may interfere with adjacent load merging for
7473   // illegal types. We can avoid losing alignment information for exotic types
7474   // pre-legalize.
7475   EVT MemVT = Ld->getMemoryVT();
7476   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7477       MemVT.getSizeInBits() >= 32)
7478     return SDValue();
7479 
7480   SDLoc SL(Ld);
7481 
7482   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7483          "unexpected vector extload");
7484 
7485   // TODO: Drop only high part of range.
7486   SDValue Ptr = Ld->getBasePtr();
7487   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7488                                 MVT::i32, SL, Ld->getChain(), Ptr,
7489                                 Ld->getOffset(),
7490                                 Ld->getPointerInfo(), MVT::i32,
7491                                 Ld->getAlignment(),
7492                                 Ld->getMemOperand()->getFlags(),
7493                                 Ld->getAAInfo(),
7494                                 nullptr); // Drop ranges
7495 
7496   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7497   if (MemVT.isFloatingPoint()) {
7498     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7499            "unexpected fp extload");
7500     TruncVT = MemVT.changeTypeToInteger();
7501   }
7502 
7503   SDValue Cvt = NewLoad;
7504   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7505     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7506                       DAG.getValueType(TruncVT));
7507   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7508              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7509     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7510   } else {
7511     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7512   }
7513 
7514   EVT VT = Ld->getValueType(0);
7515   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7516 
7517   DCI.AddToWorklist(Cvt.getNode());
7518 
7519   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7520   // the appropriate extension from the 32-bit load.
7521   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7522   DCI.AddToWorklist(Cvt.getNode());
7523 
7524   // Handle conversion back to floating point if necessary.
7525   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7526 
7527   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7528 }
7529 
7530 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7531   SDLoc DL(Op);
7532   LoadSDNode *Load = cast<LoadSDNode>(Op);
7533   ISD::LoadExtType ExtType = Load->getExtensionType();
7534   EVT MemVT = Load->getMemoryVT();
7535 
7536   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7537     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7538       return SDValue();
7539 
7540     // FIXME: Copied from PPC
7541     // First, load into 32 bits, then truncate to 1 bit.
7542 
7543     SDValue Chain = Load->getChain();
7544     SDValue BasePtr = Load->getBasePtr();
7545     MachineMemOperand *MMO = Load->getMemOperand();
7546 
7547     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7548 
7549     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7550                                    BasePtr, RealMemVT, MMO);
7551 
7552     if (!MemVT.isVector()) {
7553       SDValue Ops[] = {
7554         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7555         NewLD.getValue(1)
7556       };
7557 
7558       return DAG.getMergeValues(Ops, DL);
7559     }
7560 
7561     SmallVector<SDValue, 3> Elts;
7562     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7563       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7564                                 DAG.getConstant(I, DL, MVT::i32));
7565 
7566       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7567     }
7568 
7569     SDValue Ops[] = {
7570       DAG.getBuildVector(MemVT, DL, Elts),
7571       NewLD.getValue(1)
7572     };
7573 
7574     return DAG.getMergeValues(Ops, DL);
7575   }
7576 
7577   if (!MemVT.isVector())
7578     return SDValue();
7579 
7580   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7581          "Custom lowering for non-i32 vectors hasn't been implemented.");
7582 
7583   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7584                                       MemVT, *Load->getMemOperand())) {
7585     SDValue Ops[2];
7586     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7587     return DAG.getMergeValues(Ops, DL);
7588   }
7589 
7590   unsigned Alignment = Load->getAlignment();
7591   unsigned AS = Load->getAddressSpace();
7592   if (Subtarget->hasLDSMisalignedBug() &&
7593       AS == AMDGPUAS::FLAT_ADDRESS &&
7594       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7595     return SplitVectorLoad(Op, DAG);
7596   }
7597 
7598   MachineFunction &MF = DAG.getMachineFunction();
7599   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7600   // If there is a possibilty that flat instruction access scratch memory
7601   // then we need to use the same legalization rules we use for private.
7602   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7603       !Subtarget->hasMultiDwordFlatScratchAddressing())
7604     AS = MFI->hasFlatScratchInit() ?
7605          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7606 
7607   unsigned NumElements = MemVT.getVectorNumElements();
7608 
7609   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7610       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7611     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7612       if (MemVT.isPow2VectorType())
7613         return SDValue();
7614       if (NumElements == 3)
7615         return WidenVectorLoad(Op, DAG);
7616       return SplitVectorLoad(Op, DAG);
7617     }
7618     // Non-uniform loads will be selected to MUBUF instructions, so they
7619     // have the same legalization requirements as global and private
7620     // loads.
7621     //
7622   }
7623 
7624   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7625       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7626       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7627     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7628         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7629         Alignment >= 4 && NumElements < 32) {
7630       if (MemVT.isPow2VectorType())
7631         return SDValue();
7632       if (NumElements == 3)
7633         return WidenVectorLoad(Op, DAG);
7634       return SplitVectorLoad(Op, DAG);
7635     }
7636     // Non-uniform loads will be selected to MUBUF instructions, so they
7637     // have the same legalization requirements as global and private
7638     // loads.
7639     //
7640   }
7641   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7642       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7643       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7644       AS == AMDGPUAS::FLAT_ADDRESS) {
7645     if (NumElements > 4)
7646       return SplitVectorLoad(Op, DAG);
7647     // v3 loads not supported on SI.
7648     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7649       return WidenVectorLoad(Op, DAG);
7650     // v3 and v4 loads are supported for private and global memory.
7651     return SDValue();
7652   }
7653   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7654     // Depending on the setting of the private_element_size field in the
7655     // resource descriptor, we can only make private accesses up to a certain
7656     // size.
7657     switch (Subtarget->getMaxPrivateElementSize()) {
7658     case 4: {
7659       SDValue Ops[2];
7660       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7661       return DAG.getMergeValues(Ops, DL);
7662     }
7663     case 8:
7664       if (NumElements > 2)
7665         return SplitVectorLoad(Op, DAG);
7666       return SDValue();
7667     case 16:
7668       // Same as global/flat
7669       if (NumElements > 4)
7670         return SplitVectorLoad(Op, DAG);
7671       // v3 loads not supported on SI.
7672       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7673         return WidenVectorLoad(Op, DAG);
7674       return SDValue();
7675     default:
7676       llvm_unreachable("unsupported private_element_size");
7677     }
7678   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7679     // Use ds_read_b128 if possible.
7680     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7681         MemVT.getStoreSize() == 16)
7682       return SDValue();
7683 
7684     if (NumElements > 2)
7685       return SplitVectorLoad(Op, DAG);
7686 
7687     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7688     // address is negative, then the instruction is incorrectly treated as
7689     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7690     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7691     // load later in the SILoadStoreOptimizer.
7692     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7693         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7694         Load->getAlignment() < 8) {
7695       return SplitVectorLoad(Op, DAG);
7696     }
7697   }
7698   return SDValue();
7699 }
7700 
7701 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7702   EVT VT = Op.getValueType();
7703   assert(VT.getSizeInBits() == 64);
7704 
7705   SDLoc DL(Op);
7706   SDValue Cond = Op.getOperand(0);
7707 
7708   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7709   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7710 
7711   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7712   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7713 
7714   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7715   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7716 
7717   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7718 
7719   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7720   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7721 
7722   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7723 
7724   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7725   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7726 }
7727 
7728 // Catch division cases where we can use shortcuts with rcp and rsq
7729 // instructions.
7730 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7731                                               SelectionDAG &DAG) const {
7732   SDLoc SL(Op);
7733   SDValue LHS = Op.getOperand(0);
7734   SDValue RHS = Op.getOperand(1);
7735   EVT VT = Op.getValueType();
7736   const SDNodeFlags Flags = Op->getFlags();
7737 
7738   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7739                             Flags.hasApproximateFuncs();
7740 
7741   // Without !fpmath accuracy information, we can't do more because we don't
7742   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7743   if (!AllowInaccurateRcp)
7744     return SDValue();
7745 
7746   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7747     if (CLHS->isExactlyValue(1.0)) {
7748       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7749       // the CI documentation has a worst case error of 1 ulp.
7750       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7751       // use it as long as we aren't trying to use denormals.
7752       //
7753       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7754 
7755       // 1.0 / sqrt(x) -> rsq(x)
7756 
7757       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7758       // error seems really high at 2^29 ULP.
7759       if (RHS.getOpcode() == ISD::FSQRT)
7760         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7761 
7762       // 1.0 / x -> rcp(x)
7763       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7764     }
7765 
7766     // Same as for 1.0, but expand the sign out of the constant.
7767     if (CLHS->isExactlyValue(-1.0)) {
7768       // -1.0 / x -> rcp (fneg x)
7769       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7770       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7771     }
7772   }
7773 
7774   // Turn into multiply by the reciprocal.
7775   // x / y -> x * (1.0 / y)
7776   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7777   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7778 }
7779 
7780 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7781                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7782   if (GlueChain->getNumValues() <= 1) {
7783     return DAG.getNode(Opcode, SL, VT, A, B);
7784   }
7785 
7786   assert(GlueChain->getNumValues() == 3);
7787 
7788   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7789   switch (Opcode) {
7790   default: llvm_unreachable("no chain equivalent for opcode");
7791   case ISD::FMUL:
7792     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7793     break;
7794   }
7795 
7796   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7797                      GlueChain.getValue(2));
7798 }
7799 
7800 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7801                            EVT VT, SDValue A, SDValue B, SDValue C,
7802                            SDValue GlueChain) {
7803   if (GlueChain->getNumValues() <= 1) {
7804     return DAG.getNode(Opcode, SL, VT, A, B, C);
7805   }
7806 
7807   assert(GlueChain->getNumValues() == 3);
7808 
7809   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7810   switch (Opcode) {
7811   default: llvm_unreachable("no chain equivalent for opcode");
7812   case ISD::FMA:
7813     Opcode = AMDGPUISD::FMA_W_CHAIN;
7814     break;
7815   }
7816 
7817   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7818                      GlueChain.getValue(2));
7819 }
7820 
7821 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7822   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7823     return FastLowered;
7824 
7825   SDLoc SL(Op);
7826   SDValue Src0 = Op.getOperand(0);
7827   SDValue Src1 = Op.getOperand(1);
7828 
7829   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7830   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7831 
7832   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7833   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7834 
7835   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7836   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7837 
7838   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7839 }
7840 
7841 // Faster 2.5 ULP division that does not support denormals.
7842 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7843   SDLoc SL(Op);
7844   SDValue LHS = Op.getOperand(1);
7845   SDValue RHS = Op.getOperand(2);
7846 
7847   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7848 
7849   const APFloat K0Val(BitsToFloat(0x6f800000));
7850   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7851 
7852   const APFloat K1Val(BitsToFloat(0x2f800000));
7853   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7854 
7855   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7856 
7857   EVT SetCCVT =
7858     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7859 
7860   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7861 
7862   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7863 
7864   // TODO: Should this propagate fast-math-flags?
7865   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7866 
7867   // rcp does not support denormals.
7868   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7869 
7870   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7871 
7872   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7873 }
7874 
7875 // Returns immediate value for setting the F32 denorm mode when using the
7876 // S_DENORM_MODE instruction.
7877 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7878                                           const SDLoc &SL, const GCNSubtarget *ST) {
7879   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7880   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7881                                 ? FP_DENORM_FLUSH_NONE
7882                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7883 
7884   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7885   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7886 }
7887 
7888 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7889   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7890     return FastLowered;
7891 
7892   SDLoc SL(Op);
7893   SDValue LHS = Op.getOperand(0);
7894   SDValue RHS = Op.getOperand(1);
7895 
7896   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7897 
7898   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7899 
7900   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7901                                           RHS, RHS, LHS);
7902   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7903                                         LHS, RHS, LHS);
7904 
7905   // Denominator is scaled to not be denormal, so using rcp is ok.
7906   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7907                                   DenominatorScaled);
7908   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7909                                      DenominatorScaled);
7910 
7911   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7912                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7913                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7914   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7915 
7916   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7917 
7918   if (!HasFP32Denormals) {
7919     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7920 
7921     SDValue EnableDenorm;
7922     if (Subtarget->hasDenormModeInst()) {
7923       const SDValue EnableDenormValue =
7924           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7925 
7926       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7927                                  DAG.getEntryNode(), EnableDenormValue);
7928     } else {
7929       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7930                                                         SL, MVT::i32);
7931       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7932                                  DAG.getEntryNode(), EnableDenormValue,
7933                                  BitField);
7934     }
7935 
7936     SDValue Ops[3] = {
7937       NegDivScale0,
7938       EnableDenorm.getValue(0),
7939       EnableDenorm.getValue(1)
7940     };
7941 
7942     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7943   }
7944 
7945   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7946                              ApproxRcp, One, NegDivScale0);
7947 
7948   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7949                              ApproxRcp, Fma0);
7950 
7951   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7952                            Fma1, Fma1);
7953 
7954   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7955                              NumeratorScaled, Mul);
7956 
7957   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7958 
7959   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7960                              NumeratorScaled, Fma3);
7961 
7962   if (!HasFP32Denormals) {
7963     SDValue DisableDenorm;
7964     if (Subtarget->hasDenormModeInst()) {
7965       const SDValue DisableDenormValue =
7966           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7967 
7968       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7969                                   Fma4.getValue(1), DisableDenormValue,
7970                                   Fma4.getValue(2));
7971     } else {
7972       const SDValue DisableDenormValue =
7973           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7974 
7975       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7976                                   Fma4.getValue(1), DisableDenormValue,
7977                                   BitField, Fma4.getValue(2));
7978     }
7979 
7980     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7981                                       DisableDenorm, DAG.getRoot());
7982     DAG.setRoot(OutputChain);
7983   }
7984 
7985   SDValue Scale = NumeratorScaled.getValue(1);
7986   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7987                              Fma4, Fma1, Fma3, Scale);
7988 
7989   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7990 }
7991 
7992 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7993   if (DAG.getTarget().Options.UnsafeFPMath)
7994     return lowerFastUnsafeFDIV(Op, DAG);
7995 
7996   SDLoc SL(Op);
7997   SDValue X = Op.getOperand(0);
7998   SDValue Y = Op.getOperand(1);
7999 
8000   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8001 
8002   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8003 
8004   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8005 
8006   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8007 
8008   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8009 
8010   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8011 
8012   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8013 
8014   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8015 
8016   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8017 
8018   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8019   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8020 
8021   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8022                              NegDivScale0, Mul, DivScale1);
8023 
8024   SDValue Scale;
8025 
8026   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8027     // Workaround a hardware bug on SI where the condition output from div_scale
8028     // is not usable.
8029 
8030     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8031 
8032     // Figure out if the scale to use for div_fmas.
8033     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8034     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8035     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8036     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8037 
8038     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8039     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8040 
8041     SDValue Scale0Hi
8042       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8043     SDValue Scale1Hi
8044       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8045 
8046     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8047     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8048     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8049   } else {
8050     Scale = DivScale1.getValue(1);
8051   }
8052 
8053   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8054                              Fma4, Fma3, Mul, Scale);
8055 
8056   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8057 }
8058 
8059 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8060   EVT VT = Op.getValueType();
8061 
8062   if (VT == MVT::f32)
8063     return LowerFDIV32(Op, DAG);
8064 
8065   if (VT == MVT::f64)
8066     return LowerFDIV64(Op, DAG);
8067 
8068   if (VT == MVT::f16)
8069     return LowerFDIV16(Op, DAG);
8070 
8071   llvm_unreachable("Unexpected type for fdiv");
8072 }
8073 
8074 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8075   SDLoc DL(Op);
8076   StoreSDNode *Store = cast<StoreSDNode>(Op);
8077   EVT VT = Store->getMemoryVT();
8078 
8079   if (VT == MVT::i1) {
8080     return DAG.getTruncStore(Store->getChain(), DL,
8081        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8082        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8083   }
8084 
8085   assert(VT.isVector() &&
8086          Store->getValue().getValueType().getScalarType() == MVT::i32);
8087 
8088   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8089                                       VT, *Store->getMemOperand())) {
8090     return expandUnalignedStore(Store, DAG);
8091   }
8092 
8093   unsigned AS = Store->getAddressSpace();
8094   if (Subtarget->hasLDSMisalignedBug() &&
8095       AS == AMDGPUAS::FLAT_ADDRESS &&
8096       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8097     return SplitVectorStore(Op, DAG);
8098   }
8099 
8100   MachineFunction &MF = DAG.getMachineFunction();
8101   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8102   // If there is a possibilty that flat instruction access scratch memory
8103   // then we need to use the same legalization rules we use for private.
8104   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8105       !Subtarget->hasMultiDwordFlatScratchAddressing())
8106     AS = MFI->hasFlatScratchInit() ?
8107          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8108 
8109   unsigned NumElements = VT.getVectorNumElements();
8110   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8111       AS == AMDGPUAS::FLAT_ADDRESS) {
8112     if (NumElements > 4)
8113       return SplitVectorStore(Op, DAG);
8114     // v3 stores not supported on SI.
8115     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8116       return SplitVectorStore(Op, DAG);
8117     return SDValue();
8118   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8119     switch (Subtarget->getMaxPrivateElementSize()) {
8120     case 4:
8121       return scalarizeVectorStore(Store, DAG);
8122     case 8:
8123       if (NumElements > 2)
8124         return SplitVectorStore(Op, DAG);
8125       return SDValue();
8126     case 16:
8127       if (NumElements > 4 || NumElements == 3)
8128         return SplitVectorStore(Op, DAG);
8129       return SDValue();
8130     default:
8131       llvm_unreachable("unsupported private_element_size");
8132     }
8133   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8134     // Use ds_write_b128 if possible.
8135     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8136         VT.getStoreSize() == 16 && NumElements != 3)
8137       return SDValue();
8138 
8139     if (NumElements > 2)
8140       return SplitVectorStore(Op, DAG);
8141 
8142     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8143     // address is negative, then the instruction is incorrectly treated as
8144     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8145     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8146     // store later in the SILoadStoreOptimizer.
8147     if (!Subtarget->hasUsableDSOffset() &&
8148         NumElements == 2 && VT.getStoreSize() == 8 &&
8149         Store->getAlignment() < 8) {
8150       return SplitVectorStore(Op, DAG);
8151     }
8152 
8153     return SDValue();
8154   } else {
8155     llvm_unreachable("unhandled address space");
8156   }
8157 }
8158 
8159 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8160   SDLoc DL(Op);
8161   EVT VT = Op.getValueType();
8162   SDValue Arg = Op.getOperand(0);
8163   SDValue TrigVal;
8164 
8165   // TODO: Should this propagate fast-math-flags?
8166 
8167   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
8168 
8169   if (Subtarget->hasTrigReducedRange()) {
8170     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8171     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
8172   } else {
8173     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8174   }
8175 
8176   switch (Op.getOpcode()) {
8177   case ISD::FCOS:
8178     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
8179   case ISD::FSIN:
8180     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
8181   default:
8182     llvm_unreachable("Wrong trig opcode");
8183   }
8184 }
8185 
8186 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8187   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8188   assert(AtomicNode->isCompareAndSwap());
8189   unsigned AS = AtomicNode->getAddressSpace();
8190 
8191   // No custom lowering required for local address space
8192   if (!isFlatGlobalAddrSpace(AS))
8193     return Op;
8194 
8195   // Non-local address space requires custom lowering for atomic compare
8196   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8197   SDLoc DL(Op);
8198   SDValue ChainIn = Op.getOperand(0);
8199   SDValue Addr = Op.getOperand(1);
8200   SDValue Old = Op.getOperand(2);
8201   SDValue New = Op.getOperand(3);
8202   EVT VT = Op.getValueType();
8203   MVT SimpleVT = VT.getSimpleVT();
8204   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8205 
8206   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8207   SDValue Ops[] = { ChainIn, Addr, NewOld };
8208 
8209   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8210                                  Ops, VT, AtomicNode->getMemOperand());
8211 }
8212 
8213 //===----------------------------------------------------------------------===//
8214 // Custom DAG optimizations
8215 //===----------------------------------------------------------------------===//
8216 
8217 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8218                                                      DAGCombinerInfo &DCI) const {
8219   EVT VT = N->getValueType(0);
8220   EVT ScalarVT = VT.getScalarType();
8221   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8222     return SDValue();
8223 
8224   SelectionDAG &DAG = DCI.DAG;
8225   SDLoc DL(N);
8226 
8227   SDValue Src = N->getOperand(0);
8228   EVT SrcVT = Src.getValueType();
8229 
8230   // TODO: We could try to match extracting the higher bytes, which would be
8231   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8232   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8233   // about in practice.
8234   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8235     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8236       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8237       DCI.AddToWorklist(Cvt.getNode());
8238 
8239       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8240       if (ScalarVT != MVT::f32) {
8241         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8242                           DAG.getTargetConstant(0, DL, MVT::i32));
8243       }
8244       return Cvt;
8245     }
8246   }
8247 
8248   return SDValue();
8249 }
8250 
8251 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8252 
8253 // This is a variant of
8254 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8255 //
8256 // The normal DAG combiner will do this, but only if the add has one use since
8257 // that would increase the number of instructions.
8258 //
8259 // This prevents us from seeing a constant offset that can be folded into a
8260 // memory instruction's addressing mode. If we know the resulting add offset of
8261 // a pointer can be folded into an addressing offset, we can replace the pointer
8262 // operand with the add of new constant offset. This eliminates one of the uses,
8263 // and may allow the remaining use to also be simplified.
8264 //
8265 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8266                                                unsigned AddrSpace,
8267                                                EVT MemVT,
8268                                                DAGCombinerInfo &DCI) const {
8269   SDValue N0 = N->getOperand(0);
8270   SDValue N1 = N->getOperand(1);
8271 
8272   // We only do this to handle cases where it's profitable when there are
8273   // multiple uses of the add, so defer to the standard combine.
8274   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8275       N0->hasOneUse())
8276     return SDValue();
8277 
8278   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8279   if (!CN1)
8280     return SDValue();
8281 
8282   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8283   if (!CAdd)
8284     return SDValue();
8285 
8286   // If the resulting offset is too large, we can't fold it into the addressing
8287   // mode offset.
8288   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8289   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8290 
8291   AddrMode AM;
8292   AM.HasBaseReg = true;
8293   AM.BaseOffs = Offset.getSExtValue();
8294   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8295     return SDValue();
8296 
8297   SelectionDAG &DAG = DCI.DAG;
8298   SDLoc SL(N);
8299   EVT VT = N->getValueType(0);
8300 
8301   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8302   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8303 
8304   SDNodeFlags Flags;
8305   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8306                           (N0.getOpcode() == ISD::OR ||
8307                            N0->getFlags().hasNoUnsignedWrap()));
8308 
8309   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8310 }
8311 
8312 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8313                                                   DAGCombinerInfo &DCI) const {
8314   SDValue Ptr = N->getBasePtr();
8315   SelectionDAG &DAG = DCI.DAG;
8316   SDLoc SL(N);
8317 
8318   // TODO: We could also do this for multiplies.
8319   if (Ptr.getOpcode() == ISD::SHL) {
8320     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8321                                           N->getMemoryVT(), DCI);
8322     if (NewPtr) {
8323       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8324 
8325       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8326       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8327     }
8328   }
8329 
8330   return SDValue();
8331 }
8332 
8333 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8334   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8335          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8336          (Opc == ISD::XOR && Val == 0);
8337 }
8338 
8339 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8340 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8341 // integer combine opportunities since most 64-bit operations are decomposed
8342 // this way.  TODO: We won't want this for SALU especially if it is an inline
8343 // immediate.
8344 SDValue SITargetLowering::splitBinaryBitConstantOp(
8345   DAGCombinerInfo &DCI,
8346   const SDLoc &SL,
8347   unsigned Opc, SDValue LHS,
8348   const ConstantSDNode *CRHS) const {
8349   uint64_t Val = CRHS->getZExtValue();
8350   uint32_t ValLo = Lo_32(Val);
8351   uint32_t ValHi = Hi_32(Val);
8352   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8353 
8354     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8355          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8356         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8357     // If we need to materialize a 64-bit immediate, it will be split up later
8358     // anyway. Avoid creating the harder to understand 64-bit immediate
8359     // materialization.
8360     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8361   }
8362 
8363   return SDValue();
8364 }
8365 
8366 // Returns true if argument is a boolean value which is not serialized into
8367 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8368 static bool isBoolSGPR(SDValue V) {
8369   if (V.getValueType() != MVT::i1)
8370     return false;
8371   switch (V.getOpcode()) {
8372   default: break;
8373   case ISD::SETCC:
8374   case ISD::AND:
8375   case ISD::OR:
8376   case ISD::XOR:
8377   case AMDGPUISD::FP_CLASS:
8378     return true;
8379   }
8380   return false;
8381 }
8382 
8383 // If a constant has all zeroes or all ones within each byte return it.
8384 // Otherwise return 0.
8385 static uint32_t getConstantPermuteMask(uint32_t C) {
8386   // 0xff for any zero byte in the mask
8387   uint32_t ZeroByteMask = 0;
8388   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8389   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8390   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8391   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8392   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8393   if ((NonZeroByteMask & C) != NonZeroByteMask)
8394     return 0; // Partial bytes selected.
8395   return C;
8396 }
8397 
8398 // Check if a node selects whole bytes from its operand 0 starting at a byte
8399 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8400 // or -1 if not succeeded.
8401 // Note byte select encoding:
8402 // value 0-3 selects corresponding source byte;
8403 // value 0xc selects zero;
8404 // value 0xff selects 0xff.
8405 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8406   assert(V.getValueSizeInBits() == 32);
8407 
8408   if (V.getNumOperands() != 2)
8409     return ~0;
8410 
8411   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8412   if (!N1)
8413     return ~0;
8414 
8415   uint32_t C = N1->getZExtValue();
8416 
8417   switch (V.getOpcode()) {
8418   default:
8419     break;
8420   case ISD::AND:
8421     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8422       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8423     }
8424     break;
8425 
8426   case ISD::OR:
8427     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8428       return (0x03020100 & ~ConstMask) | ConstMask;
8429     }
8430     break;
8431 
8432   case ISD::SHL:
8433     if (C % 8)
8434       return ~0;
8435 
8436     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8437 
8438   case ISD::SRL:
8439     if (C % 8)
8440       return ~0;
8441 
8442     return uint32_t(0x0c0c0c0c03020100ull >> C);
8443   }
8444 
8445   return ~0;
8446 }
8447 
8448 SDValue SITargetLowering::performAndCombine(SDNode *N,
8449                                             DAGCombinerInfo &DCI) const {
8450   if (DCI.isBeforeLegalize())
8451     return SDValue();
8452 
8453   SelectionDAG &DAG = DCI.DAG;
8454   EVT VT = N->getValueType(0);
8455   SDValue LHS = N->getOperand(0);
8456   SDValue RHS = N->getOperand(1);
8457 
8458 
8459   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8460   if (VT == MVT::i64 && CRHS) {
8461     if (SDValue Split
8462         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8463       return Split;
8464   }
8465 
8466   if (CRHS && VT == MVT::i32) {
8467     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8468     // nb = number of trailing zeroes in mask
8469     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8470     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8471     uint64_t Mask = CRHS->getZExtValue();
8472     unsigned Bits = countPopulation(Mask);
8473     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8474         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8475       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8476         unsigned Shift = CShift->getZExtValue();
8477         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8478         unsigned Offset = NB + Shift;
8479         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8480           SDLoc SL(N);
8481           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8482                                     LHS->getOperand(0),
8483                                     DAG.getConstant(Offset, SL, MVT::i32),
8484                                     DAG.getConstant(Bits, SL, MVT::i32));
8485           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8486           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8487                                     DAG.getValueType(NarrowVT));
8488           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8489                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8490           return Shl;
8491         }
8492       }
8493     }
8494 
8495     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8496     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8497         isa<ConstantSDNode>(LHS.getOperand(2))) {
8498       uint32_t Sel = getConstantPermuteMask(Mask);
8499       if (!Sel)
8500         return SDValue();
8501 
8502       // Select 0xc for all zero bytes
8503       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8504       SDLoc DL(N);
8505       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8506                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8507     }
8508   }
8509 
8510   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8511   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8512   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8513     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8514     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8515 
8516     SDValue X = LHS.getOperand(0);
8517     SDValue Y = RHS.getOperand(0);
8518     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8519       return SDValue();
8520 
8521     if (LCC == ISD::SETO) {
8522       if (X != LHS.getOperand(1))
8523         return SDValue();
8524 
8525       if (RCC == ISD::SETUNE) {
8526         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8527         if (!C1 || !C1->isInfinity() || C1->isNegative())
8528           return SDValue();
8529 
8530         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8531                               SIInstrFlags::N_SUBNORMAL |
8532                               SIInstrFlags::N_ZERO |
8533                               SIInstrFlags::P_ZERO |
8534                               SIInstrFlags::P_SUBNORMAL |
8535                               SIInstrFlags::P_NORMAL;
8536 
8537         static_assert(((~(SIInstrFlags::S_NAN |
8538                           SIInstrFlags::Q_NAN |
8539                           SIInstrFlags::N_INFINITY |
8540                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8541                       "mask not equal");
8542 
8543         SDLoc DL(N);
8544         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8545                            X, DAG.getConstant(Mask, DL, MVT::i32));
8546       }
8547     }
8548   }
8549 
8550   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8551     std::swap(LHS, RHS);
8552 
8553   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8554       RHS.hasOneUse()) {
8555     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8556     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8557     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8558     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8559     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8560         (RHS.getOperand(0) == LHS.getOperand(0) &&
8561          LHS.getOperand(0) == LHS.getOperand(1))) {
8562       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8563       unsigned NewMask = LCC == ISD::SETO ?
8564         Mask->getZExtValue() & ~OrdMask :
8565         Mask->getZExtValue() & OrdMask;
8566 
8567       SDLoc DL(N);
8568       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8569                          DAG.getConstant(NewMask, DL, MVT::i32));
8570     }
8571   }
8572 
8573   if (VT == MVT::i32 &&
8574       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8575     // and x, (sext cc from i1) => select cc, x, 0
8576     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8577       std::swap(LHS, RHS);
8578     if (isBoolSGPR(RHS.getOperand(0)))
8579       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8580                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8581   }
8582 
8583   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8584   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8585   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8586       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8587     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8588     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8589     if (LHSMask != ~0u && RHSMask != ~0u) {
8590       // Canonicalize the expression in an attempt to have fewer unique masks
8591       // and therefore fewer registers used to hold the masks.
8592       if (LHSMask > RHSMask) {
8593         std::swap(LHSMask, RHSMask);
8594         std::swap(LHS, RHS);
8595       }
8596 
8597       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8598       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8599       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8600       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8601 
8602       // Check of we need to combine values from two sources within a byte.
8603       if (!(LHSUsedLanes & RHSUsedLanes) &&
8604           // If we select high and lower word keep it for SDWA.
8605           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8606           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8607         // Each byte in each mask is either selector mask 0-3, or has higher
8608         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8609         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8610         // mask which is not 0xff wins. By anding both masks we have a correct
8611         // result except that 0x0c shall be corrected to give 0x0c only.
8612         uint32_t Mask = LHSMask & RHSMask;
8613         for (unsigned I = 0; I < 32; I += 8) {
8614           uint32_t ByteSel = 0xff << I;
8615           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8616             Mask &= (0x0c << I) & 0xffffffff;
8617         }
8618 
8619         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8620         // or 0x0c.
8621         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8622         SDLoc DL(N);
8623 
8624         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8625                            LHS.getOperand(0), RHS.getOperand(0),
8626                            DAG.getConstant(Sel, DL, MVT::i32));
8627       }
8628     }
8629   }
8630 
8631   return SDValue();
8632 }
8633 
8634 SDValue SITargetLowering::performOrCombine(SDNode *N,
8635                                            DAGCombinerInfo &DCI) const {
8636   SelectionDAG &DAG = DCI.DAG;
8637   SDValue LHS = N->getOperand(0);
8638   SDValue RHS = N->getOperand(1);
8639 
8640   EVT VT = N->getValueType(0);
8641   if (VT == MVT::i1) {
8642     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8643     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8644         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8645       SDValue Src = LHS.getOperand(0);
8646       if (Src != RHS.getOperand(0))
8647         return SDValue();
8648 
8649       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8650       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8651       if (!CLHS || !CRHS)
8652         return SDValue();
8653 
8654       // Only 10 bits are used.
8655       static const uint32_t MaxMask = 0x3ff;
8656 
8657       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8658       SDLoc DL(N);
8659       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8660                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8661     }
8662 
8663     return SDValue();
8664   }
8665 
8666   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8667   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8668       LHS.getOpcode() == AMDGPUISD::PERM &&
8669       isa<ConstantSDNode>(LHS.getOperand(2))) {
8670     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8671     if (!Sel)
8672       return SDValue();
8673 
8674     Sel |= LHS.getConstantOperandVal(2);
8675     SDLoc DL(N);
8676     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8677                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8678   }
8679 
8680   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8681   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8682   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8683       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8684     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8685     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8686     if (LHSMask != ~0u && RHSMask != ~0u) {
8687       // Canonicalize the expression in an attempt to have fewer unique masks
8688       // and therefore fewer registers used to hold the masks.
8689       if (LHSMask > RHSMask) {
8690         std::swap(LHSMask, RHSMask);
8691         std::swap(LHS, RHS);
8692       }
8693 
8694       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8695       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8696       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8697       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8698 
8699       // Check of we need to combine values from two sources within a byte.
8700       if (!(LHSUsedLanes & RHSUsedLanes) &&
8701           // If we select high and lower word keep it for SDWA.
8702           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8703           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8704         // Kill zero bytes selected by other mask. Zero value is 0xc.
8705         LHSMask &= ~RHSUsedLanes;
8706         RHSMask &= ~LHSUsedLanes;
8707         // Add 4 to each active LHS lane
8708         LHSMask |= LHSUsedLanes & 0x04040404;
8709         // Combine masks
8710         uint32_t Sel = LHSMask | RHSMask;
8711         SDLoc DL(N);
8712 
8713         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8714                            LHS.getOperand(0), RHS.getOperand(0),
8715                            DAG.getConstant(Sel, DL, MVT::i32));
8716       }
8717     }
8718   }
8719 
8720   if (VT != MVT::i64)
8721     return SDValue();
8722 
8723   // TODO: This could be a generic combine with a predicate for extracting the
8724   // high half of an integer being free.
8725 
8726   // (or i64:x, (zero_extend i32:y)) ->
8727   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8728   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8729       RHS.getOpcode() != ISD::ZERO_EXTEND)
8730     std::swap(LHS, RHS);
8731 
8732   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8733     SDValue ExtSrc = RHS.getOperand(0);
8734     EVT SrcVT = ExtSrc.getValueType();
8735     if (SrcVT == MVT::i32) {
8736       SDLoc SL(N);
8737       SDValue LowLHS, HiBits;
8738       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8739       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8740 
8741       DCI.AddToWorklist(LowOr.getNode());
8742       DCI.AddToWorklist(HiBits.getNode());
8743 
8744       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8745                                 LowOr, HiBits);
8746       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8747     }
8748   }
8749 
8750   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8751   if (CRHS) {
8752     if (SDValue Split
8753           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8754       return Split;
8755   }
8756 
8757   return SDValue();
8758 }
8759 
8760 SDValue SITargetLowering::performXorCombine(SDNode *N,
8761                                             DAGCombinerInfo &DCI) const {
8762   EVT VT = N->getValueType(0);
8763   if (VT != MVT::i64)
8764     return SDValue();
8765 
8766   SDValue LHS = N->getOperand(0);
8767   SDValue RHS = N->getOperand(1);
8768 
8769   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8770   if (CRHS) {
8771     if (SDValue Split
8772           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8773       return Split;
8774   }
8775 
8776   return SDValue();
8777 }
8778 
8779 // Instructions that will be lowered with a final instruction that zeros the
8780 // high result bits.
8781 // XXX - probably only need to list legal operations.
8782 static bool fp16SrcZerosHighBits(unsigned Opc) {
8783   switch (Opc) {
8784   case ISD::FADD:
8785   case ISD::FSUB:
8786   case ISD::FMUL:
8787   case ISD::FDIV:
8788   case ISD::FREM:
8789   case ISD::FMA:
8790   case ISD::FMAD:
8791   case ISD::FCANONICALIZE:
8792   case ISD::FP_ROUND:
8793   case ISD::UINT_TO_FP:
8794   case ISD::SINT_TO_FP:
8795   case ISD::FABS:
8796     // Fabs is lowered to a bit operation, but it's an and which will clear the
8797     // high bits anyway.
8798   case ISD::FSQRT:
8799   case ISD::FSIN:
8800   case ISD::FCOS:
8801   case ISD::FPOWI:
8802   case ISD::FPOW:
8803   case ISD::FLOG:
8804   case ISD::FLOG2:
8805   case ISD::FLOG10:
8806   case ISD::FEXP:
8807   case ISD::FEXP2:
8808   case ISD::FCEIL:
8809   case ISD::FTRUNC:
8810   case ISD::FRINT:
8811   case ISD::FNEARBYINT:
8812   case ISD::FROUND:
8813   case ISD::FFLOOR:
8814   case ISD::FMINNUM:
8815   case ISD::FMAXNUM:
8816   case AMDGPUISD::FRACT:
8817   case AMDGPUISD::CLAMP:
8818   case AMDGPUISD::COS_HW:
8819   case AMDGPUISD::SIN_HW:
8820   case AMDGPUISD::FMIN3:
8821   case AMDGPUISD::FMAX3:
8822   case AMDGPUISD::FMED3:
8823   case AMDGPUISD::FMAD_FTZ:
8824   case AMDGPUISD::RCP:
8825   case AMDGPUISD::RSQ:
8826   case AMDGPUISD::RCP_IFLAG:
8827   case AMDGPUISD::LDEXP:
8828     return true;
8829   default:
8830     // fcopysign, select and others may be lowered to 32-bit bit operations
8831     // which don't zero the high bits.
8832     return false;
8833   }
8834 }
8835 
8836 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8837                                                    DAGCombinerInfo &DCI) const {
8838   if (!Subtarget->has16BitInsts() ||
8839       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8840     return SDValue();
8841 
8842   EVT VT = N->getValueType(0);
8843   if (VT != MVT::i32)
8844     return SDValue();
8845 
8846   SDValue Src = N->getOperand(0);
8847   if (Src.getValueType() != MVT::i16)
8848     return SDValue();
8849 
8850   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8851   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8852   if (Src.getOpcode() == ISD::BITCAST) {
8853     SDValue BCSrc = Src.getOperand(0);
8854     if (BCSrc.getValueType() == MVT::f16 &&
8855         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8856       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8857   }
8858 
8859   return SDValue();
8860 }
8861 
8862 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8863                                                         DAGCombinerInfo &DCI)
8864                                                         const {
8865   SDValue Src = N->getOperand(0);
8866   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8867 
8868   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8869       VTSign->getVT() == MVT::i8) ||
8870       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8871       VTSign->getVT() == MVT::i16)) &&
8872       Src.hasOneUse()) {
8873     auto *M = cast<MemSDNode>(Src);
8874     SDValue Ops[] = {
8875       Src.getOperand(0), // Chain
8876       Src.getOperand(1), // rsrc
8877       Src.getOperand(2), // vindex
8878       Src.getOperand(3), // voffset
8879       Src.getOperand(4), // soffset
8880       Src.getOperand(5), // offset
8881       Src.getOperand(6),
8882       Src.getOperand(7)
8883     };
8884     // replace with BUFFER_LOAD_BYTE/SHORT
8885     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8886                                          Src.getOperand(0).getValueType());
8887     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8888                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8889     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8890                                                           ResList,
8891                                                           Ops, M->getMemoryVT(),
8892                                                           M->getMemOperand());
8893     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8894                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8895   }
8896   return SDValue();
8897 }
8898 
8899 SDValue SITargetLowering::performClassCombine(SDNode *N,
8900                                               DAGCombinerInfo &DCI) const {
8901   SelectionDAG &DAG = DCI.DAG;
8902   SDValue Mask = N->getOperand(1);
8903 
8904   // fp_class x, 0 -> false
8905   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8906     if (CMask->isNullValue())
8907       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8908   }
8909 
8910   if (N->getOperand(0).isUndef())
8911     return DAG.getUNDEF(MVT::i1);
8912 
8913   return SDValue();
8914 }
8915 
8916 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8917                                             DAGCombinerInfo &DCI) const {
8918   EVT VT = N->getValueType(0);
8919   SDValue N0 = N->getOperand(0);
8920 
8921   if (N0.isUndef())
8922     return N0;
8923 
8924   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8925                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8926     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8927                            N->getFlags());
8928   }
8929 
8930   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8931     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8932                            N0.getOperand(0), N->getFlags());
8933   }
8934 
8935   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8936 }
8937 
8938 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8939                                        unsigned MaxDepth) const {
8940   unsigned Opcode = Op.getOpcode();
8941   if (Opcode == ISD::FCANONICALIZE)
8942     return true;
8943 
8944   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8945     auto F = CFP->getValueAPF();
8946     if (F.isNaN() && F.isSignaling())
8947       return false;
8948     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8949   }
8950 
8951   // If source is a result of another standard FP operation it is already in
8952   // canonical form.
8953   if (MaxDepth == 0)
8954     return false;
8955 
8956   switch (Opcode) {
8957   // These will flush denorms if required.
8958   case ISD::FADD:
8959   case ISD::FSUB:
8960   case ISD::FMUL:
8961   case ISD::FCEIL:
8962   case ISD::FFLOOR:
8963   case ISD::FMA:
8964   case ISD::FMAD:
8965   case ISD::FSQRT:
8966   case ISD::FDIV:
8967   case ISD::FREM:
8968   case ISD::FP_ROUND:
8969   case ISD::FP_EXTEND:
8970   case AMDGPUISD::FMUL_LEGACY:
8971   case AMDGPUISD::FMAD_FTZ:
8972   case AMDGPUISD::RCP:
8973   case AMDGPUISD::RSQ:
8974   case AMDGPUISD::RSQ_CLAMP:
8975   case AMDGPUISD::RCP_LEGACY:
8976   case AMDGPUISD::RCP_IFLAG:
8977   case AMDGPUISD::TRIG_PREOP:
8978   case AMDGPUISD::DIV_SCALE:
8979   case AMDGPUISD::DIV_FMAS:
8980   case AMDGPUISD::DIV_FIXUP:
8981   case AMDGPUISD::FRACT:
8982   case AMDGPUISD::LDEXP:
8983   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8984   case AMDGPUISD::CVT_F32_UBYTE0:
8985   case AMDGPUISD::CVT_F32_UBYTE1:
8986   case AMDGPUISD::CVT_F32_UBYTE2:
8987   case AMDGPUISD::CVT_F32_UBYTE3:
8988     return true;
8989 
8990   // It can/will be lowered or combined as a bit operation.
8991   // Need to check their input recursively to handle.
8992   case ISD::FNEG:
8993   case ISD::FABS:
8994   case ISD::FCOPYSIGN:
8995     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8996 
8997   case ISD::FSIN:
8998   case ISD::FCOS:
8999   case ISD::FSINCOS:
9000     return Op.getValueType().getScalarType() != MVT::f16;
9001 
9002   case ISD::FMINNUM:
9003   case ISD::FMAXNUM:
9004   case ISD::FMINNUM_IEEE:
9005   case ISD::FMAXNUM_IEEE:
9006   case AMDGPUISD::CLAMP:
9007   case AMDGPUISD::FMED3:
9008   case AMDGPUISD::FMAX3:
9009   case AMDGPUISD::FMIN3: {
9010     // FIXME: Shouldn't treat the generic operations different based these.
9011     // However, we aren't really required to flush the result from
9012     // minnum/maxnum..
9013 
9014     // snans will be quieted, so we only need to worry about denormals.
9015     if (Subtarget->supportsMinMaxDenormModes() ||
9016         denormalsEnabledForType(DAG, Op.getValueType()))
9017       return true;
9018 
9019     // Flushing may be required.
9020     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9021     // targets need to check their input recursively.
9022 
9023     // FIXME: Does this apply with clamp? It's implemented with max.
9024     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9025       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9026         return false;
9027     }
9028 
9029     return true;
9030   }
9031   case ISD::SELECT: {
9032     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9033            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9034   }
9035   case ISD::BUILD_VECTOR: {
9036     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9037       SDValue SrcOp = Op.getOperand(i);
9038       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9039         return false;
9040     }
9041 
9042     return true;
9043   }
9044   case ISD::EXTRACT_VECTOR_ELT:
9045   case ISD::EXTRACT_SUBVECTOR: {
9046     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9047   }
9048   case ISD::INSERT_VECTOR_ELT: {
9049     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9050            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9051   }
9052   case ISD::UNDEF:
9053     // Could be anything.
9054     return false;
9055 
9056   case ISD::BITCAST: {
9057     // Hack round the mess we make when legalizing extract_vector_elt
9058     SDValue Src = Op.getOperand(0);
9059     if (Src.getValueType() == MVT::i16 &&
9060         Src.getOpcode() == ISD::TRUNCATE) {
9061       SDValue TruncSrc = Src.getOperand(0);
9062       if (TruncSrc.getValueType() == MVT::i32 &&
9063           TruncSrc.getOpcode() == ISD::BITCAST &&
9064           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9065         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9066       }
9067     }
9068 
9069     return false;
9070   }
9071   case ISD::INTRINSIC_WO_CHAIN: {
9072     unsigned IntrinsicID
9073       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9074     // TODO: Handle more intrinsics
9075     switch (IntrinsicID) {
9076     case Intrinsic::amdgcn_cvt_pkrtz:
9077     case Intrinsic::amdgcn_cubeid:
9078     case Intrinsic::amdgcn_frexp_mant:
9079     case Intrinsic::amdgcn_fdot2:
9080     case Intrinsic::amdgcn_rcp:
9081     case Intrinsic::amdgcn_rsq:
9082     case Intrinsic::amdgcn_rsq_clamp:
9083     case Intrinsic::amdgcn_rcp_legacy:
9084     case Intrinsic::amdgcn_rsq_legacy:
9085       return true;
9086     default:
9087       break;
9088     }
9089 
9090     LLVM_FALLTHROUGH;
9091   }
9092   default:
9093     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9094            DAG.isKnownNeverSNaN(Op);
9095   }
9096 
9097   llvm_unreachable("invalid operation");
9098 }
9099 
9100 // Constant fold canonicalize.
9101 SDValue SITargetLowering::getCanonicalConstantFP(
9102   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9103   // Flush denormals to 0 if not enabled.
9104   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9105     return DAG.getConstantFP(0.0, SL, VT);
9106 
9107   if (C.isNaN()) {
9108     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9109     if (C.isSignaling()) {
9110       // Quiet a signaling NaN.
9111       // FIXME: Is this supposed to preserve payload bits?
9112       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9113     }
9114 
9115     // Make sure it is the canonical NaN bitpattern.
9116     //
9117     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9118     // immediate?
9119     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9120       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9121   }
9122 
9123   // Already canonical.
9124   return DAG.getConstantFP(C, SL, VT);
9125 }
9126 
9127 static bool vectorEltWillFoldAway(SDValue Op) {
9128   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9129 }
9130 
9131 SDValue SITargetLowering::performFCanonicalizeCombine(
9132   SDNode *N,
9133   DAGCombinerInfo &DCI) const {
9134   SelectionDAG &DAG = DCI.DAG;
9135   SDValue N0 = N->getOperand(0);
9136   EVT VT = N->getValueType(0);
9137 
9138   // fcanonicalize undef -> qnan
9139   if (N0.isUndef()) {
9140     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9141     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9142   }
9143 
9144   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9145     EVT VT = N->getValueType(0);
9146     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9147   }
9148 
9149   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9150   //                                                   (fcanonicalize k)
9151   //
9152   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9153 
9154   // TODO: This could be better with wider vectors that will be split to v2f16,
9155   // and to consider uses since there aren't that many packed operations.
9156   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9157       isTypeLegal(MVT::v2f16)) {
9158     SDLoc SL(N);
9159     SDValue NewElts[2];
9160     SDValue Lo = N0.getOperand(0);
9161     SDValue Hi = N0.getOperand(1);
9162     EVT EltVT = Lo.getValueType();
9163 
9164     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9165       for (unsigned I = 0; I != 2; ++I) {
9166         SDValue Op = N0.getOperand(I);
9167         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9168           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9169                                               CFP->getValueAPF());
9170         } else if (Op.isUndef()) {
9171           // Handled below based on what the other operand is.
9172           NewElts[I] = Op;
9173         } else {
9174           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9175         }
9176       }
9177 
9178       // If one half is undef, and one is constant, perfer a splat vector rather
9179       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9180       // cheaper to use and may be free with a packed operation.
9181       if (NewElts[0].isUndef()) {
9182         if (isa<ConstantFPSDNode>(NewElts[1]))
9183           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9184             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9185       }
9186 
9187       if (NewElts[1].isUndef()) {
9188         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9189           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9190       }
9191 
9192       return DAG.getBuildVector(VT, SL, NewElts);
9193     }
9194   }
9195 
9196   unsigned SrcOpc = N0.getOpcode();
9197 
9198   // If it's free to do so, push canonicalizes further up the source, which may
9199   // find a canonical source.
9200   //
9201   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9202   // sNaNs.
9203   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9204     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9205     if (CRHS && N0.hasOneUse()) {
9206       SDLoc SL(N);
9207       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9208                                    N0.getOperand(0));
9209       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9210       DCI.AddToWorklist(Canon0.getNode());
9211 
9212       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9213     }
9214   }
9215 
9216   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9217 }
9218 
9219 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9220   switch (Opc) {
9221   case ISD::FMAXNUM:
9222   case ISD::FMAXNUM_IEEE:
9223     return AMDGPUISD::FMAX3;
9224   case ISD::SMAX:
9225     return AMDGPUISD::SMAX3;
9226   case ISD::UMAX:
9227     return AMDGPUISD::UMAX3;
9228   case ISD::FMINNUM:
9229   case ISD::FMINNUM_IEEE:
9230     return AMDGPUISD::FMIN3;
9231   case ISD::SMIN:
9232     return AMDGPUISD::SMIN3;
9233   case ISD::UMIN:
9234     return AMDGPUISD::UMIN3;
9235   default:
9236     llvm_unreachable("Not a min/max opcode");
9237   }
9238 }
9239 
9240 SDValue SITargetLowering::performIntMed3ImmCombine(
9241   SelectionDAG &DAG, const SDLoc &SL,
9242   SDValue Op0, SDValue Op1, bool Signed) const {
9243   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9244   if (!K1)
9245     return SDValue();
9246 
9247   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9248   if (!K0)
9249     return SDValue();
9250 
9251   if (Signed) {
9252     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9253       return SDValue();
9254   } else {
9255     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9256       return SDValue();
9257   }
9258 
9259   EVT VT = K0->getValueType(0);
9260   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9261   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9262     return DAG.getNode(Med3Opc, SL, VT,
9263                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9264   }
9265 
9266   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9267   MVT NVT = MVT::i32;
9268   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9269 
9270   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9271   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9272   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9273 
9274   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9275   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9276 }
9277 
9278 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9279   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9280     return C;
9281 
9282   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9283     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9284       return C;
9285   }
9286 
9287   return nullptr;
9288 }
9289 
9290 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9291                                                   const SDLoc &SL,
9292                                                   SDValue Op0,
9293                                                   SDValue Op1) const {
9294   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9295   if (!K1)
9296     return SDValue();
9297 
9298   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9299   if (!K0)
9300     return SDValue();
9301 
9302   // Ordered >= (although NaN inputs should have folded away by now).
9303   if (K0->getValueAPF() > K1->getValueAPF())
9304     return SDValue();
9305 
9306   const MachineFunction &MF = DAG.getMachineFunction();
9307   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9308 
9309   // TODO: Check IEEE bit enabled?
9310   EVT VT = Op0.getValueType();
9311   if (Info->getMode().DX10Clamp) {
9312     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9313     // hardware fmed3 behavior converting to a min.
9314     // FIXME: Should this be allowing -0.0?
9315     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9316       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9317   }
9318 
9319   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9320   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9321     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9322     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9323     // then give the other result, which is different from med3 with a NaN
9324     // input.
9325     SDValue Var = Op0.getOperand(0);
9326     if (!DAG.isKnownNeverSNaN(Var))
9327       return SDValue();
9328 
9329     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9330 
9331     if ((!K0->hasOneUse() ||
9332          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9333         (!K1->hasOneUse() ||
9334          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9335       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9336                          Var, SDValue(K0, 0), SDValue(K1, 0));
9337     }
9338   }
9339 
9340   return SDValue();
9341 }
9342 
9343 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9344                                                DAGCombinerInfo &DCI) const {
9345   SelectionDAG &DAG = DCI.DAG;
9346 
9347   EVT VT = N->getValueType(0);
9348   unsigned Opc = N->getOpcode();
9349   SDValue Op0 = N->getOperand(0);
9350   SDValue Op1 = N->getOperand(1);
9351 
9352   // Only do this if the inner op has one use since this will just increases
9353   // register pressure for no benefit.
9354 
9355   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9356       !VT.isVector() &&
9357       (VT == MVT::i32 || VT == MVT::f32 ||
9358        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9359     // max(max(a, b), c) -> max3(a, b, c)
9360     // min(min(a, b), c) -> min3(a, b, c)
9361     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9362       SDLoc DL(N);
9363       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9364                          DL,
9365                          N->getValueType(0),
9366                          Op0.getOperand(0),
9367                          Op0.getOperand(1),
9368                          Op1);
9369     }
9370 
9371     // Try commuted.
9372     // max(a, max(b, c)) -> max3(a, b, c)
9373     // min(a, min(b, c)) -> min3(a, b, c)
9374     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9375       SDLoc DL(N);
9376       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9377                          DL,
9378                          N->getValueType(0),
9379                          Op0,
9380                          Op1.getOperand(0),
9381                          Op1.getOperand(1));
9382     }
9383   }
9384 
9385   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9386   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9387     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9388       return Med3;
9389   }
9390 
9391   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9392     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9393       return Med3;
9394   }
9395 
9396   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9397   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9398        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9399        (Opc == AMDGPUISD::FMIN_LEGACY &&
9400         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9401       (VT == MVT::f32 || VT == MVT::f64 ||
9402        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9403        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9404       Op0.hasOneUse()) {
9405     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9406       return Res;
9407   }
9408 
9409   return SDValue();
9410 }
9411 
9412 static bool isClampZeroToOne(SDValue A, SDValue B) {
9413   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9414     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9415       // FIXME: Should this be allowing -0.0?
9416       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9417              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9418     }
9419   }
9420 
9421   return false;
9422 }
9423 
9424 // FIXME: Should only worry about snans for version with chain.
9425 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9426                                               DAGCombinerInfo &DCI) const {
9427   EVT VT = N->getValueType(0);
9428   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9429   // NaNs. With a NaN input, the order of the operands may change the result.
9430 
9431   SelectionDAG &DAG = DCI.DAG;
9432   SDLoc SL(N);
9433 
9434   SDValue Src0 = N->getOperand(0);
9435   SDValue Src1 = N->getOperand(1);
9436   SDValue Src2 = N->getOperand(2);
9437 
9438   if (isClampZeroToOne(Src0, Src1)) {
9439     // const_a, const_b, x -> clamp is safe in all cases including signaling
9440     // nans.
9441     // FIXME: Should this be allowing -0.0?
9442     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9443   }
9444 
9445   const MachineFunction &MF = DAG.getMachineFunction();
9446   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9447 
9448   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9449   // handling no dx10-clamp?
9450   if (Info->getMode().DX10Clamp) {
9451     // If NaNs is clamped to 0, we are free to reorder the inputs.
9452 
9453     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9454       std::swap(Src0, Src1);
9455 
9456     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9457       std::swap(Src1, Src2);
9458 
9459     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9460       std::swap(Src0, Src1);
9461 
9462     if (isClampZeroToOne(Src1, Src2))
9463       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9464   }
9465 
9466   return SDValue();
9467 }
9468 
9469 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9470                                                  DAGCombinerInfo &DCI) const {
9471   SDValue Src0 = N->getOperand(0);
9472   SDValue Src1 = N->getOperand(1);
9473   if (Src0.isUndef() && Src1.isUndef())
9474     return DCI.DAG.getUNDEF(N->getValueType(0));
9475   return SDValue();
9476 }
9477 
9478 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9479 // expanded into a set of cmp/select instructions.
9480 static bool shouldExpandVectorDynExt(SDNode *N) {
9481   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9482   if (UseDivergentRegisterIndexing || isa<ConstantSDNode>(Idx))
9483     return false;
9484 
9485   SDValue Vec = N->getOperand(0);
9486   EVT VecVT = Vec.getValueType();
9487   EVT EltVT = VecVT.getVectorElementType();
9488   unsigned VecSize = VecVT.getSizeInBits();
9489   unsigned EltSize = EltVT.getSizeInBits();
9490   unsigned NumElem = VecVT.getVectorNumElements();
9491 
9492   // Sub-dword vectors of size 2 dword or less have better implementation.
9493   if (VecSize <= 64 && EltSize < 32)
9494     return false;
9495 
9496   // Always expand the rest of sub-dword instructions, otherwise it will be
9497   // lowered via memory.
9498   if (EltSize < 32)
9499     return true;
9500 
9501   // Always do this if var-idx is divergent, otherwise it will become a loop.
9502   if (Idx->isDivergent())
9503     return true;
9504 
9505   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9506   unsigned NumInsts = NumElem /* Number of compares */ +
9507                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9508   return NumInsts <= 16;
9509 }
9510 
9511 SDValue SITargetLowering::performExtractVectorEltCombine(
9512   SDNode *N, DAGCombinerInfo &DCI) const {
9513   SDValue Vec = N->getOperand(0);
9514   SelectionDAG &DAG = DCI.DAG;
9515 
9516   EVT VecVT = Vec.getValueType();
9517   EVT EltVT = VecVT.getVectorElementType();
9518 
9519   if ((Vec.getOpcode() == ISD::FNEG ||
9520        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9521     SDLoc SL(N);
9522     EVT EltVT = N->getValueType(0);
9523     SDValue Idx = N->getOperand(1);
9524     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9525                               Vec.getOperand(0), Idx);
9526     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9527   }
9528 
9529   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9530   //    =>
9531   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9532   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9533   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9534   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9535     SDLoc SL(N);
9536     EVT EltVT = N->getValueType(0);
9537     SDValue Idx = N->getOperand(1);
9538     unsigned Opc = Vec.getOpcode();
9539 
9540     switch(Opc) {
9541     default:
9542       break;
9543       // TODO: Support other binary operations.
9544     case ISD::FADD:
9545     case ISD::FSUB:
9546     case ISD::FMUL:
9547     case ISD::ADD:
9548     case ISD::UMIN:
9549     case ISD::UMAX:
9550     case ISD::SMIN:
9551     case ISD::SMAX:
9552     case ISD::FMAXNUM:
9553     case ISD::FMINNUM:
9554     case ISD::FMAXNUM_IEEE:
9555     case ISD::FMINNUM_IEEE: {
9556       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9557                                  Vec.getOperand(0), Idx);
9558       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9559                                  Vec.getOperand(1), Idx);
9560 
9561       DCI.AddToWorklist(Elt0.getNode());
9562       DCI.AddToWorklist(Elt1.getNode());
9563       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9564     }
9565     }
9566   }
9567 
9568   unsigned VecSize = VecVT.getSizeInBits();
9569   unsigned EltSize = EltVT.getSizeInBits();
9570 
9571   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9572   if (shouldExpandVectorDynExt(N)) {
9573     SDLoc SL(N);
9574     SDValue Idx = N->getOperand(1);
9575     SDValue V;
9576     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9577       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9578       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9579       if (I == 0)
9580         V = Elt;
9581       else
9582         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9583     }
9584     return V;
9585   }
9586 
9587   if (!DCI.isBeforeLegalize())
9588     return SDValue();
9589 
9590   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9591   // elements. This exposes more load reduction opportunities by replacing
9592   // multiple small extract_vector_elements with a single 32-bit extract.
9593   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9594   if (isa<MemSDNode>(Vec) &&
9595       EltSize <= 16 &&
9596       EltVT.isByteSized() &&
9597       VecSize > 32 &&
9598       VecSize % 32 == 0 &&
9599       Idx) {
9600     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9601 
9602     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9603     unsigned EltIdx = BitIndex / 32;
9604     unsigned LeftoverBitIdx = BitIndex % 32;
9605     SDLoc SL(N);
9606 
9607     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9608     DCI.AddToWorklist(Cast.getNode());
9609 
9610     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9611                               DAG.getConstant(EltIdx, SL, MVT::i32));
9612     DCI.AddToWorklist(Elt.getNode());
9613     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9614                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9615     DCI.AddToWorklist(Srl.getNode());
9616 
9617     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9618     DCI.AddToWorklist(Trunc.getNode());
9619     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9620   }
9621 
9622   return SDValue();
9623 }
9624 
9625 SDValue
9626 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9627                                                 DAGCombinerInfo &DCI) const {
9628   SDValue Vec = N->getOperand(0);
9629   SDValue Idx = N->getOperand(2);
9630   EVT VecVT = Vec.getValueType();
9631   EVT EltVT = VecVT.getVectorElementType();
9632 
9633   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9634   // => BUILD_VECTOR n x select (e, const-idx)
9635   if (!shouldExpandVectorDynExt(N))
9636     return SDValue();
9637 
9638   SelectionDAG &DAG = DCI.DAG;
9639   SDLoc SL(N);
9640   SDValue Ins = N->getOperand(1);
9641   EVT IdxVT = Idx.getValueType();
9642 
9643   SmallVector<SDValue, 16> Ops;
9644   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9645     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9646     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9647     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9648     Ops.push_back(V);
9649   }
9650 
9651   return DAG.getBuildVector(VecVT, SL, Ops);
9652 }
9653 
9654 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9655                                           const SDNode *N0,
9656                                           const SDNode *N1) const {
9657   EVT VT = N0->getValueType(0);
9658 
9659   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9660   // support denormals ever.
9661   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9662        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9663         getSubtarget()->hasMadF16())) &&
9664        isOperationLegal(ISD::FMAD, VT))
9665     return ISD::FMAD;
9666 
9667   const TargetOptions &Options = DAG.getTarget().Options;
9668   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9669        (N0->getFlags().hasAllowContract() &&
9670         N1->getFlags().hasAllowContract())) &&
9671       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9672     return ISD::FMA;
9673   }
9674 
9675   return 0;
9676 }
9677 
9678 // For a reassociatable opcode perform:
9679 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9680 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9681                                                SelectionDAG &DAG) const {
9682   EVT VT = N->getValueType(0);
9683   if (VT != MVT::i32 && VT != MVT::i64)
9684     return SDValue();
9685 
9686   unsigned Opc = N->getOpcode();
9687   SDValue Op0 = N->getOperand(0);
9688   SDValue Op1 = N->getOperand(1);
9689 
9690   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9691     return SDValue();
9692 
9693   if (Op0->isDivergent())
9694     std::swap(Op0, Op1);
9695 
9696   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9697     return SDValue();
9698 
9699   SDValue Op2 = Op1.getOperand(1);
9700   Op1 = Op1.getOperand(0);
9701   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9702     return SDValue();
9703 
9704   if (Op1->isDivergent())
9705     std::swap(Op1, Op2);
9706 
9707   // If either operand is constant this will conflict with
9708   // DAGCombiner::ReassociateOps().
9709   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9710       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9711     return SDValue();
9712 
9713   SDLoc SL(N);
9714   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9715   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9716 }
9717 
9718 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9719                            EVT VT,
9720                            SDValue N0, SDValue N1, SDValue N2,
9721                            bool Signed) {
9722   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9723   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9724   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9725   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9726 }
9727 
9728 SDValue SITargetLowering::performAddCombine(SDNode *N,
9729                                             DAGCombinerInfo &DCI) const {
9730   SelectionDAG &DAG = DCI.DAG;
9731   EVT VT = N->getValueType(0);
9732   SDLoc SL(N);
9733   SDValue LHS = N->getOperand(0);
9734   SDValue RHS = N->getOperand(1);
9735 
9736   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9737       && Subtarget->hasMad64_32() &&
9738       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9739       VT.getScalarSizeInBits() <= 64) {
9740     if (LHS.getOpcode() != ISD::MUL)
9741       std::swap(LHS, RHS);
9742 
9743     SDValue MulLHS = LHS.getOperand(0);
9744     SDValue MulRHS = LHS.getOperand(1);
9745     SDValue AddRHS = RHS;
9746 
9747     // TODO: Maybe restrict if SGPR inputs.
9748     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9749         numBitsUnsigned(MulRHS, DAG) <= 32) {
9750       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9751       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9752       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9753       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9754     }
9755 
9756     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9757       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9758       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9759       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9760       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9761     }
9762 
9763     return SDValue();
9764   }
9765 
9766   if (SDValue V = reassociateScalarOps(N, DAG)) {
9767     return V;
9768   }
9769 
9770   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9771     return SDValue();
9772 
9773   // add x, zext (setcc) => addcarry x, 0, setcc
9774   // add x, sext (setcc) => subcarry x, 0, setcc
9775   unsigned Opc = LHS.getOpcode();
9776   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9777       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9778     std::swap(RHS, LHS);
9779 
9780   Opc = RHS.getOpcode();
9781   switch (Opc) {
9782   default: break;
9783   case ISD::ZERO_EXTEND:
9784   case ISD::SIGN_EXTEND:
9785   case ISD::ANY_EXTEND: {
9786     auto Cond = RHS.getOperand(0);
9787     // If this won't be a real VOPC output, we would still need to insert an
9788     // extra instruction anyway.
9789     if (!isBoolSGPR(Cond))
9790       break;
9791     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9792     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9793     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9794     return DAG.getNode(Opc, SL, VTList, Args);
9795   }
9796   case ISD::ADDCARRY: {
9797     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9798     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9799     if (!C || C->getZExtValue() != 0) break;
9800     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9801     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9802   }
9803   }
9804   return SDValue();
9805 }
9806 
9807 SDValue SITargetLowering::performSubCombine(SDNode *N,
9808                                             DAGCombinerInfo &DCI) const {
9809   SelectionDAG &DAG = DCI.DAG;
9810   EVT VT = N->getValueType(0);
9811 
9812   if (VT != MVT::i32)
9813     return SDValue();
9814 
9815   SDLoc SL(N);
9816   SDValue LHS = N->getOperand(0);
9817   SDValue RHS = N->getOperand(1);
9818 
9819   // sub x, zext (setcc) => subcarry x, 0, setcc
9820   // sub x, sext (setcc) => addcarry x, 0, setcc
9821   unsigned Opc = RHS.getOpcode();
9822   switch (Opc) {
9823   default: break;
9824   case ISD::ZERO_EXTEND:
9825   case ISD::SIGN_EXTEND:
9826   case ISD::ANY_EXTEND: {
9827     auto Cond = RHS.getOperand(0);
9828     // If this won't be a real VOPC output, we would still need to insert an
9829     // extra instruction anyway.
9830     if (!isBoolSGPR(Cond))
9831       break;
9832     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9833     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9834     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9835     return DAG.getNode(Opc, SL, VTList, Args);
9836   }
9837   }
9838 
9839   if (LHS.getOpcode() == ISD::SUBCARRY) {
9840     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9841     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9842     if (!C || !C->isNullValue())
9843       return SDValue();
9844     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9845     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9846   }
9847   return SDValue();
9848 }
9849 
9850 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9851   DAGCombinerInfo &DCI) const {
9852 
9853   if (N->getValueType(0) != MVT::i32)
9854     return SDValue();
9855 
9856   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9857   if (!C || C->getZExtValue() != 0)
9858     return SDValue();
9859 
9860   SelectionDAG &DAG = DCI.DAG;
9861   SDValue LHS = N->getOperand(0);
9862 
9863   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9864   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9865   unsigned LHSOpc = LHS.getOpcode();
9866   unsigned Opc = N->getOpcode();
9867   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9868       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9869     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9870     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9871   }
9872   return SDValue();
9873 }
9874 
9875 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9876                                              DAGCombinerInfo &DCI) const {
9877   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9878     return SDValue();
9879 
9880   SelectionDAG &DAG = DCI.DAG;
9881   EVT VT = N->getValueType(0);
9882 
9883   SDLoc SL(N);
9884   SDValue LHS = N->getOperand(0);
9885   SDValue RHS = N->getOperand(1);
9886 
9887   // These should really be instruction patterns, but writing patterns with
9888   // source modiifiers is a pain.
9889 
9890   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9891   if (LHS.getOpcode() == ISD::FADD) {
9892     SDValue A = LHS.getOperand(0);
9893     if (A == LHS.getOperand(1)) {
9894       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9895       if (FusedOp != 0) {
9896         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9897         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9898       }
9899     }
9900   }
9901 
9902   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9903   if (RHS.getOpcode() == ISD::FADD) {
9904     SDValue A = RHS.getOperand(0);
9905     if (A == RHS.getOperand(1)) {
9906       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9907       if (FusedOp != 0) {
9908         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9909         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9910       }
9911     }
9912   }
9913 
9914   return SDValue();
9915 }
9916 
9917 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9918                                              DAGCombinerInfo &DCI) const {
9919   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9920     return SDValue();
9921 
9922   SelectionDAG &DAG = DCI.DAG;
9923   SDLoc SL(N);
9924   EVT VT = N->getValueType(0);
9925   assert(!VT.isVector());
9926 
9927   // Try to get the fneg to fold into the source modifier. This undoes generic
9928   // DAG combines and folds them into the mad.
9929   //
9930   // Only do this if we are not trying to support denormals. v_mad_f32 does
9931   // not support denormals ever.
9932   SDValue LHS = N->getOperand(0);
9933   SDValue RHS = N->getOperand(1);
9934   if (LHS.getOpcode() == ISD::FADD) {
9935     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9936     SDValue A = LHS.getOperand(0);
9937     if (A == LHS.getOperand(1)) {
9938       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9939       if (FusedOp != 0){
9940         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9941         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9942 
9943         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9944       }
9945     }
9946   }
9947 
9948   if (RHS.getOpcode() == ISD::FADD) {
9949     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9950 
9951     SDValue A = RHS.getOperand(0);
9952     if (A == RHS.getOperand(1)) {
9953       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9954       if (FusedOp != 0){
9955         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9956         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9957       }
9958     }
9959   }
9960 
9961   return SDValue();
9962 }
9963 
9964 SDValue SITargetLowering::performFMACombine(SDNode *N,
9965                                             DAGCombinerInfo &DCI) const {
9966   SelectionDAG &DAG = DCI.DAG;
9967   EVT VT = N->getValueType(0);
9968   SDLoc SL(N);
9969 
9970   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9971     return SDValue();
9972 
9973   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9974   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9975   SDValue Op1 = N->getOperand(0);
9976   SDValue Op2 = N->getOperand(1);
9977   SDValue FMA = N->getOperand(2);
9978 
9979   if (FMA.getOpcode() != ISD::FMA ||
9980       Op1.getOpcode() != ISD::FP_EXTEND ||
9981       Op2.getOpcode() != ISD::FP_EXTEND)
9982     return SDValue();
9983 
9984   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9985   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9986   // is sufficient to allow generaing fdot2.
9987   const TargetOptions &Options = DAG.getTarget().Options;
9988   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9989       (N->getFlags().hasAllowContract() &&
9990        FMA->getFlags().hasAllowContract())) {
9991     Op1 = Op1.getOperand(0);
9992     Op2 = Op2.getOperand(0);
9993     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9994         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9995       return SDValue();
9996 
9997     SDValue Vec1 = Op1.getOperand(0);
9998     SDValue Idx1 = Op1.getOperand(1);
9999     SDValue Vec2 = Op2.getOperand(0);
10000 
10001     SDValue FMAOp1 = FMA.getOperand(0);
10002     SDValue FMAOp2 = FMA.getOperand(1);
10003     SDValue FMAAcc = FMA.getOperand(2);
10004 
10005     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10006         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10007       return SDValue();
10008 
10009     FMAOp1 = FMAOp1.getOperand(0);
10010     FMAOp2 = FMAOp2.getOperand(0);
10011     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10012         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10013       return SDValue();
10014 
10015     SDValue Vec3 = FMAOp1.getOperand(0);
10016     SDValue Vec4 = FMAOp2.getOperand(0);
10017     SDValue Idx2 = FMAOp1.getOperand(1);
10018 
10019     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10020         // Idx1 and Idx2 cannot be the same.
10021         Idx1 == Idx2)
10022       return SDValue();
10023 
10024     if (Vec1 == Vec2 || Vec3 == Vec4)
10025       return SDValue();
10026 
10027     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10028       return SDValue();
10029 
10030     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10031         (Vec1 == Vec4 && Vec2 == Vec3)) {
10032       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10033                          DAG.getTargetConstant(0, SL, MVT::i1));
10034     }
10035   }
10036   return SDValue();
10037 }
10038 
10039 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10040                                               DAGCombinerInfo &DCI) const {
10041   SelectionDAG &DAG = DCI.DAG;
10042   SDLoc SL(N);
10043 
10044   SDValue LHS = N->getOperand(0);
10045   SDValue RHS = N->getOperand(1);
10046   EVT VT = LHS.getValueType();
10047   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10048 
10049   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10050   if (!CRHS) {
10051     CRHS = dyn_cast<ConstantSDNode>(LHS);
10052     if (CRHS) {
10053       std::swap(LHS, RHS);
10054       CC = getSetCCSwappedOperands(CC);
10055     }
10056   }
10057 
10058   if (CRHS) {
10059     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10060         isBoolSGPR(LHS.getOperand(0))) {
10061       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10062       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10063       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10064       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10065       if ((CRHS->isAllOnesValue() &&
10066            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10067           (CRHS->isNullValue() &&
10068            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10069         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10070                            DAG.getConstant(-1, SL, MVT::i1));
10071       if ((CRHS->isAllOnesValue() &&
10072            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10073           (CRHS->isNullValue() &&
10074            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10075         return LHS.getOperand(0);
10076     }
10077 
10078     uint64_t CRHSVal = CRHS->getZExtValue();
10079     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10080         LHS.getOpcode() == ISD::SELECT &&
10081         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10082         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10083         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10084         isBoolSGPR(LHS.getOperand(0))) {
10085       // Given CT != FT:
10086       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10087       // setcc (select cc, CT, CF), CF, ne => cc
10088       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10089       // setcc (select cc, CT, CF), CT, eq => cc
10090       uint64_t CT = LHS.getConstantOperandVal(1);
10091       uint64_t CF = LHS.getConstantOperandVal(2);
10092 
10093       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10094           (CT == CRHSVal && CC == ISD::SETNE))
10095         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10096                            DAG.getConstant(-1, SL, MVT::i1));
10097       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10098           (CT == CRHSVal && CC == ISD::SETEQ))
10099         return LHS.getOperand(0);
10100     }
10101   }
10102 
10103   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10104                                            VT != MVT::f16))
10105     return SDValue();
10106 
10107   // Match isinf/isfinite pattern
10108   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10109   // (fcmp one (fabs x), inf) -> (fp_class x,
10110   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10111   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10112     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10113     if (!CRHS)
10114       return SDValue();
10115 
10116     const APFloat &APF = CRHS->getValueAPF();
10117     if (APF.isInfinity() && !APF.isNegative()) {
10118       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10119                                  SIInstrFlags::N_INFINITY;
10120       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10121                                     SIInstrFlags::P_ZERO |
10122                                     SIInstrFlags::N_NORMAL |
10123                                     SIInstrFlags::P_NORMAL |
10124                                     SIInstrFlags::N_SUBNORMAL |
10125                                     SIInstrFlags::P_SUBNORMAL;
10126       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10127       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10128                          DAG.getConstant(Mask, SL, MVT::i32));
10129     }
10130   }
10131 
10132   return SDValue();
10133 }
10134 
10135 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10136                                                      DAGCombinerInfo &DCI) const {
10137   SelectionDAG &DAG = DCI.DAG;
10138   SDLoc SL(N);
10139   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10140 
10141   SDValue Src = N->getOperand(0);
10142   SDValue Shift = N->getOperand(0);
10143 
10144   // TODO: Extend type shouldn't matter (assuming legal types).
10145   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10146     Shift = Shift.getOperand(0);
10147 
10148   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10149     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10150     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10151     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10152     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10153     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10154     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10155       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10156                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10157 
10158       unsigned ShiftOffset = 8 * Offset;
10159       if (Shift.getOpcode() == ISD::SHL)
10160         ShiftOffset -= C->getZExtValue();
10161       else
10162         ShiftOffset += C->getZExtValue();
10163 
10164       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10165         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10166                            MVT::f32, Shift);
10167       }
10168     }
10169   }
10170 
10171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10172   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10173   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10174     // We simplified Src. If this node is not dead, visit it again so it is
10175     // folded properly.
10176     if (N->getOpcode() != ISD::DELETED_NODE)
10177       DCI.AddToWorklist(N);
10178     return SDValue(N, 0);
10179   }
10180 
10181   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10182   if (SDValue DemandedSrc =
10183           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10184     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10185 
10186   return SDValue();
10187 }
10188 
10189 SDValue SITargetLowering::performClampCombine(SDNode *N,
10190                                               DAGCombinerInfo &DCI) const {
10191   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10192   if (!CSrc)
10193     return SDValue();
10194 
10195   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10196   const APFloat &F = CSrc->getValueAPF();
10197   APFloat Zero = APFloat::getZero(F.getSemantics());
10198   if (F < Zero ||
10199       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10200     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10201   }
10202 
10203   APFloat One(F.getSemantics(), "1.0");
10204   if (F > One)
10205     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10206 
10207   return SDValue(CSrc, 0);
10208 }
10209 
10210 
10211 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10212                                             DAGCombinerInfo &DCI) const {
10213   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10214     return SDValue();
10215   switch (N->getOpcode()) {
10216   default:
10217     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10218   case ISD::ADD:
10219     return performAddCombine(N, DCI);
10220   case ISD::SUB:
10221     return performSubCombine(N, DCI);
10222   case ISD::ADDCARRY:
10223   case ISD::SUBCARRY:
10224     return performAddCarrySubCarryCombine(N, DCI);
10225   case ISD::FADD:
10226     return performFAddCombine(N, DCI);
10227   case ISD::FSUB:
10228     return performFSubCombine(N, DCI);
10229   case ISD::SETCC:
10230     return performSetCCCombine(N, DCI);
10231   case ISD::FMAXNUM:
10232   case ISD::FMINNUM:
10233   case ISD::FMAXNUM_IEEE:
10234   case ISD::FMINNUM_IEEE:
10235   case ISD::SMAX:
10236   case ISD::SMIN:
10237   case ISD::UMAX:
10238   case ISD::UMIN:
10239   case AMDGPUISD::FMIN_LEGACY:
10240   case AMDGPUISD::FMAX_LEGACY:
10241     return performMinMaxCombine(N, DCI);
10242   case ISD::FMA:
10243     return performFMACombine(N, DCI);
10244   case ISD::LOAD: {
10245     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10246       return Widended;
10247     LLVM_FALLTHROUGH;
10248   }
10249   case ISD::STORE:
10250   case ISD::ATOMIC_LOAD:
10251   case ISD::ATOMIC_STORE:
10252   case ISD::ATOMIC_CMP_SWAP:
10253   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10254   case ISD::ATOMIC_SWAP:
10255   case ISD::ATOMIC_LOAD_ADD:
10256   case ISD::ATOMIC_LOAD_SUB:
10257   case ISD::ATOMIC_LOAD_AND:
10258   case ISD::ATOMIC_LOAD_OR:
10259   case ISD::ATOMIC_LOAD_XOR:
10260   case ISD::ATOMIC_LOAD_NAND:
10261   case ISD::ATOMIC_LOAD_MIN:
10262   case ISD::ATOMIC_LOAD_MAX:
10263   case ISD::ATOMIC_LOAD_UMIN:
10264   case ISD::ATOMIC_LOAD_UMAX:
10265   case ISD::ATOMIC_LOAD_FADD:
10266   case AMDGPUISD::ATOMIC_INC:
10267   case AMDGPUISD::ATOMIC_DEC:
10268   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10269   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10270     if (DCI.isBeforeLegalize())
10271       break;
10272     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10273   case ISD::AND:
10274     return performAndCombine(N, DCI);
10275   case ISD::OR:
10276     return performOrCombine(N, DCI);
10277   case ISD::XOR:
10278     return performXorCombine(N, DCI);
10279   case ISD::ZERO_EXTEND:
10280     return performZeroExtendCombine(N, DCI);
10281   case ISD::SIGN_EXTEND_INREG:
10282     return performSignExtendInRegCombine(N , DCI);
10283   case AMDGPUISD::FP_CLASS:
10284     return performClassCombine(N, DCI);
10285   case ISD::FCANONICALIZE:
10286     return performFCanonicalizeCombine(N, DCI);
10287   case AMDGPUISD::RCP:
10288     return performRcpCombine(N, DCI);
10289   case AMDGPUISD::FRACT:
10290   case AMDGPUISD::RSQ:
10291   case AMDGPUISD::RCP_LEGACY:
10292   case AMDGPUISD::RCP_IFLAG:
10293   case AMDGPUISD::RSQ_CLAMP:
10294   case AMDGPUISD::LDEXP: {
10295     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10296     SDValue Src = N->getOperand(0);
10297     if (Src.isUndef())
10298       return Src;
10299     break;
10300   }
10301   case ISD::SINT_TO_FP:
10302   case ISD::UINT_TO_FP:
10303     return performUCharToFloatCombine(N, DCI);
10304   case AMDGPUISD::CVT_F32_UBYTE0:
10305   case AMDGPUISD::CVT_F32_UBYTE1:
10306   case AMDGPUISD::CVT_F32_UBYTE2:
10307   case AMDGPUISD::CVT_F32_UBYTE3:
10308     return performCvtF32UByteNCombine(N, DCI);
10309   case AMDGPUISD::FMED3:
10310     return performFMed3Combine(N, DCI);
10311   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10312     return performCvtPkRTZCombine(N, DCI);
10313   case AMDGPUISD::CLAMP:
10314     return performClampCombine(N, DCI);
10315   case ISD::SCALAR_TO_VECTOR: {
10316     SelectionDAG &DAG = DCI.DAG;
10317     EVT VT = N->getValueType(0);
10318 
10319     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10320     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10321       SDLoc SL(N);
10322       SDValue Src = N->getOperand(0);
10323       EVT EltVT = Src.getValueType();
10324       if (EltVT == MVT::f16)
10325         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10326 
10327       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10328       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10329     }
10330 
10331     break;
10332   }
10333   case ISD::EXTRACT_VECTOR_ELT:
10334     return performExtractVectorEltCombine(N, DCI);
10335   case ISD::INSERT_VECTOR_ELT:
10336     return performInsertVectorEltCombine(N, DCI);
10337   }
10338   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10339 }
10340 
10341 /// Helper function for adjustWritemask
10342 static unsigned SubIdx2Lane(unsigned Idx) {
10343   switch (Idx) {
10344   default: return 0;
10345   case AMDGPU::sub0: return 0;
10346   case AMDGPU::sub1: return 1;
10347   case AMDGPU::sub2: return 2;
10348   case AMDGPU::sub3: return 3;
10349   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10350   }
10351 }
10352 
10353 /// Adjust the writemask of MIMG instructions
10354 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10355                                           SelectionDAG &DAG) const {
10356   unsigned Opcode = Node->getMachineOpcode();
10357 
10358   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10359   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10360   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10361     return Node; // not implemented for D16
10362 
10363   SDNode *Users[5] = { nullptr };
10364   unsigned Lane = 0;
10365   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10366   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10367   unsigned NewDmask = 0;
10368   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10369   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10370   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10371                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10372   unsigned TFCLane = 0;
10373   bool HasChain = Node->getNumValues() > 1;
10374 
10375   if (OldDmask == 0) {
10376     // These are folded out, but on the chance it happens don't assert.
10377     return Node;
10378   }
10379 
10380   unsigned OldBitsSet = countPopulation(OldDmask);
10381   // Work out which is the TFE/LWE lane if that is enabled.
10382   if (UsesTFC) {
10383     TFCLane = OldBitsSet;
10384   }
10385 
10386   // Try to figure out the used register components
10387   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10388        I != E; ++I) {
10389 
10390     // Don't look at users of the chain.
10391     if (I.getUse().getResNo() != 0)
10392       continue;
10393 
10394     // Abort if we can't understand the usage
10395     if (!I->isMachineOpcode() ||
10396         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10397       return Node;
10398 
10399     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10400     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10401     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10402     // set, etc.
10403     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10404 
10405     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10406     if (UsesTFC && Lane == TFCLane) {
10407       Users[Lane] = *I;
10408     } else {
10409       // Set which texture component corresponds to the lane.
10410       unsigned Comp;
10411       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10412         Comp = countTrailingZeros(Dmask);
10413         Dmask &= ~(1 << Comp);
10414       }
10415 
10416       // Abort if we have more than one user per component.
10417       if (Users[Lane])
10418         return Node;
10419 
10420       Users[Lane] = *I;
10421       NewDmask |= 1 << Comp;
10422     }
10423   }
10424 
10425   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10426   bool NoChannels = !NewDmask;
10427   if (NoChannels) {
10428     if (!UsesTFC) {
10429       // No uses of the result and not using TFC. Then do nothing.
10430       return Node;
10431     }
10432     // If the original dmask has one channel - then nothing to do
10433     if (OldBitsSet == 1)
10434       return Node;
10435     // Use an arbitrary dmask - required for the instruction to work
10436     NewDmask = 1;
10437   }
10438   // Abort if there's no change
10439   if (NewDmask == OldDmask)
10440     return Node;
10441 
10442   unsigned BitsSet = countPopulation(NewDmask);
10443 
10444   // Check for TFE or LWE - increase the number of channels by one to account
10445   // for the extra return value
10446   // This will need adjustment for D16 if this is also included in
10447   // adjustWriteMask (this function) but at present D16 are excluded.
10448   unsigned NewChannels = BitsSet + UsesTFC;
10449 
10450   int NewOpcode =
10451       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10452   assert(NewOpcode != -1 &&
10453          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10454          "failed to find equivalent MIMG op");
10455 
10456   // Adjust the writemask in the node
10457   SmallVector<SDValue, 12> Ops;
10458   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10459   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10460   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10461 
10462   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10463 
10464   MVT ResultVT = NewChannels == 1 ?
10465     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10466                            NewChannels == 5 ? 8 : NewChannels);
10467   SDVTList NewVTList = HasChain ?
10468     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10469 
10470 
10471   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10472                                               NewVTList, Ops);
10473 
10474   if (HasChain) {
10475     // Update chain.
10476     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10477     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10478   }
10479 
10480   if (NewChannels == 1) {
10481     assert(Node->hasNUsesOfValue(1, 0));
10482     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10483                                       SDLoc(Node), Users[Lane]->getValueType(0),
10484                                       SDValue(NewNode, 0));
10485     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10486     return nullptr;
10487   }
10488 
10489   // Update the users of the node with the new indices
10490   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10491     SDNode *User = Users[i];
10492     if (!User) {
10493       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10494       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10495       if (i || !NoChannels)
10496         continue;
10497     } else {
10498       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10499       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10500     }
10501 
10502     switch (Idx) {
10503     default: break;
10504     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10505     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10506     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10507     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10508     }
10509   }
10510 
10511   DAG.RemoveDeadNode(Node);
10512   return nullptr;
10513 }
10514 
10515 static bool isFrameIndexOp(SDValue Op) {
10516   if (Op.getOpcode() == ISD::AssertZext)
10517     Op = Op.getOperand(0);
10518 
10519   return isa<FrameIndexSDNode>(Op);
10520 }
10521 
10522 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10523 /// with frame index operands.
10524 /// LLVM assumes that inputs are to these instructions are registers.
10525 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10526                                                         SelectionDAG &DAG) const {
10527   if (Node->getOpcode() == ISD::CopyToReg) {
10528     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10529     SDValue SrcVal = Node->getOperand(2);
10530 
10531     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10532     // to try understanding copies to physical registers.
10533     if (SrcVal.getValueType() == MVT::i1 &&
10534         Register::isPhysicalRegister(DestReg->getReg())) {
10535       SDLoc SL(Node);
10536       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10537       SDValue VReg = DAG.getRegister(
10538         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10539 
10540       SDNode *Glued = Node->getGluedNode();
10541       SDValue ToVReg
10542         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10543                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10544       SDValue ToResultReg
10545         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10546                            VReg, ToVReg.getValue(1));
10547       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10548       DAG.RemoveDeadNode(Node);
10549       return ToResultReg.getNode();
10550     }
10551   }
10552 
10553   SmallVector<SDValue, 8> Ops;
10554   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10555     if (!isFrameIndexOp(Node->getOperand(i))) {
10556       Ops.push_back(Node->getOperand(i));
10557       continue;
10558     }
10559 
10560     SDLoc DL(Node);
10561     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10562                                      Node->getOperand(i).getValueType(),
10563                                      Node->getOperand(i)), 0));
10564   }
10565 
10566   return DAG.UpdateNodeOperands(Node, Ops);
10567 }
10568 
10569 /// Fold the instructions after selecting them.
10570 /// Returns null if users were already updated.
10571 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10572                                           SelectionDAG &DAG) const {
10573   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10574   unsigned Opcode = Node->getMachineOpcode();
10575 
10576   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10577       !TII->isGather4(Opcode)) {
10578     return adjustWritemask(Node, DAG);
10579   }
10580 
10581   if (Opcode == AMDGPU::INSERT_SUBREG ||
10582       Opcode == AMDGPU::REG_SEQUENCE) {
10583     legalizeTargetIndependentNode(Node, DAG);
10584     return Node;
10585   }
10586 
10587   switch (Opcode) {
10588   case AMDGPU::V_DIV_SCALE_F32:
10589   case AMDGPU::V_DIV_SCALE_F64: {
10590     // Satisfy the operand register constraint when one of the inputs is
10591     // undefined. Ordinarily each undef value will have its own implicit_def of
10592     // a vreg, so force these to use a single register.
10593     SDValue Src0 = Node->getOperand(0);
10594     SDValue Src1 = Node->getOperand(1);
10595     SDValue Src2 = Node->getOperand(2);
10596 
10597     if ((Src0.isMachineOpcode() &&
10598          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10599         (Src0 == Src1 || Src0 == Src2))
10600       break;
10601 
10602     MVT VT = Src0.getValueType().getSimpleVT();
10603     const TargetRegisterClass *RC =
10604         getRegClassFor(VT, Src0.getNode()->isDivergent());
10605 
10606     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10607     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10608 
10609     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10610                                       UndefReg, Src0, SDValue());
10611 
10612     // src0 must be the same register as src1 or src2, even if the value is
10613     // undefined, so make sure we don't violate this constraint.
10614     if (Src0.isMachineOpcode() &&
10615         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10616       if (Src1.isMachineOpcode() &&
10617           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10618         Src0 = Src1;
10619       else if (Src2.isMachineOpcode() &&
10620                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10621         Src0 = Src2;
10622       else {
10623         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10624         Src0 = UndefReg;
10625         Src1 = UndefReg;
10626       }
10627     } else
10628       break;
10629 
10630     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10631     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10632       Ops.push_back(Node->getOperand(I));
10633 
10634     Ops.push_back(ImpDef.getValue(1));
10635     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10636   }
10637   default:
10638     break;
10639   }
10640 
10641   return Node;
10642 }
10643 
10644 /// Assign the register class depending on the number of
10645 /// bits set in the writemask
10646 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10647                                                      SDNode *Node) const {
10648   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10649 
10650   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10651 
10652   if (TII->isVOP3(MI.getOpcode())) {
10653     // Make sure constant bus requirements are respected.
10654     TII->legalizeOperandsVOP3(MRI, MI);
10655 
10656     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10657     // This saves a chain-copy of registers and better ballance register
10658     // use between vgpr and agpr as agpr tuples tend to be big.
10659     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10660       unsigned Opc = MI.getOpcode();
10661       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10662       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10663                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10664         if (I == -1)
10665           break;
10666         MachineOperand &Op = MI.getOperand(I);
10667         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10668              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10669             !Register::isVirtualRegister(Op.getReg()) ||
10670             !TRI->isAGPR(MRI, Op.getReg()))
10671           continue;
10672         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10673         if (!Src || !Src->isCopy() ||
10674             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10675           continue;
10676         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10677         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10678         // All uses of agpr64 and agpr32 can also accept vgpr except for
10679         // v_accvgpr_read, but we do not produce agpr reads during selection,
10680         // so no use checks are needed.
10681         MRI.setRegClass(Op.getReg(), NewRC);
10682       }
10683     }
10684 
10685     return;
10686   }
10687 
10688   // Replace unused atomics with the no return version.
10689   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10690   if (NoRetAtomicOp != -1) {
10691     if (!Node->hasAnyUseOfValue(0)) {
10692       MI.setDesc(TII->get(NoRetAtomicOp));
10693       MI.RemoveOperand(0);
10694       return;
10695     }
10696 
10697     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10698     // instruction, because the return type of these instructions is a vec2 of
10699     // the memory type, so it can be tied to the input operand.
10700     // This means these instructions always have a use, so we need to add a
10701     // special case to check if the atomic has only one extract_subreg use,
10702     // which itself has no uses.
10703     if ((Node->hasNUsesOfValue(1, 0) &&
10704          Node->use_begin()->isMachineOpcode() &&
10705          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10706          !Node->use_begin()->hasAnyUseOfValue(0))) {
10707       Register Def = MI.getOperand(0).getReg();
10708 
10709       // Change this into a noret atomic.
10710       MI.setDesc(TII->get(NoRetAtomicOp));
10711       MI.RemoveOperand(0);
10712 
10713       // If we only remove the def operand from the atomic instruction, the
10714       // extract_subreg will be left with a use of a vreg without a def.
10715       // So we need to insert an implicit_def to avoid machine verifier
10716       // errors.
10717       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10718               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10719     }
10720     return;
10721   }
10722 }
10723 
10724 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10725                               uint64_t Val) {
10726   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10727   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10728 }
10729 
10730 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10731                                                 const SDLoc &DL,
10732                                                 SDValue Ptr) const {
10733   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10734 
10735   // Build the half of the subregister with the constants before building the
10736   // full 128-bit register. If we are building multiple resource descriptors,
10737   // this will allow CSEing of the 2-component register.
10738   const SDValue Ops0[] = {
10739     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10740     buildSMovImm32(DAG, DL, 0),
10741     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10742     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10743     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10744   };
10745 
10746   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10747                                                 MVT::v2i32, Ops0), 0);
10748 
10749   // Combine the constants and the pointer.
10750   const SDValue Ops1[] = {
10751     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10752     Ptr,
10753     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10754     SubRegHi,
10755     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10756   };
10757 
10758   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10759 }
10760 
10761 /// Return a resource descriptor with the 'Add TID' bit enabled
10762 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10763 ///        of the resource descriptor) to create an offset, which is added to
10764 ///        the resource pointer.
10765 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10766                                            SDValue Ptr, uint32_t RsrcDword1,
10767                                            uint64_t RsrcDword2And3) const {
10768   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10769   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10770   if (RsrcDword1) {
10771     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10772                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10773                     0);
10774   }
10775 
10776   SDValue DataLo = buildSMovImm32(DAG, DL,
10777                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10778   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10779 
10780   const SDValue Ops[] = {
10781     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10782     PtrLo,
10783     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10784     PtrHi,
10785     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10786     DataLo,
10787     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10788     DataHi,
10789     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10790   };
10791 
10792   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10793 }
10794 
10795 //===----------------------------------------------------------------------===//
10796 //                         SI Inline Assembly Support
10797 //===----------------------------------------------------------------------===//
10798 
10799 std::pair<unsigned, const TargetRegisterClass *>
10800 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10801                                                StringRef Constraint,
10802                                                MVT VT) const {
10803   const TargetRegisterClass *RC = nullptr;
10804   if (Constraint.size() == 1) {
10805     const unsigned BitWidth = VT.getSizeInBits();
10806     switch (Constraint[0]) {
10807     default:
10808       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10809     case 's':
10810     case 'r':
10811       switch (BitWidth) {
10812       case 16:
10813         RC = &AMDGPU::SReg_32RegClass;
10814         break;
10815       case 64:
10816         RC = &AMDGPU::SGPR_64RegClass;
10817         break;
10818       default:
10819         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
10820         if (!RC)
10821           return std::make_pair(0U, nullptr);
10822         break;
10823       }
10824       break;
10825     case 'v':
10826       switch (BitWidth) {
10827       case 16:
10828         RC = &AMDGPU::VGPR_32RegClass;
10829         break;
10830       default:
10831         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
10832         if (!RC)
10833           return std::make_pair(0U, nullptr);
10834         break;
10835       }
10836       break;
10837     case 'a':
10838       if (!Subtarget->hasMAIInsts())
10839         break;
10840       switch (BitWidth) {
10841       case 16:
10842         RC = &AMDGPU::AGPR_32RegClass;
10843         break;
10844       default:
10845         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
10846         if (!RC)
10847           return std::make_pair(0U, nullptr);
10848         break;
10849       }
10850       break;
10851     }
10852     // We actually support i128, i16 and f16 as inline parameters
10853     // even if they are not reported as legal
10854     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10855                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10856       return std::make_pair(0U, RC);
10857   }
10858 
10859   if (Constraint.size() > 1) {
10860     if (Constraint[1] == 'v') {
10861       RC = &AMDGPU::VGPR_32RegClass;
10862     } else if (Constraint[1] == 's') {
10863       RC = &AMDGPU::SGPR_32RegClass;
10864     } else if (Constraint[1] == 'a') {
10865       RC = &AMDGPU::AGPR_32RegClass;
10866     }
10867 
10868     if (RC) {
10869       uint32_t Idx;
10870       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10871       if (!Failed && Idx < RC->getNumRegs())
10872         return std::make_pair(RC->getRegister(Idx), RC);
10873     }
10874   }
10875 
10876   // FIXME: Returns VS_32 for physical SGPR constraints
10877   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10878 }
10879 
10880 SITargetLowering::ConstraintType
10881 SITargetLowering::getConstraintType(StringRef Constraint) const {
10882   if (Constraint.size() == 1) {
10883     switch (Constraint[0]) {
10884     default: break;
10885     case 's':
10886     case 'v':
10887     case 'a':
10888       return C_RegisterClass;
10889     case 'A':
10890       return C_Other;
10891     }
10892   }
10893   return TargetLowering::getConstraintType(Constraint);
10894 }
10895 
10896 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10897                                                     std::string &Constraint,
10898                                                     std::vector<SDValue> &Ops,
10899                                                     SelectionDAG &DAG) const {
10900   if (Constraint.length() == 1 && Constraint[0] == 'A') {
10901     LowerAsmOperandForConstraintA(Op, Ops, DAG);
10902   } else {
10903     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10904   }
10905 }
10906 
10907 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op,
10908                                                      std::vector<SDValue> &Ops,
10909                                                      SelectionDAG &DAG) const {
10910   unsigned Size = Op.getScalarValueSizeInBits();
10911   if (Size > 64)
10912     return;
10913 
10914   uint64_t Val;
10915   bool IsConst = false;
10916   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10917     Val = C->getSExtValue();
10918     IsConst = true;
10919   } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
10920     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
10921     IsConst = true;
10922   } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
10923     if (Size != 16 || Op.getNumOperands() != 2)
10924       return;
10925     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
10926       return;
10927     if (ConstantSDNode *C = V->getConstantSplatNode()) {
10928       Val = C->getSExtValue();
10929       IsConst = true;
10930     } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
10931       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
10932       IsConst = true;
10933     }
10934   }
10935 
10936   if (IsConst) {
10937     bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
10938     if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
10939         (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
10940         (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
10941       // Clear unused bits of fp constants
10942       if (!AMDGPU::isInlinableIntLiteral(Val)) {
10943         unsigned UnusedBits = 64 - Size;
10944         Val = (Val << UnusedBits) >> UnusedBits;
10945       }
10946       auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64);
10947       Ops.push_back(Res);
10948     }
10949   }
10950 }
10951 
10952 // Figure out which registers should be reserved for stack access. Only after
10953 // the function is legalized do we know all of the non-spill stack objects or if
10954 // calls are present.
10955 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10956   MachineRegisterInfo &MRI = MF.getRegInfo();
10957   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10958   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10959   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10960 
10961   if (Info->isEntryFunction()) {
10962     // Callable functions have fixed registers used for stack access.
10963     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10964   }
10965 
10966   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10967                              Info->getStackPtrOffsetReg()));
10968   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10969     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10970 
10971   // We need to worry about replacing the default register with itself in case
10972   // of MIR testcases missing the MFI.
10973   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10974     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10975 
10976   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10977     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10978 
10979   Info->limitOccupancy(MF);
10980 
10981   if (ST.isWave32() && !MF.empty()) {
10982     // Add VCC_HI def because many instructions marked as imp-use VCC where
10983     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10984     // having a use of undef.
10985 
10986     const SIInstrInfo *TII = ST.getInstrInfo();
10987     DebugLoc DL;
10988 
10989     MachineBasicBlock &MBB = MF.front();
10990     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10991     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10992 
10993     for (auto &MBB : MF) {
10994       for (auto &MI : MBB) {
10995         TII->fixImplicitOperands(MI);
10996       }
10997     }
10998   }
10999 
11000   TargetLoweringBase::finalizeLowering(MF);
11001 
11002   // Allocate a VGPR for future SGPR Spill if
11003   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11004   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11005   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11006       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11007     Info->reserveVGPRforSGPRSpills(MF);
11008 }
11009 
11010 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
11011                                                      KnownBits &Known,
11012                                                      const APInt &DemandedElts,
11013                                                      const SelectionDAG &DAG,
11014                                                      unsigned Depth) const {
11015   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
11016                                                 DAG, Depth);
11017 
11018   // Set the high bits to zero based on the maximum allowed scratch size per
11019   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11020   // calculation won't overflow, so assume the sign bit is never set.
11021   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11022 }
11023 
11024 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11025   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11026   const Align CacheLineAlign = Align(64);
11027 
11028   // Pre-GFX10 target did not benefit from loop alignment
11029   if (!ML || DisableLoopAlignment ||
11030       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11031       getSubtarget()->hasInstFwdPrefetchBug())
11032     return PrefAlign;
11033 
11034   // On GFX10 I$ is 4 x 64 bytes cache lines.
11035   // By default prefetcher keeps one cache line behind and reads two ahead.
11036   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11037   // behind and one ahead.
11038   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11039   // If loop fits 64 bytes it always spans no more than two cache lines and
11040   // does not need an alignment.
11041   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11042   // Else if loop is less or equal 192 bytes we need two lines behind.
11043 
11044   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11045   const MachineBasicBlock *Header = ML->getHeader();
11046   if (Header->getAlignment() != PrefAlign)
11047     return Header->getAlignment(); // Already processed.
11048 
11049   unsigned LoopSize = 0;
11050   for (const MachineBasicBlock *MBB : ML->blocks()) {
11051     // If inner loop block is aligned assume in average half of the alignment
11052     // size to be added as nops.
11053     if (MBB != Header)
11054       LoopSize += MBB->getAlignment().value() / 2;
11055 
11056     for (const MachineInstr &MI : *MBB) {
11057       LoopSize += TII->getInstSizeInBytes(MI);
11058       if (LoopSize > 192)
11059         return PrefAlign;
11060     }
11061   }
11062 
11063   if (LoopSize <= 64)
11064     return PrefAlign;
11065 
11066   if (LoopSize <= 128)
11067     return CacheLineAlign;
11068 
11069   // If any of parent loops is surrounded by prefetch instructions do not
11070   // insert new for inner loop, which would reset parent's settings.
11071   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11072     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11073       auto I = Exit->getFirstNonDebugInstr();
11074       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11075         return CacheLineAlign;
11076     }
11077   }
11078 
11079   MachineBasicBlock *Pre = ML->getLoopPreheader();
11080   MachineBasicBlock *Exit = ML->getExitBlock();
11081 
11082   if (Pre && Exit) {
11083     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11084             TII->get(AMDGPU::S_INST_PREFETCH))
11085       .addImm(1); // prefetch 2 lines behind PC
11086 
11087     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11088             TII->get(AMDGPU::S_INST_PREFETCH))
11089       .addImm(2); // prefetch 1 line behind PC
11090   }
11091 
11092   return CacheLineAlign;
11093 }
11094 
11095 LLVM_ATTRIBUTE_UNUSED
11096 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11097   assert(N->getOpcode() == ISD::CopyFromReg);
11098   do {
11099     // Follow the chain until we find an INLINEASM node.
11100     N = N->getOperand(0).getNode();
11101     if (N->getOpcode() == ISD::INLINEASM ||
11102         N->getOpcode() == ISD::INLINEASM_BR)
11103       return true;
11104   } while (N->getOpcode() == ISD::CopyFromReg);
11105   return false;
11106 }
11107 
11108 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11109   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11110 {
11111   switch (N->getOpcode()) {
11112     case ISD::CopyFromReg:
11113     {
11114       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11115       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11116       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11117       Register Reg = R->getReg();
11118 
11119       // FIXME: Why does this need to consider isLiveIn?
11120       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11121         return !TRI->isSGPRReg(MRI, Reg);
11122 
11123       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11124         return KDA->isDivergent(V);
11125 
11126       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11127       return !TRI->isSGPRReg(MRI, Reg);
11128     }
11129     break;
11130     case ISD::LOAD: {
11131       const LoadSDNode *L = cast<LoadSDNode>(N);
11132       unsigned AS = L->getAddressSpace();
11133       // A flat load may access private memory.
11134       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11135     } break;
11136     case ISD::CALLSEQ_END:
11137     return true;
11138     break;
11139     case ISD::INTRINSIC_WO_CHAIN:
11140     {
11141 
11142     }
11143       return AMDGPU::isIntrinsicSourceOfDivergence(
11144       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11145     case ISD::INTRINSIC_W_CHAIN:
11146       return AMDGPU::isIntrinsicSourceOfDivergence(
11147       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11148   }
11149   return false;
11150 }
11151 
11152 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11153                                                EVT VT) const {
11154   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11155   case MVT::f32:
11156     return hasFP32Denormals(DAG.getMachineFunction());
11157   case MVT::f64:
11158   case MVT::f16:
11159     return hasFP64FP16Denormals(DAG.getMachineFunction());
11160   default:
11161     return false;
11162   }
11163 }
11164 
11165 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11166                                                     const SelectionDAG &DAG,
11167                                                     bool SNaN,
11168                                                     unsigned Depth) const {
11169   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11170     const MachineFunction &MF = DAG.getMachineFunction();
11171     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11172 
11173     if (Info->getMode().DX10Clamp)
11174       return true; // Clamped to 0.
11175     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11176   }
11177 
11178   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11179                                                             SNaN, Depth);
11180 }
11181 
11182 TargetLowering::AtomicExpansionKind
11183 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11184   switch (RMW->getOperation()) {
11185   case AtomicRMWInst::FAdd: {
11186     Type *Ty = RMW->getType();
11187 
11188     // We don't have a way to support 16-bit atomics now, so just leave them
11189     // as-is.
11190     if (Ty->isHalfTy())
11191       return AtomicExpansionKind::None;
11192 
11193     if (!Ty->isFloatTy())
11194       return AtomicExpansionKind::CmpXChg;
11195 
11196     // TODO: Do have these for flat. Older targets also had them for buffers.
11197     unsigned AS = RMW->getPointerAddressSpace();
11198 
11199     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11200       return RMW->use_empty() ? AtomicExpansionKind::None :
11201                                 AtomicExpansionKind::CmpXChg;
11202     }
11203 
11204     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11205       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11206   }
11207   default:
11208     break;
11209   }
11210 
11211   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11212 }
11213 
11214 const TargetRegisterClass *
11215 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11216   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11217   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11218   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11219     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11220                                                : &AMDGPU::SReg_32RegClass;
11221   if (!TRI->isSGPRClass(RC) && !isDivergent)
11222     return TRI->getEquivalentSGPRClass(RC);
11223   else if (TRI->isSGPRClass(RC) && isDivergent)
11224     return TRI->getEquivalentVGPRClass(RC);
11225 
11226   return RC;
11227 }
11228 
11229 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11230 // uniform values (as produced by the mask results of control flow intrinsics)
11231 // used outside of divergent blocks. The phi users need to also be treated as
11232 // always uniform.
11233 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11234                       unsigned WaveSize) {
11235   // FIXME: We asssume we never cast the mask results of a control flow
11236   // intrinsic.
11237   // Early exit if the type won't be consistent as a compile time hack.
11238   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11239   if (!IT || IT->getBitWidth() != WaveSize)
11240     return false;
11241 
11242   if (!isa<Instruction>(V))
11243     return false;
11244   if (!Visited.insert(V).second)
11245     return false;
11246   bool Result = false;
11247   for (auto U : V->users()) {
11248     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11249       if (V == U->getOperand(1)) {
11250         switch (Intrinsic->getIntrinsicID()) {
11251         default:
11252           Result = false;
11253           break;
11254         case Intrinsic::amdgcn_if_break:
11255         case Intrinsic::amdgcn_if:
11256         case Intrinsic::amdgcn_else:
11257           Result = true;
11258           break;
11259         }
11260       }
11261       if (V == U->getOperand(0)) {
11262         switch (Intrinsic->getIntrinsicID()) {
11263         default:
11264           Result = false;
11265           break;
11266         case Intrinsic::amdgcn_end_cf:
11267         case Intrinsic::amdgcn_loop:
11268           Result = true;
11269           break;
11270         }
11271       }
11272     } else {
11273       Result = hasCFUser(U, Visited, WaveSize);
11274     }
11275     if (Result)
11276       break;
11277   }
11278   return Result;
11279 }
11280 
11281 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11282                                                const Value *V) const {
11283   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11284     if (CI->isInlineAsm()) {
11285       // FIXME: This cannot give a correct answer. This should only trigger in
11286       // the case where inline asm returns mixed SGPR and VGPR results, used
11287       // outside the defining block. We don't have a specific result to
11288       // consider, so this assumes if any value is SGPR, the overall register
11289       // also needs to be SGPR.
11290       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11291       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11292           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11293       for (auto &TC : TargetConstraints) {
11294         if (TC.Type == InlineAsm::isOutput) {
11295           ComputeConstraintToUse(TC, SDValue());
11296           unsigned AssignedReg;
11297           const TargetRegisterClass *RC;
11298           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11299               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11300           if (RC) {
11301             MachineRegisterInfo &MRI = MF.getRegInfo();
11302             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11303               return true;
11304             else if (SIRI->isSGPRClass(RC))
11305               return true;
11306           }
11307         }
11308       }
11309     }
11310   }
11311   SmallPtrSet<const Value *, 16> Visited;
11312   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11313 }
11314