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     Target = BR->getOperand(1);
4718   }
4719 
4720   unsigned CFNode = isCFIntrinsic(Intr);
4721   if (CFNode == 0) {
4722     // This is a uniform branch so we don't need to legalize.
4723     return BRCOND;
4724   }
4725 
4726   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4727                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4728 
4729   assert(!SetCC ||
4730         (SetCC->getConstantOperandVal(1) == 1 &&
4731          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4732                                                              ISD::SETNE));
4733 
4734   // operands of the new intrinsic call
4735   SmallVector<SDValue, 4> Ops;
4736   if (HaveChain)
4737     Ops.push_back(BRCOND.getOperand(0));
4738 
4739   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4740   Ops.push_back(Target);
4741 
4742   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4743 
4744   // build the new intrinsic call
4745   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4746 
4747   if (!HaveChain) {
4748     SDValue Ops[] =  {
4749       SDValue(Result, 0),
4750       BRCOND.getOperand(0)
4751     };
4752 
4753     Result = DAG.getMergeValues(Ops, DL).getNode();
4754   }
4755 
4756   if (BR) {
4757     // Give the branch instruction our target
4758     SDValue Ops[] = {
4759       BR->getOperand(0),
4760       BRCOND.getOperand(2)
4761     };
4762     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4763     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4764   }
4765 
4766   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4767 
4768   // Copy the intrinsic results to registers
4769   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4770     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4771     if (!CopyToReg)
4772       continue;
4773 
4774     Chain = DAG.getCopyToReg(
4775       Chain, DL,
4776       CopyToReg->getOperand(1),
4777       SDValue(Result, i - 1),
4778       SDValue());
4779 
4780     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4781   }
4782 
4783   // Remove the old intrinsic from the chain
4784   DAG.ReplaceAllUsesOfValueWith(
4785     SDValue(Intr, Intr->getNumValues() - 1),
4786     Intr->getOperand(0));
4787 
4788   return Chain;
4789 }
4790 
4791 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4792                                           SelectionDAG &DAG) const {
4793   MVT VT = Op.getSimpleValueType();
4794   SDLoc DL(Op);
4795   // Checking the depth
4796   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4797     return DAG.getConstant(0, DL, VT);
4798 
4799   MachineFunction &MF = DAG.getMachineFunction();
4800   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4801   // Check for kernel and shader functions
4802   if (Info->isEntryFunction())
4803     return DAG.getConstant(0, DL, VT);
4804 
4805   MachineFrameInfo &MFI = MF.getFrameInfo();
4806   // There is a call to @llvm.returnaddress in this function
4807   MFI.setReturnAddressIsTaken(true);
4808 
4809   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4810   // Get the return address reg and mark it as an implicit live-in
4811   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4812 
4813   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4814 }
4815 
4816 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4817                                             SDValue Op,
4818                                             const SDLoc &DL,
4819                                             EVT VT) const {
4820   return Op.getValueType().bitsLE(VT) ?
4821       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4822     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4823                 DAG.getTargetConstant(0, DL, MVT::i32));
4824 }
4825 
4826 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4827   assert(Op.getValueType() == MVT::f16 &&
4828          "Do not know how to custom lower FP_ROUND for non-f16 type");
4829 
4830   SDValue Src = Op.getOperand(0);
4831   EVT SrcVT = Src.getValueType();
4832   if (SrcVT != MVT::f64)
4833     return Op;
4834 
4835   SDLoc DL(Op);
4836 
4837   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4838   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4839   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4840 }
4841 
4842 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4843                                                SelectionDAG &DAG) const {
4844   EVT VT = Op.getValueType();
4845   const MachineFunction &MF = DAG.getMachineFunction();
4846   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4847   bool IsIEEEMode = Info->getMode().IEEE;
4848 
4849   // FIXME: Assert during selection that this is only selected for
4850   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4851   // mode functions, but this happens to be OK since it's only done in cases
4852   // where there is known no sNaN.
4853   if (IsIEEEMode)
4854     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4855 
4856   if (VT == MVT::v4f16)
4857     return splitBinaryVectorOp(Op, DAG);
4858   return Op;
4859 }
4860 
4861 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4862   SDLoc SL(Op);
4863   SDValue Chain = Op.getOperand(0);
4864 
4865   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4866       !Subtarget->isTrapHandlerEnabled())
4867     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4868 
4869   MachineFunction &MF = DAG.getMachineFunction();
4870   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4871   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4872   assert(UserSGPR != AMDGPU::NoRegister);
4873   SDValue QueuePtr = CreateLiveInRegister(
4874     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4875   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4876   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4877                                    QueuePtr, SDValue());
4878   SDValue Ops[] = {
4879     ToReg,
4880     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4881     SGPR01,
4882     ToReg.getValue(1)
4883   };
4884   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4885 }
4886 
4887 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4888   SDLoc SL(Op);
4889   SDValue Chain = Op.getOperand(0);
4890   MachineFunction &MF = DAG.getMachineFunction();
4891 
4892   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4893       !Subtarget->isTrapHandlerEnabled()) {
4894     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4895                                      "debugtrap handler not supported",
4896                                      Op.getDebugLoc(),
4897                                      DS_Warning);
4898     LLVMContext &Ctx = MF.getFunction().getContext();
4899     Ctx.diagnose(NoTrap);
4900     return Chain;
4901   }
4902 
4903   SDValue Ops[] = {
4904     Chain,
4905     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4906   };
4907   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4908 }
4909 
4910 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4911                                              SelectionDAG &DAG) const {
4912   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4913   if (Subtarget->hasApertureRegs()) {
4914     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4915         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4916         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4917     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4918         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4919         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4920     unsigned Encoding =
4921         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4922         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4923         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4924 
4925     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4926     SDValue ApertureReg = SDValue(
4927         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4928     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4929     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4930   }
4931 
4932   MachineFunction &MF = DAG.getMachineFunction();
4933   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4934   Register UserSGPR = Info->getQueuePtrUserSGPR();
4935   assert(UserSGPR != AMDGPU::NoRegister);
4936 
4937   SDValue QueuePtr = CreateLiveInRegister(
4938     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4939 
4940   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4941   // private_segment_aperture_base_hi.
4942   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4943 
4944   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4945 
4946   // TODO: Use custom target PseudoSourceValue.
4947   // TODO: We should use the value from the IR intrinsic call, but it might not
4948   // be available and how do we get it?
4949   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4950   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4951                      MinAlign(64, StructOffset),
4952                      MachineMemOperand::MODereferenceable |
4953                          MachineMemOperand::MOInvariant);
4954 }
4955 
4956 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4957                                              SelectionDAG &DAG) const {
4958   SDLoc SL(Op);
4959   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4960 
4961   SDValue Src = ASC->getOperand(0);
4962   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4963 
4964   const AMDGPUTargetMachine &TM =
4965     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4966 
4967   // flat -> local/private
4968   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4969     unsigned DestAS = ASC->getDestAddressSpace();
4970 
4971     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4972         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4973       unsigned NullVal = TM.getNullPointerValue(DestAS);
4974       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4975       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4976       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4977 
4978       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4979                          NonNull, Ptr, SegmentNullPtr);
4980     }
4981   }
4982 
4983   // local/private -> flat
4984   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4985     unsigned SrcAS = ASC->getSrcAddressSpace();
4986 
4987     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4988         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4989       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4990       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4991 
4992       SDValue NonNull
4993         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4994 
4995       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4996       SDValue CvtPtr
4997         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4998 
4999       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5000                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5001                          FlatNullPtr);
5002     }
5003   }
5004 
5005   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5006       Src.getValueType() == MVT::i64)
5007     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5008 
5009   // global <-> flat are no-ops and never emitted.
5010 
5011   const MachineFunction &MF = DAG.getMachineFunction();
5012   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5013     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5014   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5015 
5016   return DAG.getUNDEF(ASC->getValueType(0));
5017 }
5018 
5019 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5020 // the small vector and inserting them into the big vector. That is better than
5021 // the default expansion of doing it via a stack slot. Even though the use of
5022 // the stack slot would be optimized away afterwards, the stack slot itself
5023 // remains.
5024 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5025                                                 SelectionDAG &DAG) const {
5026   SDValue Vec = Op.getOperand(0);
5027   SDValue Ins = Op.getOperand(1);
5028   SDValue Idx = Op.getOperand(2);
5029   EVT VecVT = Vec.getValueType();
5030   EVT InsVT = Ins.getValueType();
5031   EVT EltVT = VecVT.getVectorElementType();
5032   unsigned InsNumElts = InsVT.getVectorNumElements();
5033   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5034   SDLoc SL(Op);
5035 
5036   for (unsigned I = 0; I != InsNumElts; ++I) {
5037     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5038                               DAG.getConstant(I, SL, MVT::i32));
5039     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5040                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5041   }
5042   return Vec;
5043 }
5044 
5045 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5046                                                  SelectionDAG &DAG) const {
5047   SDValue Vec = Op.getOperand(0);
5048   SDValue InsVal = Op.getOperand(1);
5049   SDValue Idx = Op.getOperand(2);
5050   EVT VecVT = Vec.getValueType();
5051   EVT EltVT = VecVT.getVectorElementType();
5052   unsigned VecSize = VecVT.getSizeInBits();
5053   unsigned EltSize = EltVT.getSizeInBits();
5054 
5055 
5056   assert(VecSize <= 64);
5057 
5058   unsigned NumElts = VecVT.getVectorNumElements();
5059   SDLoc SL(Op);
5060   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5061 
5062   if (NumElts == 4 && EltSize == 16 && KIdx) {
5063     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5064 
5065     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5066                                  DAG.getConstant(0, SL, MVT::i32));
5067     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5068                                  DAG.getConstant(1, SL, MVT::i32));
5069 
5070     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5071     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5072 
5073     unsigned Idx = KIdx->getZExtValue();
5074     bool InsertLo = Idx < 2;
5075     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5076       InsertLo ? LoVec : HiVec,
5077       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5078       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5079 
5080     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5081 
5082     SDValue Concat = InsertLo ?
5083       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5084       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5085 
5086     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5087   }
5088 
5089   if (isa<ConstantSDNode>(Idx))
5090     return SDValue();
5091 
5092   MVT IntVT = MVT::getIntegerVT(VecSize);
5093 
5094   // Avoid stack access for dynamic indexing.
5095   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5096 
5097   // Create a congruent vector with the target value in each element so that
5098   // the required element can be masked and ORed into the target vector.
5099   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5100                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5101 
5102   assert(isPowerOf2_32(EltSize));
5103   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5104 
5105   // Convert vector index to bit-index.
5106   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5107 
5108   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5109   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5110                             DAG.getConstant(0xffff, SL, IntVT),
5111                             ScaledIdx);
5112 
5113   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5114   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5115                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5116 
5117   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5118   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5119 }
5120 
5121 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5122                                                   SelectionDAG &DAG) const {
5123   SDLoc SL(Op);
5124 
5125   EVT ResultVT = Op.getValueType();
5126   SDValue Vec = Op.getOperand(0);
5127   SDValue Idx = Op.getOperand(1);
5128   EVT VecVT = Vec.getValueType();
5129   unsigned VecSize = VecVT.getSizeInBits();
5130   EVT EltVT = VecVT.getVectorElementType();
5131   assert(VecSize <= 64);
5132 
5133   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5134 
5135   // Make sure we do any optimizations that will make it easier to fold
5136   // source modifiers before obscuring it with bit operations.
5137 
5138   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5139   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5140     return Combined;
5141 
5142   unsigned EltSize = EltVT.getSizeInBits();
5143   assert(isPowerOf2_32(EltSize));
5144 
5145   MVT IntVT = MVT::getIntegerVT(VecSize);
5146   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5147 
5148   // Convert vector index to bit-index (* EltSize)
5149   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5150 
5151   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5152   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5153 
5154   if (ResultVT == MVT::f16) {
5155     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5156     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5157   }
5158 
5159   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5160 }
5161 
5162 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5163   assert(Elt % 2 == 0);
5164   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5165 }
5166 
5167 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5168                                               SelectionDAG &DAG) const {
5169   SDLoc SL(Op);
5170   EVT ResultVT = Op.getValueType();
5171   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5172 
5173   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5174   EVT EltVT = PackVT.getVectorElementType();
5175   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5176 
5177   // vector_shuffle <0,1,6,7> lhs, rhs
5178   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5179   //
5180   // vector_shuffle <6,7,2,3> lhs, rhs
5181   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5182   //
5183   // vector_shuffle <6,7,0,1> lhs, rhs
5184   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5185 
5186   // Avoid scalarizing when both halves are reading from consecutive elements.
5187   SmallVector<SDValue, 4> Pieces;
5188   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5189     if (elementPairIsContiguous(SVN->getMask(), I)) {
5190       const int Idx = SVN->getMaskElt(I);
5191       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5192       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5193       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5194                                     PackVT, SVN->getOperand(VecIdx),
5195                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5196       Pieces.push_back(SubVec);
5197     } else {
5198       const int Idx0 = SVN->getMaskElt(I);
5199       const int Idx1 = SVN->getMaskElt(I + 1);
5200       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5201       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5202       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5203       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5204 
5205       SDValue Vec0 = SVN->getOperand(VecIdx0);
5206       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5207                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5208 
5209       SDValue Vec1 = SVN->getOperand(VecIdx1);
5210       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5211                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5212       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5213     }
5214   }
5215 
5216   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5217 }
5218 
5219 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5220                                             SelectionDAG &DAG) const {
5221   SDLoc SL(Op);
5222   EVT VT = Op.getValueType();
5223 
5224   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5225     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5226 
5227     // Turn into pair of packed build_vectors.
5228     // TODO: Special case for constants that can be materialized with s_mov_b64.
5229     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5230                                     { Op.getOperand(0), Op.getOperand(1) });
5231     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5232                                     { Op.getOperand(2), Op.getOperand(3) });
5233 
5234     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5235     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5236 
5237     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5238     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5239   }
5240 
5241   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5242   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5243 
5244   SDValue Lo = Op.getOperand(0);
5245   SDValue Hi = Op.getOperand(1);
5246 
5247   // Avoid adding defined bits with the zero_extend.
5248   if (Hi.isUndef()) {
5249     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5250     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5251     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5252   }
5253 
5254   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5255   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5256 
5257   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5258                               DAG.getConstant(16, SL, MVT::i32));
5259   if (Lo.isUndef())
5260     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5261 
5262   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5263   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5264 
5265   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5266   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5267 }
5268 
5269 bool
5270 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5271   // We can fold offsets for anything that doesn't require a GOT relocation.
5272   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5273           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5274           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5275          !shouldEmitGOTReloc(GA->getGlobal());
5276 }
5277 
5278 static SDValue
5279 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5280                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5281                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5282   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5283   // lowered to the following code sequence:
5284   //
5285   // For constant address space:
5286   //   s_getpc_b64 s[0:1]
5287   //   s_add_u32 s0, s0, $symbol
5288   //   s_addc_u32 s1, s1, 0
5289   //
5290   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5291   //   a fixup or relocation is emitted to replace $symbol with a literal
5292   //   constant, which is a pc-relative offset from the encoding of the $symbol
5293   //   operand to the global variable.
5294   //
5295   // For global address space:
5296   //   s_getpc_b64 s[0:1]
5297   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5298   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5299   //
5300   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5301   //   fixups or relocations are emitted to replace $symbol@*@lo and
5302   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5303   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5304   //   operand to the global variable.
5305   //
5306   // What we want here is an offset from the value returned by s_getpc
5307   // (which is the address of the s_add_u32 instruction) to the global
5308   // variable, but since the encoding of $symbol starts 4 bytes after the start
5309   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5310   // small. This requires us to add 4 to the global variable offset in order to
5311   // compute the correct address.
5312   SDValue PtrLo =
5313       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5314   SDValue PtrHi;
5315   if (GAFlags == SIInstrInfo::MO_NONE) {
5316     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5317   } else {
5318     PtrHi =
5319         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5320   }
5321   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5322 }
5323 
5324 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5325                                              SDValue Op,
5326                                              SelectionDAG &DAG) const {
5327   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5328   const GlobalValue *GV = GSD->getGlobal();
5329   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5330        shouldUseLDSConstAddress(GV)) ||
5331       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5332       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5333     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5334 
5335   SDLoc DL(GSD);
5336   EVT PtrVT = Op.getValueType();
5337 
5338   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5339     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5340                                             SIInstrInfo::MO_ABS32_LO);
5341     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5342   }
5343 
5344   if (shouldEmitFixup(GV))
5345     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5346   else if (shouldEmitPCReloc(GV))
5347     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5348                                    SIInstrInfo::MO_REL32);
5349 
5350   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5351                                             SIInstrInfo::MO_GOTPCREL32);
5352 
5353   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5354   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5355   const DataLayout &DataLayout = DAG.getDataLayout();
5356   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5357   MachinePointerInfo PtrInfo
5358     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5359 
5360   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5361                      MachineMemOperand::MODereferenceable |
5362                          MachineMemOperand::MOInvariant);
5363 }
5364 
5365 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5366                                    const SDLoc &DL, SDValue V) const {
5367   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5368   // the destination register.
5369   //
5370   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5371   // so we will end up with redundant moves to m0.
5372   //
5373   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5374 
5375   // A Null SDValue creates a glue result.
5376   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5377                                   V, Chain);
5378   return SDValue(M0, 0);
5379 }
5380 
5381 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5382                                                  SDValue Op,
5383                                                  MVT VT,
5384                                                  unsigned Offset) const {
5385   SDLoc SL(Op);
5386   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5387                                            DAG.getEntryNode(), Offset, 4, false);
5388   // The local size values will have the hi 16-bits as zero.
5389   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5390                      DAG.getValueType(VT));
5391 }
5392 
5393 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5394                                         EVT VT) {
5395   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5396                                       "non-hsa intrinsic with hsa target",
5397                                       DL.getDebugLoc());
5398   DAG.getContext()->diagnose(BadIntrin);
5399   return DAG.getUNDEF(VT);
5400 }
5401 
5402 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5403                                          EVT VT) {
5404   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5405                                       "intrinsic not supported on subtarget",
5406                                       DL.getDebugLoc());
5407   DAG.getContext()->diagnose(BadIntrin);
5408   return DAG.getUNDEF(VT);
5409 }
5410 
5411 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5412                                     ArrayRef<SDValue> Elts) {
5413   assert(!Elts.empty());
5414   MVT Type;
5415   unsigned NumElts;
5416 
5417   if (Elts.size() == 1) {
5418     Type = MVT::f32;
5419     NumElts = 1;
5420   } else if (Elts.size() == 2) {
5421     Type = MVT::v2f32;
5422     NumElts = 2;
5423   } else if (Elts.size() == 3) {
5424     Type = MVT::v3f32;
5425     NumElts = 3;
5426   } else if (Elts.size() <= 4) {
5427     Type = MVT::v4f32;
5428     NumElts = 4;
5429   } else if (Elts.size() <= 8) {
5430     Type = MVT::v8f32;
5431     NumElts = 8;
5432   } else {
5433     assert(Elts.size() <= 16);
5434     Type = MVT::v16f32;
5435     NumElts = 16;
5436   }
5437 
5438   SmallVector<SDValue, 16> VecElts(NumElts);
5439   for (unsigned i = 0; i < Elts.size(); ++i) {
5440     SDValue Elt = Elts[i];
5441     if (Elt.getValueType() != MVT::f32)
5442       Elt = DAG.getBitcast(MVT::f32, Elt);
5443     VecElts[i] = Elt;
5444   }
5445   for (unsigned i = Elts.size(); i < NumElts; ++i)
5446     VecElts[i] = DAG.getUNDEF(MVT::f32);
5447 
5448   if (NumElts == 1)
5449     return VecElts[0];
5450   return DAG.getBuildVector(Type, DL, VecElts);
5451 }
5452 
5453 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5454                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5455   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5456 
5457   uint64_t Value = CachePolicyConst->getZExtValue();
5458   SDLoc DL(CachePolicy);
5459   if (GLC) {
5460     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5461     Value &= ~(uint64_t)0x1;
5462   }
5463   if (SLC) {
5464     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5465     Value &= ~(uint64_t)0x2;
5466   }
5467   if (DLC) {
5468     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5469     Value &= ~(uint64_t)0x4;
5470   }
5471 
5472   return Value == 0;
5473 }
5474 
5475 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5476                               SDValue Src, int ExtraElts) {
5477   EVT SrcVT = Src.getValueType();
5478 
5479   SmallVector<SDValue, 8> Elts;
5480 
5481   if (SrcVT.isVector())
5482     DAG.ExtractVectorElements(Src, Elts);
5483   else
5484     Elts.push_back(Src);
5485 
5486   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5487   while (ExtraElts--)
5488     Elts.push_back(Undef);
5489 
5490   return DAG.getBuildVector(CastVT, DL, Elts);
5491 }
5492 
5493 // Re-construct the required return value for a image load intrinsic.
5494 // This is more complicated due to the optional use TexFailCtrl which means the required
5495 // return type is an aggregate
5496 static SDValue constructRetValue(SelectionDAG &DAG,
5497                                  MachineSDNode *Result,
5498                                  ArrayRef<EVT> ResultTypes,
5499                                  bool IsTexFail, bool Unpacked, bool IsD16,
5500                                  int DMaskPop, int NumVDataDwords,
5501                                  const SDLoc &DL, LLVMContext &Context) {
5502   // Determine the required return type. This is the same regardless of IsTexFail flag
5503   EVT ReqRetVT = ResultTypes[0];
5504   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5505   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5506     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5507 
5508   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5509     DMaskPop : (DMaskPop + 1) / 2;
5510 
5511   MVT DataDwordVT = NumDataDwords == 1 ?
5512     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5513 
5514   MVT MaskPopVT = MaskPopDwords == 1 ?
5515     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5516 
5517   SDValue Data(Result, 0);
5518   SDValue TexFail;
5519 
5520   if (IsTexFail) {
5521     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5522     if (MaskPopVT.isVector()) {
5523       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5524                          SDValue(Result, 0), ZeroIdx);
5525     } else {
5526       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5527                          SDValue(Result, 0), ZeroIdx);
5528     }
5529 
5530     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5531                           SDValue(Result, 0),
5532                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5533   }
5534 
5535   if (DataDwordVT.isVector())
5536     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5537                           NumDataDwords - MaskPopDwords);
5538 
5539   if (IsD16)
5540     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5541 
5542   if (!ReqRetVT.isVector())
5543     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5544 
5545   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5546 
5547   if (TexFail)
5548     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5549 
5550   if (Result->getNumValues() == 1)
5551     return Data;
5552 
5553   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5554 }
5555 
5556 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5557                          SDValue *LWE, bool &IsTexFail) {
5558   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5559 
5560   uint64_t Value = TexFailCtrlConst->getZExtValue();
5561   if (Value) {
5562     IsTexFail = true;
5563   }
5564 
5565   SDLoc DL(TexFailCtrlConst);
5566   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5567   Value &= ~(uint64_t)0x1;
5568   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5569   Value &= ~(uint64_t)0x2;
5570 
5571   return Value == 0;
5572 }
5573 
5574 SDValue SITargetLowering::lowerImage(SDValue Op,
5575                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5576                                      SelectionDAG &DAG) const {
5577   SDLoc DL(Op);
5578   MachineFunction &MF = DAG.getMachineFunction();
5579   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5580   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5581       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5582   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5583   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5584       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5585   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5586       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5587   unsigned IntrOpcode = Intr->BaseOpcode;
5588   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5589 
5590   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5591   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5592   bool IsD16 = false;
5593   bool IsA16 = false;
5594   SDValue VData;
5595   int NumVDataDwords;
5596   bool AdjustRetType = false;
5597 
5598   unsigned AddrIdx; // Index of first address argument
5599   unsigned DMask;
5600   unsigned DMaskLanes = 0;
5601 
5602   if (BaseOpcode->Atomic) {
5603     VData = Op.getOperand(2);
5604 
5605     bool Is64Bit = VData.getValueType() == MVT::i64;
5606     if (BaseOpcode->AtomicX2) {
5607       SDValue VData2 = Op.getOperand(3);
5608       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5609                                  {VData, VData2});
5610       if (Is64Bit)
5611         VData = DAG.getBitcast(MVT::v4i32, VData);
5612 
5613       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5614       DMask = Is64Bit ? 0xf : 0x3;
5615       NumVDataDwords = Is64Bit ? 4 : 2;
5616       AddrIdx = 4;
5617     } else {
5618       DMask = Is64Bit ? 0x3 : 0x1;
5619       NumVDataDwords = Is64Bit ? 2 : 1;
5620       AddrIdx = 3;
5621     }
5622   } else {
5623     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5624     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5625     DMask = DMaskConst->getZExtValue();
5626     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5627 
5628     if (BaseOpcode->Store) {
5629       VData = Op.getOperand(2);
5630 
5631       MVT StoreVT = VData.getSimpleValueType();
5632       if (StoreVT.getScalarType() == MVT::f16) {
5633         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5634           return Op; // D16 is unsupported for this instruction
5635 
5636         IsD16 = true;
5637         VData = handleD16VData(VData, DAG);
5638       }
5639 
5640       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5641     } else {
5642       // Work out the num dwords based on the dmask popcount and underlying type
5643       // and whether packing is supported.
5644       MVT LoadVT = ResultTypes[0].getSimpleVT();
5645       if (LoadVT.getScalarType() == MVT::f16) {
5646         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5647           return Op; // D16 is unsupported for this instruction
5648 
5649         IsD16 = true;
5650       }
5651 
5652       // Confirm that the return type is large enough for the dmask specified
5653       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5654           (!LoadVT.isVector() && DMaskLanes > 1))
5655           return Op;
5656 
5657       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5658         NumVDataDwords = (DMaskLanes + 1) / 2;
5659       else
5660         NumVDataDwords = DMaskLanes;
5661 
5662       AdjustRetType = true;
5663     }
5664 
5665     AddrIdx = DMaskIdx + 1;
5666   }
5667 
5668   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5669   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5670   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5671   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5672                        NumCoords + NumLCM;
5673   unsigned NumMIVAddrs = NumVAddrs;
5674 
5675   SmallVector<SDValue, 4> VAddrs;
5676 
5677   // Optimize _L to _LZ when _L is zero
5678   if (LZMappingInfo) {
5679     if (auto ConstantLod =
5680          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5681       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5682         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5683         NumMIVAddrs--;               // remove 'lod'
5684       }
5685     }
5686   }
5687 
5688   // Optimize _mip away, when 'lod' is zero
5689   if (MIPMappingInfo) {
5690     if (auto ConstantLod =
5691          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5692       if (ConstantLod->isNullValue()) {
5693         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5694         NumMIVAddrs--;               // remove 'lod'
5695       }
5696     }
5697   }
5698 
5699   // Check for 16 bit addresses and pack if true.
5700   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5701   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5702   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5703   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5704     // Illegal to use a16 images
5705     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5706       return Op;
5707 
5708     IsA16 = true;
5709     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5710     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5711       SDValue AddrLo;
5712       // Push back extra arguments.
5713       if (i < DimIdx) {
5714         AddrLo = Op.getOperand(i);
5715       } else {
5716         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5717         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5718         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5719             ((NumGradients / 2) % 2 == 1 &&
5720             (i == DimIdx + (NumGradients / 2) - 1 ||
5721              i == DimIdx + NumGradients - 1))) {
5722           AddrLo = Op.getOperand(i);
5723           if (AddrLo.getValueType() != MVT::i16)
5724             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5725           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5726         } else {
5727           AddrLo = DAG.getBuildVector(VectorVT, DL,
5728                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5729           i++;
5730         }
5731         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5732       }
5733       VAddrs.push_back(AddrLo);
5734     }
5735   } else {
5736     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5737       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5738   }
5739 
5740   // If the register allocator cannot place the address registers contiguously
5741   // without introducing moves, then using the non-sequential address encoding
5742   // is always preferable, since it saves VALU instructions and is usually a
5743   // wash in terms of code size or even better.
5744   //
5745   // However, we currently have no way of hinting to the register allocator that
5746   // MIMG addresses should be placed contiguously when it is possible to do so,
5747   // so force non-NSA for the common 2-address case as a heuristic.
5748   //
5749   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5750   // allocation when possible.
5751   bool UseNSA =
5752       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5753   SDValue VAddr;
5754   if (!UseNSA)
5755     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5756 
5757   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5758   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5759   unsigned CtrlIdx; // Index of texfailctrl argument
5760   SDValue Unorm;
5761   if (!BaseOpcode->Sampler) {
5762     Unorm = True;
5763     CtrlIdx = AddrIdx + NumVAddrs + 1;
5764   } else {
5765     auto UnormConst =
5766         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5767 
5768     Unorm = UnormConst->getZExtValue() ? True : False;
5769     CtrlIdx = AddrIdx + NumVAddrs + 3;
5770   }
5771 
5772   SDValue TFE;
5773   SDValue LWE;
5774   SDValue TexFail = Op.getOperand(CtrlIdx);
5775   bool IsTexFail = false;
5776   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5777     return Op;
5778 
5779   if (IsTexFail) {
5780     if (!DMaskLanes) {
5781       // Expecting to get an error flag since TFC is on - and dmask is 0
5782       // Force dmask to be at least 1 otherwise the instruction will fail
5783       DMask = 0x1;
5784       DMaskLanes = 1;
5785       NumVDataDwords = 1;
5786     }
5787     NumVDataDwords += 1;
5788     AdjustRetType = true;
5789   }
5790 
5791   // Has something earlier tagged that the return type needs adjusting
5792   // This happens if the instruction is a load or has set TexFailCtrl flags
5793   if (AdjustRetType) {
5794     // NumVDataDwords reflects the true number of dwords required in the return type
5795     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5796       // This is a no-op load. This can be eliminated
5797       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5798       if (isa<MemSDNode>(Op))
5799         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5800       return Undef;
5801     }
5802 
5803     EVT NewVT = NumVDataDwords > 1 ?
5804                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5805                 : MVT::i32;
5806 
5807     ResultTypes[0] = NewVT;
5808     if (ResultTypes.size() == 3) {
5809       // Original result was aggregate type used for TexFailCtrl results
5810       // The actual instruction returns as a vector type which has now been
5811       // created. Remove the aggregate result.
5812       ResultTypes.erase(&ResultTypes[1]);
5813     }
5814   }
5815 
5816   SDValue GLC;
5817   SDValue SLC;
5818   SDValue DLC;
5819   if (BaseOpcode->Atomic) {
5820     GLC = True; // TODO no-return optimization
5821     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5822                           IsGFX10 ? &DLC : nullptr))
5823       return Op;
5824   } else {
5825     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5826                           IsGFX10 ? &DLC : nullptr))
5827       return Op;
5828   }
5829 
5830   SmallVector<SDValue, 26> Ops;
5831   if (BaseOpcode->Store || BaseOpcode->Atomic)
5832     Ops.push_back(VData); // vdata
5833   if (UseNSA) {
5834     for (const SDValue &Addr : VAddrs)
5835       Ops.push_back(Addr);
5836   } else {
5837     Ops.push_back(VAddr);
5838   }
5839   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5840   if (BaseOpcode->Sampler)
5841     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5842   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5843   if (IsGFX10)
5844     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5845   Ops.push_back(Unorm);
5846   if (IsGFX10)
5847     Ops.push_back(DLC);
5848   Ops.push_back(GLC);
5849   Ops.push_back(SLC);
5850   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5851                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5852   if (IsGFX10)
5853     Ops.push_back(IsA16 ? True : False);
5854   Ops.push_back(TFE);
5855   Ops.push_back(LWE);
5856   if (!IsGFX10)
5857     Ops.push_back(DimInfo->DA ? True : False);
5858   if (BaseOpcode->HasD16)
5859     Ops.push_back(IsD16 ? True : False);
5860   if (isa<MemSDNode>(Op))
5861     Ops.push_back(Op.getOperand(0)); // chain
5862 
5863   int NumVAddrDwords =
5864       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5865   int Opcode = -1;
5866 
5867   if (IsGFX10) {
5868     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5869                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5870                                           : AMDGPU::MIMGEncGfx10Default,
5871                                    NumVDataDwords, NumVAddrDwords);
5872   } else {
5873     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5874       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5875                                      NumVDataDwords, NumVAddrDwords);
5876     if (Opcode == -1)
5877       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5878                                      NumVDataDwords, NumVAddrDwords);
5879   }
5880   assert(Opcode != -1);
5881 
5882   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5883   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5884     MachineMemOperand *MemRef = MemOp->getMemOperand();
5885     DAG.setNodeMemRefs(NewNode, {MemRef});
5886   }
5887 
5888   if (BaseOpcode->AtomicX2) {
5889     SmallVector<SDValue, 1> Elt;
5890     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5891     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5892   } else if (!BaseOpcode->Store) {
5893     return constructRetValue(DAG, NewNode,
5894                              OrigResultTypes, IsTexFail,
5895                              Subtarget->hasUnpackedD16VMem(), IsD16,
5896                              DMaskLanes, NumVDataDwords, DL,
5897                              *DAG.getContext());
5898   }
5899 
5900   return SDValue(NewNode, 0);
5901 }
5902 
5903 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5904                                        SDValue Offset, SDValue CachePolicy,
5905                                        SelectionDAG &DAG) const {
5906   MachineFunction &MF = DAG.getMachineFunction();
5907 
5908   const DataLayout &DataLayout = DAG.getDataLayout();
5909   Align Alignment =
5910       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
5911 
5912   MachineMemOperand *MMO = MF.getMachineMemOperand(
5913       MachinePointerInfo(),
5914       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5915           MachineMemOperand::MOInvariant,
5916       VT.getStoreSize(), Alignment);
5917 
5918   if (!Offset->isDivergent()) {
5919     SDValue Ops[] = {
5920         Rsrc,
5921         Offset, // Offset
5922         CachePolicy
5923     };
5924 
5925     // Widen vec3 load to vec4.
5926     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5927       EVT WidenedVT =
5928           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5929       auto WidenedOp = DAG.getMemIntrinsicNode(
5930           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5931           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5932       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5933                                    DAG.getVectorIdxConstant(0, DL));
5934       return Subvector;
5935     }
5936 
5937     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5938                                    DAG.getVTList(VT), Ops, VT, MMO);
5939   }
5940 
5941   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5942   // assume that the buffer is unswizzled.
5943   SmallVector<SDValue, 4> Loads;
5944   unsigned NumLoads = 1;
5945   MVT LoadVT = VT.getSimpleVT();
5946   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5947   assert((LoadVT.getScalarType() == MVT::i32 ||
5948           LoadVT.getScalarType() == MVT::f32));
5949 
5950   if (NumElts == 8 || NumElts == 16) {
5951     NumLoads = NumElts / 4;
5952     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5953   }
5954 
5955   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5956   SDValue Ops[] = {
5957       DAG.getEntryNode(),                               // Chain
5958       Rsrc,                                             // rsrc
5959       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5960       {},                                               // voffset
5961       {},                                               // soffset
5962       {},                                               // offset
5963       CachePolicy,                                      // cachepolicy
5964       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5965   };
5966 
5967   // Use the alignment to ensure that the required offsets will fit into the
5968   // immediate offsets.
5969   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5970 
5971   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5972   for (unsigned i = 0; i < NumLoads; ++i) {
5973     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5974     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5975                                         LoadVT, MMO, DAG));
5976   }
5977 
5978   if (NumElts == 8 || NumElts == 16)
5979     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5980 
5981   return Loads[0];
5982 }
5983 
5984 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5985                                                   SelectionDAG &DAG) const {
5986   MachineFunction &MF = DAG.getMachineFunction();
5987   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5988 
5989   EVT VT = Op.getValueType();
5990   SDLoc DL(Op);
5991   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5992 
5993   // TODO: Should this propagate fast-math-flags?
5994 
5995   switch (IntrinsicID) {
5996   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5997     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5998       return emitNonHSAIntrinsicError(DAG, DL, VT);
5999     return getPreloadedValue(DAG, *MFI, VT,
6000                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6001   }
6002   case Intrinsic::amdgcn_dispatch_ptr:
6003   case Intrinsic::amdgcn_queue_ptr: {
6004     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6005       DiagnosticInfoUnsupported BadIntrin(
6006           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6007           DL.getDebugLoc());
6008       DAG.getContext()->diagnose(BadIntrin);
6009       return DAG.getUNDEF(VT);
6010     }
6011 
6012     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6013       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6014     return getPreloadedValue(DAG, *MFI, VT, RegID);
6015   }
6016   case Intrinsic::amdgcn_implicitarg_ptr: {
6017     if (MFI->isEntryFunction())
6018       return getImplicitArgPtr(DAG, DL);
6019     return getPreloadedValue(DAG, *MFI, VT,
6020                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6021   }
6022   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6023     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6024       // This only makes sense to call in a kernel, so just lower to null.
6025       return DAG.getConstant(0, DL, VT);
6026     }
6027 
6028     return getPreloadedValue(DAG, *MFI, VT,
6029                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6030   }
6031   case Intrinsic::amdgcn_dispatch_id: {
6032     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6033   }
6034   case Intrinsic::amdgcn_rcp:
6035     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6036   case Intrinsic::amdgcn_rsq:
6037     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6038   case Intrinsic::amdgcn_rsq_legacy:
6039     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6040       return emitRemovedIntrinsicError(DAG, DL, VT);
6041     return SDValue();
6042   case Intrinsic::amdgcn_rcp_legacy:
6043     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6044       return emitRemovedIntrinsicError(DAG, DL, VT);
6045     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6046   case Intrinsic::amdgcn_rsq_clamp: {
6047     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6048       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6049 
6050     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6051     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6052     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6053 
6054     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6055     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6056                               DAG.getConstantFP(Max, DL, VT));
6057     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6058                        DAG.getConstantFP(Min, DL, VT));
6059   }
6060   case Intrinsic::r600_read_ngroups_x:
6061     if (Subtarget->isAmdHsaOS())
6062       return emitNonHSAIntrinsicError(DAG, DL, VT);
6063 
6064     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6065                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6066   case Intrinsic::r600_read_ngroups_y:
6067     if (Subtarget->isAmdHsaOS())
6068       return emitNonHSAIntrinsicError(DAG, DL, VT);
6069 
6070     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6071                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6072   case Intrinsic::r600_read_ngroups_z:
6073     if (Subtarget->isAmdHsaOS())
6074       return emitNonHSAIntrinsicError(DAG, DL, VT);
6075 
6076     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6077                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6078   case Intrinsic::r600_read_global_size_x:
6079     if (Subtarget->isAmdHsaOS())
6080       return emitNonHSAIntrinsicError(DAG, DL, VT);
6081 
6082     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6083                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6084   case Intrinsic::r600_read_global_size_y:
6085     if (Subtarget->isAmdHsaOS())
6086       return emitNonHSAIntrinsicError(DAG, DL, VT);
6087 
6088     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6089                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6090   case Intrinsic::r600_read_global_size_z:
6091     if (Subtarget->isAmdHsaOS())
6092       return emitNonHSAIntrinsicError(DAG, DL, VT);
6093 
6094     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6095                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6096   case Intrinsic::r600_read_local_size_x:
6097     if (Subtarget->isAmdHsaOS())
6098       return emitNonHSAIntrinsicError(DAG, DL, VT);
6099 
6100     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6101                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6102   case Intrinsic::r600_read_local_size_y:
6103     if (Subtarget->isAmdHsaOS())
6104       return emitNonHSAIntrinsicError(DAG, DL, VT);
6105 
6106     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6107                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6108   case Intrinsic::r600_read_local_size_z:
6109     if (Subtarget->isAmdHsaOS())
6110       return emitNonHSAIntrinsicError(DAG, DL, VT);
6111 
6112     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6113                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6114   case Intrinsic::amdgcn_workgroup_id_x:
6115     return getPreloadedValue(DAG, *MFI, VT,
6116                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6117   case Intrinsic::amdgcn_workgroup_id_y:
6118     return getPreloadedValue(DAG, *MFI, VT,
6119                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6120   case Intrinsic::amdgcn_workgroup_id_z:
6121     return getPreloadedValue(DAG, *MFI, VT,
6122                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6123   case Intrinsic::amdgcn_workitem_id_x:
6124     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6125                           SDLoc(DAG.getEntryNode()),
6126                           MFI->getArgInfo().WorkItemIDX);
6127   case Intrinsic::amdgcn_workitem_id_y:
6128     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6129                           SDLoc(DAG.getEntryNode()),
6130                           MFI->getArgInfo().WorkItemIDY);
6131   case Intrinsic::amdgcn_workitem_id_z:
6132     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6133                           SDLoc(DAG.getEntryNode()),
6134                           MFI->getArgInfo().WorkItemIDZ);
6135   case Intrinsic::amdgcn_wavefrontsize:
6136     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6137                            SDLoc(Op), MVT::i32);
6138   case Intrinsic::amdgcn_s_buffer_load: {
6139     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6140     SDValue GLC;
6141     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6142     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6143                           IsGFX10 ? &DLC : nullptr))
6144       return Op;
6145     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6146                         DAG);
6147   }
6148   case Intrinsic::amdgcn_fdiv_fast:
6149     return lowerFDIV_FAST(Op, DAG);
6150   case Intrinsic::amdgcn_sin:
6151     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6152 
6153   case Intrinsic::amdgcn_cos:
6154     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6155 
6156   case Intrinsic::amdgcn_mul_u24:
6157     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6158   case Intrinsic::amdgcn_mul_i24:
6159     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6160 
6161   case Intrinsic::amdgcn_log_clamp: {
6162     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6163       return SDValue();
6164 
6165     DiagnosticInfoUnsupported BadIntrin(
6166       MF.getFunction(), "intrinsic not supported on subtarget",
6167       DL.getDebugLoc());
6168       DAG.getContext()->diagnose(BadIntrin);
6169       return DAG.getUNDEF(VT);
6170   }
6171   case Intrinsic::amdgcn_ldexp:
6172     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6173                        Op.getOperand(1), Op.getOperand(2));
6174 
6175   case Intrinsic::amdgcn_fract:
6176     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6177 
6178   case Intrinsic::amdgcn_class:
6179     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6180                        Op.getOperand(1), Op.getOperand(2));
6181   case Intrinsic::amdgcn_div_fmas:
6182     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6183                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6184                        Op.getOperand(4));
6185 
6186   case Intrinsic::amdgcn_div_fixup:
6187     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6188                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6189 
6190   case Intrinsic::amdgcn_trig_preop:
6191     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
6192                        Op.getOperand(1), Op.getOperand(2));
6193   case Intrinsic::amdgcn_div_scale: {
6194     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6195 
6196     // Translate to the operands expected by the machine instruction. The
6197     // first parameter must be the same as the first instruction.
6198     SDValue Numerator = Op.getOperand(1);
6199     SDValue Denominator = Op.getOperand(2);
6200 
6201     // Note this order is opposite of the machine instruction's operations,
6202     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6203     // intrinsic has the numerator as the first operand to match a normal
6204     // division operation.
6205 
6206     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6207 
6208     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6209                        Denominator, Numerator);
6210   }
6211   case Intrinsic::amdgcn_icmp: {
6212     // There is a Pat that handles this variant, so return it as-is.
6213     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6214         Op.getConstantOperandVal(2) == 0 &&
6215         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6216       return Op;
6217     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6218   }
6219   case Intrinsic::amdgcn_fcmp: {
6220     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6221   }
6222   case Intrinsic::amdgcn_ballot:
6223     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6224   case Intrinsic::amdgcn_fmed3:
6225     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6226                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6227   case Intrinsic::amdgcn_fdot2:
6228     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6229                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6230                        Op.getOperand(4));
6231   case Intrinsic::amdgcn_fmul_legacy:
6232     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6233                        Op.getOperand(1), Op.getOperand(2));
6234   case Intrinsic::amdgcn_sffbh:
6235     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6236   case Intrinsic::amdgcn_sbfe:
6237     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6238                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6239   case Intrinsic::amdgcn_ubfe:
6240     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6241                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6242   case Intrinsic::amdgcn_cvt_pkrtz:
6243   case Intrinsic::amdgcn_cvt_pknorm_i16:
6244   case Intrinsic::amdgcn_cvt_pknorm_u16:
6245   case Intrinsic::amdgcn_cvt_pk_i16:
6246   case Intrinsic::amdgcn_cvt_pk_u16: {
6247     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6248     EVT VT = Op.getValueType();
6249     unsigned Opcode;
6250 
6251     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6252       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6253     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6254       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6255     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6256       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6257     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6258       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6259     else
6260       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6261 
6262     if (isTypeLegal(VT))
6263       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6264 
6265     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6266                                Op.getOperand(1), Op.getOperand(2));
6267     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6268   }
6269   case Intrinsic::amdgcn_fmad_ftz:
6270     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6271                        Op.getOperand(2), Op.getOperand(3));
6272 
6273   case Intrinsic::amdgcn_if_break:
6274     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6275                                       Op->getOperand(1), Op->getOperand(2)), 0);
6276 
6277   case Intrinsic::amdgcn_groupstaticsize: {
6278     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6279     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6280       return Op;
6281 
6282     const Module *M = MF.getFunction().getParent();
6283     const GlobalValue *GV =
6284         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6285     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6286                                             SIInstrInfo::MO_ABS32_LO);
6287     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6288   }
6289   case Intrinsic::amdgcn_is_shared:
6290   case Intrinsic::amdgcn_is_private: {
6291     SDLoc SL(Op);
6292     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6293       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6294     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6295     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6296                                  Op.getOperand(1));
6297 
6298     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6299                                 DAG.getConstant(1, SL, MVT::i32));
6300     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6301   }
6302   case Intrinsic::amdgcn_alignbit:
6303     return DAG.getNode(ISD::FSHR, DL, VT,
6304                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6305   case Intrinsic::amdgcn_reloc_constant: {
6306     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6307     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6308     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6309     auto RelocSymbol = cast<GlobalVariable>(
6310         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6311     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6312                                             SIInstrInfo::MO_ABS32_LO);
6313     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6314   }
6315   default:
6316     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6317             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6318       return lowerImage(Op, ImageDimIntr, DAG);
6319 
6320     return Op;
6321   }
6322 }
6323 
6324 // This function computes an appropriate offset to pass to
6325 // MachineMemOperand::setOffset() based on the offset inputs to
6326 // an intrinsic.  If any of the offsets are non-contstant or
6327 // if VIndex is non-zero then this function returns 0.  Otherwise,
6328 // it returns the sum of VOffset, SOffset, and Offset.
6329 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6330                                       SDValue SOffset,
6331                                       SDValue Offset,
6332                                       SDValue VIndex = SDValue()) {
6333 
6334   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6335       !isa<ConstantSDNode>(Offset))
6336     return 0;
6337 
6338   if (VIndex) {
6339     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6340       return 0;
6341   }
6342 
6343   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6344          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6345          cast<ConstantSDNode>(Offset)->getSExtValue();
6346 }
6347 
6348 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6349   switch (MF.getFunction().getCallingConv()) {
6350   case CallingConv::AMDGPU_PS:
6351     return 1;
6352   case CallingConv::AMDGPU_VS:
6353     return 2;
6354   case CallingConv::AMDGPU_GS:
6355     return 3;
6356   case CallingConv::AMDGPU_HS:
6357   case CallingConv::AMDGPU_LS:
6358   case CallingConv::AMDGPU_ES:
6359     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6360   case CallingConv::AMDGPU_CS:
6361   case CallingConv::AMDGPU_KERNEL:
6362   case CallingConv::C:
6363   case CallingConv::Fast:
6364   default:
6365     // Assume other calling conventions are various compute callable functions
6366     return 0;
6367   }
6368 }
6369 
6370 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6371                                                  SelectionDAG &DAG) const {
6372   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6373   SDLoc DL(Op);
6374 
6375   switch (IntrID) {
6376   case Intrinsic::amdgcn_ds_ordered_add:
6377   case Intrinsic::amdgcn_ds_ordered_swap: {
6378     MemSDNode *M = cast<MemSDNode>(Op);
6379     SDValue Chain = M->getOperand(0);
6380     SDValue M0 = M->getOperand(2);
6381     SDValue Value = M->getOperand(3);
6382     unsigned IndexOperand = M->getConstantOperandVal(7);
6383     unsigned WaveRelease = M->getConstantOperandVal(8);
6384     unsigned WaveDone = M->getConstantOperandVal(9);
6385 
6386     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6387     IndexOperand &= ~0x3f;
6388     unsigned CountDw = 0;
6389 
6390     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6391       CountDw = (IndexOperand >> 24) & 0xf;
6392       IndexOperand &= ~(0xf << 24);
6393 
6394       if (CountDw < 1 || CountDw > 4) {
6395         report_fatal_error(
6396             "ds_ordered_count: dword count must be between 1 and 4");
6397       }
6398     }
6399 
6400     if (IndexOperand)
6401       report_fatal_error("ds_ordered_count: bad index operand");
6402 
6403     if (WaveDone && !WaveRelease)
6404       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6405 
6406     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6407     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6408     unsigned Offset0 = OrderedCountIndex << 2;
6409     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6410                        (Instruction << 4);
6411 
6412     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6413       Offset1 |= (CountDw - 1) << 6;
6414 
6415     unsigned Offset = Offset0 | (Offset1 << 8);
6416 
6417     SDValue Ops[] = {
6418       Chain,
6419       Value,
6420       DAG.getTargetConstant(Offset, DL, MVT::i16),
6421       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6422     };
6423     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6424                                    M->getVTList(), Ops, M->getMemoryVT(),
6425                                    M->getMemOperand());
6426   }
6427   case Intrinsic::amdgcn_ds_fadd: {
6428     MemSDNode *M = cast<MemSDNode>(Op);
6429     unsigned Opc;
6430     switch (IntrID) {
6431     case Intrinsic::amdgcn_ds_fadd:
6432       Opc = ISD::ATOMIC_LOAD_FADD;
6433       break;
6434     }
6435 
6436     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6437                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6438                          M->getMemOperand());
6439   }
6440   case Intrinsic::amdgcn_atomic_inc:
6441   case Intrinsic::amdgcn_atomic_dec:
6442   case Intrinsic::amdgcn_ds_fmin:
6443   case Intrinsic::amdgcn_ds_fmax: {
6444     MemSDNode *M = cast<MemSDNode>(Op);
6445     unsigned Opc;
6446     switch (IntrID) {
6447     case Intrinsic::amdgcn_atomic_inc:
6448       Opc = AMDGPUISD::ATOMIC_INC;
6449       break;
6450     case Intrinsic::amdgcn_atomic_dec:
6451       Opc = AMDGPUISD::ATOMIC_DEC;
6452       break;
6453     case Intrinsic::amdgcn_ds_fmin:
6454       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6455       break;
6456     case Intrinsic::amdgcn_ds_fmax:
6457       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6458       break;
6459     default:
6460       llvm_unreachable("Unknown intrinsic!");
6461     }
6462     SDValue Ops[] = {
6463       M->getOperand(0), // Chain
6464       M->getOperand(2), // Ptr
6465       M->getOperand(3)  // Value
6466     };
6467 
6468     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6469                                    M->getMemoryVT(), M->getMemOperand());
6470   }
6471   case Intrinsic::amdgcn_buffer_load:
6472   case Intrinsic::amdgcn_buffer_load_format: {
6473     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6474     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6475     unsigned IdxEn = 1;
6476     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6477       IdxEn = Idx->getZExtValue() != 0;
6478     SDValue Ops[] = {
6479       Op.getOperand(0), // Chain
6480       Op.getOperand(2), // rsrc
6481       Op.getOperand(3), // vindex
6482       SDValue(),        // voffset -- will be set by setBufferOffsets
6483       SDValue(),        // soffset -- will be set by setBufferOffsets
6484       SDValue(),        // offset -- will be set by setBufferOffsets
6485       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6486       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6487     };
6488 
6489     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6490     // We don't know the offset if vindex is non-zero, so clear it.
6491     if (IdxEn)
6492       Offset = 0;
6493 
6494     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6495         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6496 
6497     EVT VT = Op.getValueType();
6498     EVT IntVT = VT.changeTypeToInteger();
6499     auto *M = cast<MemSDNode>(Op);
6500     M->getMemOperand()->setOffset(Offset);
6501     EVT LoadVT = Op.getValueType();
6502 
6503     if (LoadVT.getScalarType() == MVT::f16)
6504       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6505                                  M, DAG, Ops);
6506 
6507     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6508     if (LoadVT.getScalarType() == MVT::i8 ||
6509         LoadVT.getScalarType() == MVT::i16)
6510       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6511 
6512     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6513                                M->getMemOperand(), DAG);
6514   }
6515   case Intrinsic::amdgcn_raw_buffer_load:
6516   case Intrinsic::amdgcn_raw_buffer_load_format: {
6517     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6518 
6519     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6520     SDValue Ops[] = {
6521       Op.getOperand(0), // Chain
6522       Op.getOperand(2), // rsrc
6523       DAG.getConstant(0, DL, MVT::i32), // vindex
6524       Offsets.first,    // voffset
6525       Op.getOperand(4), // soffset
6526       Offsets.second,   // offset
6527       Op.getOperand(5), // cachepolicy, swizzled buffer
6528       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6529     };
6530 
6531     auto *M = cast<MemSDNode>(Op);
6532     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6533     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6534   }
6535   case Intrinsic::amdgcn_struct_buffer_load:
6536   case Intrinsic::amdgcn_struct_buffer_load_format: {
6537     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6538 
6539     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6540     SDValue Ops[] = {
6541       Op.getOperand(0), // Chain
6542       Op.getOperand(2), // rsrc
6543       Op.getOperand(3), // vindex
6544       Offsets.first,    // voffset
6545       Op.getOperand(5), // soffset
6546       Offsets.second,   // offset
6547       Op.getOperand(6), // cachepolicy, swizzled buffer
6548       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6549     };
6550 
6551     auto *M = cast<MemSDNode>(Op);
6552     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6553                                                         Ops[2]));
6554     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6555   }
6556   case Intrinsic::amdgcn_tbuffer_load: {
6557     MemSDNode *M = cast<MemSDNode>(Op);
6558     EVT LoadVT = Op.getValueType();
6559 
6560     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6561     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6562     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6563     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6564     unsigned IdxEn = 1;
6565     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6566       IdxEn = Idx->getZExtValue() != 0;
6567     SDValue Ops[] = {
6568       Op.getOperand(0),  // Chain
6569       Op.getOperand(2),  // rsrc
6570       Op.getOperand(3),  // vindex
6571       Op.getOperand(4),  // voffset
6572       Op.getOperand(5),  // soffset
6573       Op.getOperand(6),  // offset
6574       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6575       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6576       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6577     };
6578 
6579     if (LoadVT.getScalarType() == MVT::f16)
6580       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6581                                  M, DAG, Ops);
6582     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6583                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6584                                DAG);
6585   }
6586   case Intrinsic::amdgcn_raw_tbuffer_load: {
6587     MemSDNode *M = cast<MemSDNode>(Op);
6588     EVT LoadVT = Op.getValueType();
6589     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6590 
6591     SDValue Ops[] = {
6592       Op.getOperand(0),  // Chain
6593       Op.getOperand(2),  // rsrc
6594       DAG.getConstant(0, DL, MVT::i32), // vindex
6595       Offsets.first,     // voffset
6596       Op.getOperand(4),  // soffset
6597       Offsets.second,    // offset
6598       Op.getOperand(5),  // format
6599       Op.getOperand(6),  // cachepolicy, swizzled buffer
6600       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6601     };
6602 
6603     if (LoadVT.getScalarType() == MVT::f16)
6604       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6605                                  M, DAG, Ops);
6606     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6607                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6608                                DAG);
6609   }
6610   case Intrinsic::amdgcn_struct_tbuffer_load: {
6611     MemSDNode *M = cast<MemSDNode>(Op);
6612     EVT LoadVT = Op.getValueType();
6613     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6614 
6615     SDValue Ops[] = {
6616       Op.getOperand(0),  // Chain
6617       Op.getOperand(2),  // rsrc
6618       Op.getOperand(3),  // vindex
6619       Offsets.first,     // voffset
6620       Op.getOperand(5),  // soffset
6621       Offsets.second,    // offset
6622       Op.getOperand(6),  // format
6623       Op.getOperand(7),  // cachepolicy, swizzled buffer
6624       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6625     };
6626 
6627     if (LoadVT.getScalarType() == MVT::f16)
6628       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6629                                  M, DAG, Ops);
6630     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6631                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6632                                DAG);
6633   }
6634   case Intrinsic::amdgcn_buffer_atomic_swap:
6635   case Intrinsic::amdgcn_buffer_atomic_add:
6636   case Intrinsic::amdgcn_buffer_atomic_sub:
6637   case Intrinsic::amdgcn_buffer_atomic_smin:
6638   case Intrinsic::amdgcn_buffer_atomic_umin:
6639   case Intrinsic::amdgcn_buffer_atomic_smax:
6640   case Intrinsic::amdgcn_buffer_atomic_umax:
6641   case Intrinsic::amdgcn_buffer_atomic_and:
6642   case Intrinsic::amdgcn_buffer_atomic_or:
6643   case Intrinsic::amdgcn_buffer_atomic_xor: {
6644     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6645     unsigned IdxEn = 1;
6646     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6647       IdxEn = Idx->getZExtValue() != 0;
6648     SDValue Ops[] = {
6649       Op.getOperand(0), // Chain
6650       Op.getOperand(2), // vdata
6651       Op.getOperand(3), // rsrc
6652       Op.getOperand(4), // vindex
6653       SDValue(),        // voffset -- will be set by setBufferOffsets
6654       SDValue(),        // soffset -- will be set by setBufferOffsets
6655       SDValue(),        // offset -- will be set by setBufferOffsets
6656       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6657       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6658     };
6659     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6660     // We don't know the offset if vindex is non-zero, so clear it.
6661     if (IdxEn)
6662       Offset = 0;
6663     EVT VT = Op.getValueType();
6664 
6665     auto *M = cast<MemSDNode>(Op);
6666     M->getMemOperand()->setOffset(Offset);
6667     unsigned Opcode = 0;
6668 
6669     switch (IntrID) {
6670     case Intrinsic::amdgcn_buffer_atomic_swap:
6671       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6672       break;
6673     case Intrinsic::amdgcn_buffer_atomic_add:
6674       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6675       break;
6676     case Intrinsic::amdgcn_buffer_atomic_sub:
6677       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6678       break;
6679     case Intrinsic::amdgcn_buffer_atomic_smin:
6680       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6681       break;
6682     case Intrinsic::amdgcn_buffer_atomic_umin:
6683       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6684       break;
6685     case Intrinsic::amdgcn_buffer_atomic_smax:
6686       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6687       break;
6688     case Intrinsic::amdgcn_buffer_atomic_umax:
6689       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6690       break;
6691     case Intrinsic::amdgcn_buffer_atomic_and:
6692       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6693       break;
6694     case Intrinsic::amdgcn_buffer_atomic_or:
6695       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6696       break;
6697     case Intrinsic::amdgcn_buffer_atomic_xor:
6698       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6699       break;
6700     default:
6701       llvm_unreachable("unhandled atomic opcode");
6702     }
6703 
6704     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6705                                    M->getMemOperand());
6706   }
6707   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6708   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6709   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6710   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6711   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6712   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6713   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6714   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6715   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6716   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6717   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6718   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6719     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6720     SDValue Ops[] = {
6721       Op.getOperand(0), // Chain
6722       Op.getOperand(2), // vdata
6723       Op.getOperand(3), // rsrc
6724       DAG.getConstant(0, DL, MVT::i32), // vindex
6725       Offsets.first,    // voffset
6726       Op.getOperand(5), // soffset
6727       Offsets.second,   // offset
6728       Op.getOperand(6), // cachepolicy
6729       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6730     };
6731     EVT VT = Op.getValueType();
6732 
6733     auto *M = cast<MemSDNode>(Op);
6734     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6735     unsigned Opcode = 0;
6736 
6737     switch (IntrID) {
6738     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6739       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6740       break;
6741     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6742       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6743       break;
6744     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6745       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6746       break;
6747     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6748       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6749       break;
6750     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6751       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6752       break;
6753     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6754       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6755       break;
6756     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6757       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6758       break;
6759     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6760       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6761       break;
6762     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6763       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6764       break;
6765     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6766       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6767       break;
6768     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6769       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6770       break;
6771     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6772       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6773       break;
6774     default:
6775       llvm_unreachable("unhandled atomic opcode");
6776     }
6777 
6778     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6779                                    M->getMemOperand());
6780   }
6781   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6782   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6783   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6784   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6785   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6786   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6787   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6788   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6789   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6790   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6791   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6792   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6793     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6794     SDValue Ops[] = {
6795       Op.getOperand(0), // Chain
6796       Op.getOperand(2), // vdata
6797       Op.getOperand(3), // rsrc
6798       Op.getOperand(4), // vindex
6799       Offsets.first,    // voffset
6800       Op.getOperand(6), // soffset
6801       Offsets.second,   // offset
6802       Op.getOperand(7), // cachepolicy
6803       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6804     };
6805     EVT VT = Op.getValueType();
6806 
6807     auto *M = cast<MemSDNode>(Op);
6808     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6809                                                         Ops[3]));
6810     unsigned Opcode = 0;
6811 
6812     switch (IntrID) {
6813     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6814       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6815       break;
6816     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6817       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6818       break;
6819     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6820       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6821       break;
6822     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6823       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6824       break;
6825     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6826       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6827       break;
6828     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6829       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6830       break;
6831     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6832       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6833       break;
6834     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6835       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6836       break;
6837     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6838       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6839       break;
6840     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6841       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6842       break;
6843     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6844       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6845       break;
6846     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6847       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6848       break;
6849     default:
6850       llvm_unreachable("unhandled atomic opcode");
6851     }
6852 
6853     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6854                                    M->getMemOperand());
6855   }
6856   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6857     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6858     unsigned IdxEn = 1;
6859     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6860       IdxEn = Idx->getZExtValue() != 0;
6861     SDValue Ops[] = {
6862       Op.getOperand(0), // Chain
6863       Op.getOperand(2), // src
6864       Op.getOperand(3), // cmp
6865       Op.getOperand(4), // rsrc
6866       Op.getOperand(5), // vindex
6867       SDValue(),        // voffset -- will be set by setBufferOffsets
6868       SDValue(),        // soffset -- will be set by setBufferOffsets
6869       SDValue(),        // offset -- will be set by setBufferOffsets
6870       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6871       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6872     };
6873     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6874     // We don't know the offset if vindex is non-zero, so clear it.
6875     if (IdxEn)
6876       Offset = 0;
6877     EVT VT = Op.getValueType();
6878     auto *M = cast<MemSDNode>(Op);
6879     M->getMemOperand()->setOffset(Offset);
6880 
6881     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6882                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6883   }
6884   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6885     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6886     SDValue Ops[] = {
6887       Op.getOperand(0), // Chain
6888       Op.getOperand(2), // src
6889       Op.getOperand(3), // cmp
6890       Op.getOperand(4), // rsrc
6891       DAG.getConstant(0, DL, MVT::i32), // vindex
6892       Offsets.first,    // voffset
6893       Op.getOperand(6), // soffset
6894       Offsets.second,   // offset
6895       Op.getOperand(7), // cachepolicy
6896       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6897     };
6898     EVT VT = Op.getValueType();
6899     auto *M = cast<MemSDNode>(Op);
6900     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6901 
6902     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6903                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6904   }
6905   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6906     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6907     SDValue Ops[] = {
6908       Op.getOperand(0), // Chain
6909       Op.getOperand(2), // src
6910       Op.getOperand(3), // cmp
6911       Op.getOperand(4), // rsrc
6912       Op.getOperand(5), // vindex
6913       Offsets.first,    // voffset
6914       Op.getOperand(7), // soffset
6915       Offsets.second,   // offset
6916       Op.getOperand(8), // cachepolicy
6917       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6918     };
6919     EVT VT = Op.getValueType();
6920     auto *M = cast<MemSDNode>(Op);
6921     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6922                                                         Ops[4]));
6923 
6924     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6925                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6926   }
6927 
6928   default:
6929     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6930             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6931       return lowerImage(Op, ImageDimIntr, DAG);
6932 
6933     return SDValue();
6934   }
6935 }
6936 
6937 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6938 // dwordx4 if on SI.
6939 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6940                                               SDVTList VTList,
6941                                               ArrayRef<SDValue> Ops, EVT MemVT,
6942                                               MachineMemOperand *MMO,
6943                                               SelectionDAG &DAG) const {
6944   EVT VT = VTList.VTs[0];
6945   EVT WidenedVT = VT;
6946   EVT WidenedMemVT = MemVT;
6947   if (!Subtarget->hasDwordx3LoadStores() &&
6948       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6949     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6950                                  WidenedVT.getVectorElementType(), 4);
6951     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6952                                     WidenedMemVT.getVectorElementType(), 4);
6953     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6954   }
6955 
6956   assert(VTList.NumVTs == 2);
6957   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6958 
6959   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6960                                        WidenedMemVT, MMO);
6961   if (WidenedVT != VT) {
6962     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6963                                DAG.getVectorIdxConstant(0, DL));
6964     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6965   }
6966   return NewOp;
6967 }
6968 
6969 SDValue SITargetLowering::handleD16VData(SDValue VData,
6970                                          SelectionDAG &DAG) const {
6971   EVT StoreVT = VData.getValueType();
6972 
6973   // No change for f16 and legal vector D16 types.
6974   if (!StoreVT.isVector())
6975     return VData;
6976 
6977   SDLoc DL(VData);
6978   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6979 
6980   if (Subtarget->hasUnpackedD16VMem()) {
6981     // We need to unpack the packed data to store.
6982     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6983     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6984 
6985     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6986                                         StoreVT.getVectorNumElements());
6987     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6988     return DAG.UnrollVectorOp(ZExt.getNode());
6989   }
6990 
6991   assert(isTypeLegal(StoreVT));
6992   return VData;
6993 }
6994 
6995 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6996                                               SelectionDAG &DAG) const {
6997   SDLoc DL(Op);
6998   SDValue Chain = Op.getOperand(0);
6999   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7000   MachineFunction &MF = DAG.getMachineFunction();
7001 
7002   switch (IntrinsicID) {
7003   case Intrinsic::amdgcn_exp_compr: {
7004     SDValue Src0 = Op.getOperand(4);
7005     SDValue Src1 = Op.getOperand(5);
7006     // Hack around illegal type on SI by directly selecting it.
7007     if (isTypeLegal(Src0.getValueType()))
7008       return SDValue();
7009 
7010     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7011     SDValue Undef = DAG.getUNDEF(MVT::f32);
7012     const SDValue Ops[] = {
7013       Op.getOperand(2), // tgt
7014       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7015       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7016       Undef, // src2
7017       Undef, // src3
7018       Op.getOperand(7), // vm
7019       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7020       Op.getOperand(3), // en
7021       Op.getOperand(0) // Chain
7022     };
7023 
7024     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7025     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7026   }
7027   case Intrinsic::amdgcn_s_barrier: {
7028     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7029       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7030       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7031       if (WGSize <= ST.getWavefrontSize())
7032         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7033                                           Op.getOperand(0)), 0);
7034     }
7035     return SDValue();
7036   };
7037   case Intrinsic::amdgcn_tbuffer_store: {
7038     SDValue VData = Op.getOperand(2);
7039     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7040     if (IsD16)
7041       VData = handleD16VData(VData, DAG);
7042     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7043     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7044     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7045     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7046     unsigned IdxEn = 1;
7047     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7048       IdxEn = Idx->getZExtValue() != 0;
7049     SDValue Ops[] = {
7050       Chain,
7051       VData,             // vdata
7052       Op.getOperand(3),  // rsrc
7053       Op.getOperand(4),  // vindex
7054       Op.getOperand(5),  // voffset
7055       Op.getOperand(6),  // soffset
7056       Op.getOperand(7),  // offset
7057       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7058       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7059       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7060     };
7061     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7062                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7063     MemSDNode *M = cast<MemSDNode>(Op);
7064     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7065                                    M->getMemoryVT(), M->getMemOperand());
7066   }
7067 
7068   case Intrinsic::amdgcn_struct_tbuffer_store: {
7069     SDValue VData = Op.getOperand(2);
7070     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7071     if (IsD16)
7072       VData = handleD16VData(VData, DAG);
7073     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7074     SDValue Ops[] = {
7075       Chain,
7076       VData,             // vdata
7077       Op.getOperand(3),  // rsrc
7078       Op.getOperand(4),  // vindex
7079       Offsets.first,     // voffset
7080       Op.getOperand(6),  // soffset
7081       Offsets.second,    // offset
7082       Op.getOperand(7),  // format
7083       Op.getOperand(8),  // cachepolicy, swizzled buffer
7084       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7085     };
7086     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7087                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7088     MemSDNode *M = cast<MemSDNode>(Op);
7089     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7090                                    M->getMemoryVT(), M->getMemOperand());
7091   }
7092 
7093   case Intrinsic::amdgcn_raw_tbuffer_store: {
7094     SDValue VData = Op.getOperand(2);
7095     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7096     if (IsD16)
7097       VData = handleD16VData(VData, DAG);
7098     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7099     SDValue Ops[] = {
7100       Chain,
7101       VData,             // vdata
7102       Op.getOperand(3),  // rsrc
7103       DAG.getConstant(0, DL, MVT::i32), // vindex
7104       Offsets.first,     // voffset
7105       Op.getOperand(5),  // soffset
7106       Offsets.second,    // offset
7107       Op.getOperand(6),  // format
7108       Op.getOperand(7),  // cachepolicy, swizzled buffer
7109       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7110     };
7111     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7112                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7113     MemSDNode *M = cast<MemSDNode>(Op);
7114     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7115                                    M->getMemoryVT(), M->getMemOperand());
7116   }
7117 
7118   case Intrinsic::amdgcn_buffer_store:
7119   case Intrinsic::amdgcn_buffer_store_format: {
7120     SDValue VData = Op.getOperand(2);
7121     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7122     if (IsD16)
7123       VData = handleD16VData(VData, DAG);
7124     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7125     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7126     unsigned IdxEn = 1;
7127     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7128       IdxEn = Idx->getZExtValue() != 0;
7129     SDValue Ops[] = {
7130       Chain,
7131       VData,
7132       Op.getOperand(3), // rsrc
7133       Op.getOperand(4), // vindex
7134       SDValue(), // voffset -- will be set by setBufferOffsets
7135       SDValue(), // soffset -- will be set by setBufferOffsets
7136       SDValue(), // offset -- will be set by setBufferOffsets
7137       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7138       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7139     };
7140     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7141     // We don't know the offset if vindex is non-zero, so clear it.
7142     if (IdxEn)
7143       Offset = 0;
7144     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7145                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7146     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7147     MemSDNode *M = cast<MemSDNode>(Op);
7148     M->getMemOperand()->setOffset(Offset);
7149 
7150     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7151     EVT VDataType = VData.getValueType().getScalarType();
7152     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7153       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7154 
7155     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7156                                    M->getMemoryVT(), M->getMemOperand());
7157   }
7158 
7159   case Intrinsic::amdgcn_raw_buffer_store:
7160   case Intrinsic::amdgcn_raw_buffer_store_format: {
7161     const bool IsFormat =
7162         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7163 
7164     SDValue VData = Op.getOperand(2);
7165     EVT VDataVT = VData.getValueType();
7166     EVT EltType = VDataVT.getScalarType();
7167     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7168     if (IsD16)
7169       VData = handleD16VData(VData, DAG);
7170 
7171     if (!isTypeLegal(VDataVT)) {
7172       VData =
7173           DAG.getNode(ISD::BITCAST, DL,
7174                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7175     }
7176 
7177     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7178     SDValue Ops[] = {
7179       Chain,
7180       VData,
7181       Op.getOperand(3), // rsrc
7182       DAG.getConstant(0, DL, MVT::i32), // vindex
7183       Offsets.first,    // voffset
7184       Op.getOperand(5), // soffset
7185       Offsets.second,   // offset
7186       Op.getOperand(6), // cachepolicy, swizzled buffer
7187       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7188     };
7189     unsigned Opc =
7190         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7191     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7192     MemSDNode *M = cast<MemSDNode>(Op);
7193     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7194 
7195     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7196     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7197       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7198 
7199     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7200                                    M->getMemoryVT(), M->getMemOperand());
7201   }
7202 
7203   case Intrinsic::amdgcn_struct_buffer_store:
7204   case Intrinsic::amdgcn_struct_buffer_store_format: {
7205     const bool IsFormat =
7206         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7207 
7208     SDValue VData = Op.getOperand(2);
7209     EVT VDataVT = VData.getValueType();
7210     EVT EltType = VDataVT.getScalarType();
7211     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7212 
7213     if (IsD16)
7214       VData = handleD16VData(VData, DAG);
7215 
7216     if (!isTypeLegal(VDataVT)) {
7217       VData =
7218           DAG.getNode(ISD::BITCAST, DL,
7219                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7220     }
7221 
7222     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7223     SDValue Ops[] = {
7224       Chain,
7225       VData,
7226       Op.getOperand(3), // rsrc
7227       Op.getOperand(4), // vindex
7228       Offsets.first,    // voffset
7229       Op.getOperand(6), // soffset
7230       Offsets.second,   // offset
7231       Op.getOperand(7), // cachepolicy, swizzled buffer
7232       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7233     };
7234     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7235                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7236     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7237     MemSDNode *M = cast<MemSDNode>(Op);
7238     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7239                                                         Ops[3]));
7240 
7241     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7242     EVT VDataType = VData.getValueType().getScalarType();
7243     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7244       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7245 
7246     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7247                                    M->getMemoryVT(), M->getMemOperand());
7248   }
7249 
7250   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7251     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7252     unsigned IdxEn = 1;
7253     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7254       IdxEn = Idx->getZExtValue() != 0;
7255     SDValue Ops[] = {
7256       Chain,
7257       Op.getOperand(2), // vdata
7258       Op.getOperand(3), // rsrc
7259       Op.getOperand(4), // vindex
7260       SDValue(),        // voffset -- will be set by setBufferOffsets
7261       SDValue(),        // soffset -- will be set by setBufferOffsets
7262       SDValue(),        // offset -- will be set by setBufferOffsets
7263       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7264       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7265     };
7266     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7267     // We don't know the offset if vindex is non-zero, so clear it.
7268     if (IdxEn)
7269       Offset = 0;
7270     EVT VT = Op.getOperand(2).getValueType();
7271 
7272     auto *M = cast<MemSDNode>(Op);
7273     M->getMemOperand()->setOffset(Offset);
7274     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7275                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7276 
7277     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7278                                    M->getMemOperand());
7279   }
7280 
7281   case Intrinsic::amdgcn_global_atomic_fadd: {
7282     SDValue Ops[] = {
7283       Chain,
7284       Op.getOperand(2), // ptr
7285       Op.getOperand(3)  // vdata
7286     };
7287     EVT VT = Op.getOperand(3).getValueType();
7288 
7289     auto *M = cast<MemSDNode>(Op);
7290     if (VT.isVector()) {
7291       return DAG.getMemIntrinsicNode(
7292         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7293         M->getMemOperand());
7294     }
7295 
7296     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7297                          DAG.getVTList(VT, MVT::Other), Ops,
7298                          M->getMemOperand()).getValue(1);
7299   }
7300   case Intrinsic::amdgcn_end_cf:
7301     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7302                                       Op->getOperand(2), Chain), 0);
7303 
7304   default: {
7305     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7306             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7307       return lowerImage(Op, ImageDimIntr, DAG);
7308 
7309     return Op;
7310   }
7311   }
7312 }
7313 
7314 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7315 // offset (the offset that is included in bounds checking and swizzling, to be
7316 // split between the instruction's voffset and immoffset fields) and soffset
7317 // (the offset that is excluded from bounds checking and swizzling, to go in
7318 // the instruction's soffset field).  This function takes the first kind of
7319 // offset and figures out how to split it between voffset and immoffset.
7320 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7321     SDValue Offset, SelectionDAG &DAG) const {
7322   SDLoc DL(Offset);
7323   const unsigned MaxImm = 4095;
7324   SDValue N0 = Offset;
7325   ConstantSDNode *C1 = nullptr;
7326 
7327   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7328     N0 = SDValue();
7329   else if (DAG.isBaseWithConstantOffset(N0)) {
7330     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7331     N0 = N0.getOperand(0);
7332   }
7333 
7334   if (C1) {
7335     unsigned ImmOffset = C1->getZExtValue();
7336     // If the immediate value is too big for the immoffset field, put the value
7337     // and -4096 into the immoffset field so that the value that is copied/added
7338     // for the voffset field is a multiple of 4096, and it stands more chance
7339     // of being CSEd with the copy/add for another similar load/store.
7340     // However, do not do that rounding down to a multiple of 4096 if that is a
7341     // negative number, as it appears to be illegal to have a negative offset
7342     // in the vgpr, even if adding the immediate offset makes it positive.
7343     unsigned Overflow = ImmOffset & ~MaxImm;
7344     ImmOffset -= Overflow;
7345     if ((int32_t)Overflow < 0) {
7346       Overflow += ImmOffset;
7347       ImmOffset = 0;
7348     }
7349     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7350     if (Overflow) {
7351       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7352       if (!N0)
7353         N0 = OverflowVal;
7354       else {
7355         SDValue Ops[] = { N0, OverflowVal };
7356         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7357       }
7358     }
7359   }
7360   if (!N0)
7361     N0 = DAG.getConstant(0, DL, MVT::i32);
7362   if (!C1)
7363     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7364   return {N0, SDValue(C1, 0)};
7365 }
7366 
7367 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7368 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7369 // pointed to by Offsets.
7370 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7371                                         SelectionDAG &DAG, SDValue *Offsets,
7372                                         unsigned Align) const {
7373   SDLoc DL(CombinedOffset);
7374   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7375     uint32_t Imm = C->getZExtValue();
7376     uint32_t SOffset, ImmOffset;
7377     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7378       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7379       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7380       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7381       return SOffset + ImmOffset;
7382     }
7383   }
7384   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7385     SDValue N0 = CombinedOffset.getOperand(0);
7386     SDValue N1 = CombinedOffset.getOperand(1);
7387     uint32_t SOffset, ImmOffset;
7388     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7389     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7390                                                 Subtarget, Align)) {
7391       Offsets[0] = N0;
7392       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7393       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7394       return 0;
7395     }
7396   }
7397   Offsets[0] = CombinedOffset;
7398   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7399   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7400   return 0;
7401 }
7402 
7403 // Handle 8 bit and 16 bit buffer loads
7404 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7405                                                      EVT LoadVT, SDLoc DL,
7406                                                      ArrayRef<SDValue> Ops,
7407                                                      MemSDNode *M) const {
7408   EVT IntVT = LoadVT.changeTypeToInteger();
7409   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7410          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7411 
7412   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7413   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7414                                                Ops, IntVT,
7415                                                M->getMemOperand());
7416   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7417   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7418 
7419   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7420 }
7421 
7422 // Handle 8 bit and 16 bit buffer stores
7423 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7424                                                       EVT VDataType, SDLoc DL,
7425                                                       SDValue Ops[],
7426                                                       MemSDNode *M) const {
7427   if (VDataType == MVT::f16)
7428     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7429 
7430   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7431   Ops[1] = BufferStoreExt;
7432   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7433                                  AMDGPUISD::BUFFER_STORE_SHORT;
7434   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7435   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7436                                      M->getMemOperand());
7437 }
7438 
7439 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7440                                  ISD::LoadExtType ExtType, SDValue Op,
7441                                  const SDLoc &SL, EVT VT) {
7442   if (VT.bitsLT(Op.getValueType()))
7443     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7444 
7445   switch (ExtType) {
7446   case ISD::SEXTLOAD:
7447     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7448   case ISD::ZEXTLOAD:
7449     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7450   case ISD::EXTLOAD:
7451     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7452   case ISD::NON_EXTLOAD:
7453     return Op;
7454   }
7455 
7456   llvm_unreachable("invalid ext type");
7457 }
7458 
7459 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7460   SelectionDAG &DAG = DCI.DAG;
7461   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7462     return SDValue();
7463 
7464   // FIXME: Constant loads should all be marked invariant.
7465   unsigned AS = Ld->getAddressSpace();
7466   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7467       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7468       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7469     return SDValue();
7470 
7471   // Don't do this early, since it may interfere with adjacent load merging for
7472   // illegal types. We can avoid losing alignment information for exotic types
7473   // pre-legalize.
7474   EVT MemVT = Ld->getMemoryVT();
7475   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7476       MemVT.getSizeInBits() >= 32)
7477     return SDValue();
7478 
7479   SDLoc SL(Ld);
7480 
7481   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7482          "unexpected vector extload");
7483 
7484   // TODO: Drop only high part of range.
7485   SDValue Ptr = Ld->getBasePtr();
7486   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7487                                 MVT::i32, SL, Ld->getChain(), Ptr,
7488                                 Ld->getOffset(),
7489                                 Ld->getPointerInfo(), MVT::i32,
7490                                 Ld->getAlignment(),
7491                                 Ld->getMemOperand()->getFlags(),
7492                                 Ld->getAAInfo(),
7493                                 nullptr); // Drop ranges
7494 
7495   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7496   if (MemVT.isFloatingPoint()) {
7497     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7498            "unexpected fp extload");
7499     TruncVT = MemVT.changeTypeToInteger();
7500   }
7501 
7502   SDValue Cvt = NewLoad;
7503   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7504     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7505                       DAG.getValueType(TruncVT));
7506   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7507              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7508     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7509   } else {
7510     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7511   }
7512 
7513   EVT VT = Ld->getValueType(0);
7514   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7515 
7516   DCI.AddToWorklist(Cvt.getNode());
7517 
7518   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7519   // the appropriate extension from the 32-bit load.
7520   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7521   DCI.AddToWorklist(Cvt.getNode());
7522 
7523   // Handle conversion back to floating point if necessary.
7524   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7525 
7526   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7527 }
7528 
7529 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7530   SDLoc DL(Op);
7531   LoadSDNode *Load = cast<LoadSDNode>(Op);
7532   ISD::LoadExtType ExtType = Load->getExtensionType();
7533   EVT MemVT = Load->getMemoryVT();
7534 
7535   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7536     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7537       return SDValue();
7538 
7539     // FIXME: Copied from PPC
7540     // First, load into 32 bits, then truncate to 1 bit.
7541 
7542     SDValue Chain = Load->getChain();
7543     SDValue BasePtr = Load->getBasePtr();
7544     MachineMemOperand *MMO = Load->getMemOperand();
7545 
7546     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7547 
7548     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7549                                    BasePtr, RealMemVT, MMO);
7550 
7551     if (!MemVT.isVector()) {
7552       SDValue Ops[] = {
7553         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7554         NewLD.getValue(1)
7555       };
7556 
7557       return DAG.getMergeValues(Ops, DL);
7558     }
7559 
7560     SmallVector<SDValue, 3> Elts;
7561     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7562       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7563                                 DAG.getConstant(I, DL, MVT::i32));
7564 
7565       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7566     }
7567 
7568     SDValue Ops[] = {
7569       DAG.getBuildVector(MemVT, DL, Elts),
7570       NewLD.getValue(1)
7571     };
7572 
7573     return DAG.getMergeValues(Ops, DL);
7574   }
7575 
7576   if (!MemVT.isVector())
7577     return SDValue();
7578 
7579   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7580          "Custom lowering for non-i32 vectors hasn't been implemented.");
7581 
7582   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7583                                       MemVT, *Load->getMemOperand())) {
7584     SDValue Ops[2];
7585     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7586     return DAG.getMergeValues(Ops, DL);
7587   }
7588 
7589   unsigned Alignment = Load->getAlignment();
7590   unsigned AS = Load->getAddressSpace();
7591   if (Subtarget->hasLDSMisalignedBug() &&
7592       AS == AMDGPUAS::FLAT_ADDRESS &&
7593       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7594     return SplitVectorLoad(Op, DAG);
7595   }
7596 
7597   MachineFunction &MF = DAG.getMachineFunction();
7598   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7599   // If there is a possibilty that flat instruction access scratch memory
7600   // then we need to use the same legalization rules we use for private.
7601   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7602       !Subtarget->hasMultiDwordFlatScratchAddressing())
7603     AS = MFI->hasFlatScratchInit() ?
7604          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7605 
7606   unsigned NumElements = MemVT.getVectorNumElements();
7607 
7608   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7609       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7610     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7611       if (MemVT.isPow2VectorType())
7612         return SDValue();
7613       if (NumElements == 3)
7614         return WidenVectorLoad(Op, DAG);
7615       return SplitVectorLoad(Op, DAG);
7616     }
7617     // Non-uniform loads will be selected to MUBUF instructions, so they
7618     // have the same legalization requirements as global and private
7619     // loads.
7620     //
7621   }
7622 
7623   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7624       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7625       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7626     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7627         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7628         Alignment >= 4 && NumElements < 32) {
7629       if (MemVT.isPow2VectorType())
7630         return SDValue();
7631       if (NumElements == 3)
7632         return WidenVectorLoad(Op, DAG);
7633       return SplitVectorLoad(Op, DAG);
7634     }
7635     // Non-uniform loads will be selected to MUBUF instructions, so they
7636     // have the same legalization requirements as global and private
7637     // loads.
7638     //
7639   }
7640   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7641       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7642       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7643       AS == AMDGPUAS::FLAT_ADDRESS) {
7644     if (NumElements > 4)
7645       return SplitVectorLoad(Op, DAG);
7646     // v3 loads not supported on SI.
7647     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7648       return WidenVectorLoad(Op, DAG);
7649     // v3 and v4 loads are supported for private and global memory.
7650     return SDValue();
7651   }
7652   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7653     // Depending on the setting of the private_element_size field in the
7654     // resource descriptor, we can only make private accesses up to a certain
7655     // size.
7656     switch (Subtarget->getMaxPrivateElementSize()) {
7657     case 4: {
7658       SDValue Ops[2];
7659       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7660       return DAG.getMergeValues(Ops, DL);
7661     }
7662     case 8:
7663       if (NumElements > 2)
7664         return SplitVectorLoad(Op, DAG);
7665       return SDValue();
7666     case 16:
7667       // Same as global/flat
7668       if (NumElements > 4)
7669         return SplitVectorLoad(Op, DAG);
7670       // v3 loads not supported on SI.
7671       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7672         return WidenVectorLoad(Op, DAG);
7673       return SDValue();
7674     default:
7675       llvm_unreachable("unsupported private_element_size");
7676     }
7677   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7678     // Use ds_read_b128 if possible.
7679     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7680         MemVT.getStoreSize() == 16)
7681       return SDValue();
7682 
7683     if (NumElements > 2)
7684       return SplitVectorLoad(Op, DAG);
7685 
7686     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7687     // address is negative, then the instruction is incorrectly treated as
7688     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7689     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7690     // load later in the SILoadStoreOptimizer.
7691     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7692         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7693         Load->getAlignment() < 8) {
7694       return SplitVectorLoad(Op, DAG);
7695     }
7696   }
7697   return SDValue();
7698 }
7699 
7700 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7701   EVT VT = Op.getValueType();
7702   assert(VT.getSizeInBits() == 64);
7703 
7704   SDLoc DL(Op);
7705   SDValue Cond = Op.getOperand(0);
7706 
7707   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7708   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7709 
7710   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7711   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7712 
7713   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7714   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7715 
7716   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7717 
7718   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7719   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7720 
7721   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7722 
7723   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7724   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7725 }
7726 
7727 // Catch division cases where we can use shortcuts with rcp and rsq
7728 // instructions.
7729 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7730                                               SelectionDAG &DAG) const {
7731   SDLoc SL(Op);
7732   SDValue LHS = Op.getOperand(0);
7733   SDValue RHS = Op.getOperand(1);
7734   EVT VT = Op.getValueType();
7735   const SDNodeFlags Flags = Op->getFlags();
7736 
7737   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7738                             Flags.hasApproximateFuncs();
7739 
7740   // Without !fpmath accuracy information, we can't do more because we don't
7741   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7742   if (!AllowInaccurateRcp)
7743     return SDValue();
7744 
7745   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7746     if (CLHS->isExactlyValue(1.0)) {
7747       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7748       // the CI documentation has a worst case error of 1 ulp.
7749       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7750       // use it as long as we aren't trying to use denormals.
7751       //
7752       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7753 
7754       // 1.0 / sqrt(x) -> rsq(x)
7755 
7756       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7757       // error seems really high at 2^29 ULP.
7758       if (RHS.getOpcode() == ISD::FSQRT)
7759         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7760 
7761       // 1.0 / x -> rcp(x)
7762       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7763     }
7764 
7765     // Same as for 1.0, but expand the sign out of the constant.
7766     if (CLHS->isExactlyValue(-1.0)) {
7767       // -1.0 / x -> rcp (fneg x)
7768       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7769       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7770     }
7771   }
7772 
7773   // Turn into multiply by the reciprocal.
7774   // x / y -> x * (1.0 / y)
7775   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7776   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7777 }
7778 
7779 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7780                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7781   if (GlueChain->getNumValues() <= 1) {
7782     return DAG.getNode(Opcode, SL, VT, A, B);
7783   }
7784 
7785   assert(GlueChain->getNumValues() == 3);
7786 
7787   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7788   switch (Opcode) {
7789   default: llvm_unreachable("no chain equivalent for opcode");
7790   case ISD::FMUL:
7791     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7792     break;
7793   }
7794 
7795   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7796                      GlueChain.getValue(2));
7797 }
7798 
7799 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7800                            EVT VT, SDValue A, SDValue B, SDValue C,
7801                            SDValue GlueChain) {
7802   if (GlueChain->getNumValues() <= 1) {
7803     return DAG.getNode(Opcode, SL, VT, A, B, C);
7804   }
7805 
7806   assert(GlueChain->getNumValues() == 3);
7807 
7808   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7809   switch (Opcode) {
7810   default: llvm_unreachable("no chain equivalent for opcode");
7811   case ISD::FMA:
7812     Opcode = AMDGPUISD::FMA_W_CHAIN;
7813     break;
7814   }
7815 
7816   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7817                      GlueChain.getValue(2));
7818 }
7819 
7820 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7821   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7822     return FastLowered;
7823 
7824   SDLoc SL(Op);
7825   SDValue Src0 = Op.getOperand(0);
7826   SDValue Src1 = Op.getOperand(1);
7827 
7828   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7829   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7830 
7831   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7832   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7833 
7834   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7835   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7836 
7837   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7838 }
7839 
7840 // Faster 2.5 ULP division that does not support denormals.
7841 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7842   SDLoc SL(Op);
7843   SDValue LHS = Op.getOperand(1);
7844   SDValue RHS = Op.getOperand(2);
7845 
7846   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7847 
7848   const APFloat K0Val(BitsToFloat(0x6f800000));
7849   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7850 
7851   const APFloat K1Val(BitsToFloat(0x2f800000));
7852   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7853 
7854   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7855 
7856   EVT SetCCVT =
7857     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7858 
7859   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7860 
7861   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7862 
7863   // TODO: Should this propagate fast-math-flags?
7864   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7865 
7866   // rcp does not support denormals.
7867   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7868 
7869   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7870 
7871   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7872 }
7873 
7874 // Returns immediate value for setting the F32 denorm mode when using the
7875 // S_DENORM_MODE instruction.
7876 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7877                                           const SDLoc &SL, const GCNSubtarget *ST) {
7878   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7879   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7880                                 ? FP_DENORM_FLUSH_NONE
7881                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7882 
7883   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7884   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7885 }
7886 
7887 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7888   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7889     return FastLowered;
7890 
7891   SDLoc SL(Op);
7892   SDValue LHS = Op.getOperand(0);
7893   SDValue RHS = Op.getOperand(1);
7894 
7895   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7896 
7897   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7898 
7899   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7900                                           RHS, RHS, LHS);
7901   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7902                                         LHS, RHS, LHS);
7903 
7904   // Denominator is scaled to not be denormal, so using rcp is ok.
7905   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7906                                   DenominatorScaled);
7907   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7908                                      DenominatorScaled);
7909 
7910   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7911                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7912                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7913   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7914 
7915   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7916 
7917   if (!HasFP32Denormals) {
7918     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7919 
7920     SDValue EnableDenorm;
7921     if (Subtarget->hasDenormModeInst()) {
7922       const SDValue EnableDenormValue =
7923           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7924 
7925       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7926                                  DAG.getEntryNode(), EnableDenormValue);
7927     } else {
7928       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7929                                                         SL, MVT::i32);
7930       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7931                                  DAG.getEntryNode(), EnableDenormValue,
7932                                  BitField);
7933     }
7934 
7935     SDValue Ops[3] = {
7936       NegDivScale0,
7937       EnableDenorm.getValue(0),
7938       EnableDenorm.getValue(1)
7939     };
7940 
7941     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7942   }
7943 
7944   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7945                              ApproxRcp, One, NegDivScale0);
7946 
7947   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7948                              ApproxRcp, Fma0);
7949 
7950   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7951                            Fma1, Fma1);
7952 
7953   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7954                              NumeratorScaled, Mul);
7955 
7956   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7957 
7958   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7959                              NumeratorScaled, Fma3);
7960 
7961   if (!HasFP32Denormals) {
7962     SDValue DisableDenorm;
7963     if (Subtarget->hasDenormModeInst()) {
7964       const SDValue DisableDenormValue =
7965           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7966 
7967       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7968                                   Fma4.getValue(1), DisableDenormValue,
7969                                   Fma4.getValue(2));
7970     } else {
7971       const SDValue DisableDenormValue =
7972           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7973 
7974       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7975                                   Fma4.getValue(1), DisableDenormValue,
7976                                   BitField, Fma4.getValue(2));
7977     }
7978 
7979     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7980                                       DisableDenorm, DAG.getRoot());
7981     DAG.setRoot(OutputChain);
7982   }
7983 
7984   SDValue Scale = NumeratorScaled.getValue(1);
7985   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7986                              Fma4, Fma1, Fma3, Scale);
7987 
7988   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7989 }
7990 
7991 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7992   if (DAG.getTarget().Options.UnsafeFPMath)
7993     return lowerFastUnsafeFDIV(Op, DAG);
7994 
7995   SDLoc SL(Op);
7996   SDValue X = Op.getOperand(0);
7997   SDValue Y = Op.getOperand(1);
7998 
7999   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8000 
8001   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8002 
8003   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8004 
8005   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8006 
8007   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8008 
8009   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8010 
8011   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8012 
8013   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8014 
8015   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8016 
8017   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8018   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8019 
8020   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8021                              NegDivScale0, Mul, DivScale1);
8022 
8023   SDValue Scale;
8024 
8025   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8026     // Workaround a hardware bug on SI where the condition output from div_scale
8027     // is not usable.
8028 
8029     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8030 
8031     // Figure out if the scale to use for div_fmas.
8032     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8033     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8034     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8035     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8036 
8037     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8038     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8039 
8040     SDValue Scale0Hi
8041       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8042     SDValue Scale1Hi
8043       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8044 
8045     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8046     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8047     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8048   } else {
8049     Scale = DivScale1.getValue(1);
8050   }
8051 
8052   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8053                              Fma4, Fma3, Mul, Scale);
8054 
8055   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8056 }
8057 
8058 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8059   EVT VT = Op.getValueType();
8060 
8061   if (VT == MVT::f32)
8062     return LowerFDIV32(Op, DAG);
8063 
8064   if (VT == MVT::f64)
8065     return LowerFDIV64(Op, DAG);
8066 
8067   if (VT == MVT::f16)
8068     return LowerFDIV16(Op, DAG);
8069 
8070   llvm_unreachable("Unexpected type for fdiv");
8071 }
8072 
8073 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8074   SDLoc DL(Op);
8075   StoreSDNode *Store = cast<StoreSDNode>(Op);
8076   EVT VT = Store->getMemoryVT();
8077 
8078   if (VT == MVT::i1) {
8079     return DAG.getTruncStore(Store->getChain(), DL,
8080        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8081        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8082   }
8083 
8084   assert(VT.isVector() &&
8085          Store->getValue().getValueType().getScalarType() == MVT::i32);
8086 
8087   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8088                                       VT, *Store->getMemOperand())) {
8089     return expandUnalignedStore(Store, DAG);
8090   }
8091 
8092   unsigned AS = Store->getAddressSpace();
8093   if (Subtarget->hasLDSMisalignedBug() &&
8094       AS == AMDGPUAS::FLAT_ADDRESS &&
8095       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8096     return SplitVectorStore(Op, DAG);
8097   }
8098 
8099   MachineFunction &MF = DAG.getMachineFunction();
8100   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8101   // If there is a possibilty that flat instruction access scratch memory
8102   // then we need to use the same legalization rules we use for private.
8103   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8104       !Subtarget->hasMultiDwordFlatScratchAddressing())
8105     AS = MFI->hasFlatScratchInit() ?
8106          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8107 
8108   unsigned NumElements = VT.getVectorNumElements();
8109   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8110       AS == AMDGPUAS::FLAT_ADDRESS) {
8111     if (NumElements > 4)
8112       return SplitVectorStore(Op, DAG);
8113     // v3 stores not supported on SI.
8114     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8115       return SplitVectorStore(Op, DAG);
8116     return SDValue();
8117   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8118     switch (Subtarget->getMaxPrivateElementSize()) {
8119     case 4:
8120       return scalarizeVectorStore(Store, DAG);
8121     case 8:
8122       if (NumElements > 2)
8123         return SplitVectorStore(Op, DAG);
8124       return SDValue();
8125     case 16:
8126       if (NumElements > 4 || NumElements == 3)
8127         return SplitVectorStore(Op, DAG);
8128       return SDValue();
8129     default:
8130       llvm_unreachable("unsupported private_element_size");
8131     }
8132   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8133     // Use ds_write_b128 if possible.
8134     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8135         VT.getStoreSize() == 16 && NumElements != 3)
8136       return SDValue();
8137 
8138     if (NumElements > 2)
8139       return SplitVectorStore(Op, DAG);
8140 
8141     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8142     // address is negative, then the instruction is incorrectly treated as
8143     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8144     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8145     // store later in the SILoadStoreOptimizer.
8146     if (!Subtarget->hasUsableDSOffset() &&
8147         NumElements == 2 && VT.getStoreSize() == 8 &&
8148         Store->getAlignment() < 8) {
8149       return SplitVectorStore(Op, DAG);
8150     }
8151 
8152     return SDValue();
8153   } else {
8154     llvm_unreachable("unhandled address space");
8155   }
8156 }
8157 
8158 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8159   SDLoc DL(Op);
8160   EVT VT = Op.getValueType();
8161   SDValue Arg = Op.getOperand(0);
8162   SDValue TrigVal;
8163 
8164   // TODO: Should this propagate fast-math-flags?
8165 
8166   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
8167 
8168   if (Subtarget->hasTrigReducedRange()) {
8169     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8170     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
8171   } else {
8172     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8173   }
8174 
8175   switch (Op.getOpcode()) {
8176   case ISD::FCOS:
8177     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
8178   case ISD::FSIN:
8179     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
8180   default:
8181     llvm_unreachable("Wrong trig opcode");
8182   }
8183 }
8184 
8185 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8186   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8187   assert(AtomicNode->isCompareAndSwap());
8188   unsigned AS = AtomicNode->getAddressSpace();
8189 
8190   // No custom lowering required for local address space
8191   if (!isFlatGlobalAddrSpace(AS))
8192     return Op;
8193 
8194   // Non-local address space requires custom lowering for atomic compare
8195   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8196   SDLoc DL(Op);
8197   SDValue ChainIn = Op.getOperand(0);
8198   SDValue Addr = Op.getOperand(1);
8199   SDValue Old = Op.getOperand(2);
8200   SDValue New = Op.getOperand(3);
8201   EVT VT = Op.getValueType();
8202   MVT SimpleVT = VT.getSimpleVT();
8203   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8204 
8205   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8206   SDValue Ops[] = { ChainIn, Addr, NewOld };
8207 
8208   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8209                                  Ops, VT, AtomicNode->getMemOperand());
8210 }
8211 
8212 //===----------------------------------------------------------------------===//
8213 // Custom DAG optimizations
8214 //===----------------------------------------------------------------------===//
8215 
8216 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8217                                                      DAGCombinerInfo &DCI) const {
8218   EVT VT = N->getValueType(0);
8219   EVT ScalarVT = VT.getScalarType();
8220   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8221     return SDValue();
8222 
8223   SelectionDAG &DAG = DCI.DAG;
8224   SDLoc DL(N);
8225 
8226   SDValue Src = N->getOperand(0);
8227   EVT SrcVT = Src.getValueType();
8228 
8229   // TODO: We could try to match extracting the higher bytes, which would be
8230   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8231   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8232   // about in practice.
8233   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8234     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8235       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8236       DCI.AddToWorklist(Cvt.getNode());
8237 
8238       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8239       if (ScalarVT != MVT::f32) {
8240         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8241                           DAG.getTargetConstant(0, DL, MVT::i32));
8242       }
8243       return Cvt;
8244     }
8245   }
8246 
8247   return SDValue();
8248 }
8249 
8250 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8251 
8252 // This is a variant of
8253 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8254 //
8255 // The normal DAG combiner will do this, but only if the add has one use since
8256 // that would increase the number of instructions.
8257 //
8258 // This prevents us from seeing a constant offset that can be folded into a
8259 // memory instruction's addressing mode. If we know the resulting add offset of
8260 // a pointer can be folded into an addressing offset, we can replace the pointer
8261 // operand with the add of new constant offset. This eliminates one of the uses,
8262 // and may allow the remaining use to also be simplified.
8263 //
8264 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8265                                                unsigned AddrSpace,
8266                                                EVT MemVT,
8267                                                DAGCombinerInfo &DCI) const {
8268   SDValue N0 = N->getOperand(0);
8269   SDValue N1 = N->getOperand(1);
8270 
8271   // We only do this to handle cases where it's profitable when there are
8272   // multiple uses of the add, so defer to the standard combine.
8273   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8274       N0->hasOneUse())
8275     return SDValue();
8276 
8277   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8278   if (!CN1)
8279     return SDValue();
8280 
8281   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8282   if (!CAdd)
8283     return SDValue();
8284 
8285   // If the resulting offset is too large, we can't fold it into the addressing
8286   // mode offset.
8287   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8288   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8289 
8290   AddrMode AM;
8291   AM.HasBaseReg = true;
8292   AM.BaseOffs = Offset.getSExtValue();
8293   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8294     return SDValue();
8295 
8296   SelectionDAG &DAG = DCI.DAG;
8297   SDLoc SL(N);
8298   EVT VT = N->getValueType(0);
8299 
8300   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8301   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8302 
8303   SDNodeFlags Flags;
8304   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8305                           (N0.getOpcode() == ISD::OR ||
8306                            N0->getFlags().hasNoUnsignedWrap()));
8307 
8308   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8309 }
8310 
8311 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8312                                                   DAGCombinerInfo &DCI) const {
8313   SDValue Ptr = N->getBasePtr();
8314   SelectionDAG &DAG = DCI.DAG;
8315   SDLoc SL(N);
8316 
8317   // TODO: We could also do this for multiplies.
8318   if (Ptr.getOpcode() == ISD::SHL) {
8319     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8320                                           N->getMemoryVT(), DCI);
8321     if (NewPtr) {
8322       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8323 
8324       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8325       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8326     }
8327   }
8328 
8329   return SDValue();
8330 }
8331 
8332 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8333   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8334          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8335          (Opc == ISD::XOR && Val == 0);
8336 }
8337 
8338 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8339 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8340 // integer combine opportunities since most 64-bit operations are decomposed
8341 // this way.  TODO: We won't want this for SALU especially if it is an inline
8342 // immediate.
8343 SDValue SITargetLowering::splitBinaryBitConstantOp(
8344   DAGCombinerInfo &DCI,
8345   const SDLoc &SL,
8346   unsigned Opc, SDValue LHS,
8347   const ConstantSDNode *CRHS) const {
8348   uint64_t Val = CRHS->getZExtValue();
8349   uint32_t ValLo = Lo_32(Val);
8350   uint32_t ValHi = Hi_32(Val);
8351   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8352 
8353     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8354          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8355         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8356     // If we need to materialize a 64-bit immediate, it will be split up later
8357     // anyway. Avoid creating the harder to understand 64-bit immediate
8358     // materialization.
8359     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8360   }
8361 
8362   return SDValue();
8363 }
8364 
8365 // Returns true if argument is a boolean value which is not serialized into
8366 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8367 static bool isBoolSGPR(SDValue V) {
8368   if (V.getValueType() != MVT::i1)
8369     return false;
8370   switch (V.getOpcode()) {
8371   default: break;
8372   case ISD::SETCC:
8373   case ISD::AND:
8374   case ISD::OR:
8375   case ISD::XOR:
8376   case AMDGPUISD::FP_CLASS:
8377     return true;
8378   }
8379   return false;
8380 }
8381 
8382 // If a constant has all zeroes or all ones within each byte return it.
8383 // Otherwise return 0.
8384 static uint32_t getConstantPermuteMask(uint32_t C) {
8385   // 0xff for any zero byte in the mask
8386   uint32_t ZeroByteMask = 0;
8387   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8388   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8389   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8390   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8391   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8392   if ((NonZeroByteMask & C) != NonZeroByteMask)
8393     return 0; // Partial bytes selected.
8394   return C;
8395 }
8396 
8397 // Check if a node selects whole bytes from its operand 0 starting at a byte
8398 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8399 // or -1 if not succeeded.
8400 // Note byte select encoding:
8401 // value 0-3 selects corresponding source byte;
8402 // value 0xc selects zero;
8403 // value 0xff selects 0xff.
8404 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8405   assert(V.getValueSizeInBits() == 32);
8406 
8407   if (V.getNumOperands() != 2)
8408     return ~0;
8409 
8410   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8411   if (!N1)
8412     return ~0;
8413 
8414   uint32_t C = N1->getZExtValue();
8415 
8416   switch (V.getOpcode()) {
8417   default:
8418     break;
8419   case ISD::AND:
8420     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8421       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8422     }
8423     break;
8424 
8425   case ISD::OR:
8426     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8427       return (0x03020100 & ~ConstMask) | ConstMask;
8428     }
8429     break;
8430 
8431   case ISD::SHL:
8432     if (C % 8)
8433       return ~0;
8434 
8435     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8436 
8437   case ISD::SRL:
8438     if (C % 8)
8439       return ~0;
8440 
8441     return uint32_t(0x0c0c0c0c03020100ull >> C);
8442   }
8443 
8444   return ~0;
8445 }
8446 
8447 SDValue SITargetLowering::performAndCombine(SDNode *N,
8448                                             DAGCombinerInfo &DCI) const {
8449   if (DCI.isBeforeLegalize())
8450     return SDValue();
8451 
8452   SelectionDAG &DAG = DCI.DAG;
8453   EVT VT = N->getValueType(0);
8454   SDValue LHS = N->getOperand(0);
8455   SDValue RHS = N->getOperand(1);
8456 
8457 
8458   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8459   if (VT == MVT::i64 && CRHS) {
8460     if (SDValue Split
8461         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8462       return Split;
8463   }
8464 
8465   if (CRHS && VT == MVT::i32) {
8466     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8467     // nb = number of trailing zeroes in mask
8468     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8469     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8470     uint64_t Mask = CRHS->getZExtValue();
8471     unsigned Bits = countPopulation(Mask);
8472     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8473         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8474       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8475         unsigned Shift = CShift->getZExtValue();
8476         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8477         unsigned Offset = NB + Shift;
8478         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8479           SDLoc SL(N);
8480           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8481                                     LHS->getOperand(0),
8482                                     DAG.getConstant(Offset, SL, MVT::i32),
8483                                     DAG.getConstant(Bits, SL, MVT::i32));
8484           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8485           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8486                                     DAG.getValueType(NarrowVT));
8487           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8488                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8489           return Shl;
8490         }
8491       }
8492     }
8493 
8494     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8495     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8496         isa<ConstantSDNode>(LHS.getOperand(2))) {
8497       uint32_t Sel = getConstantPermuteMask(Mask);
8498       if (!Sel)
8499         return SDValue();
8500 
8501       // Select 0xc for all zero bytes
8502       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8503       SDLoc DL(N);
8504       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8505                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8506     }
8507   }
8508 
8509   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8510   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8511   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8512     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8513     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8514 
8515     SDValue X = LHS.getOperand(0);
8516     SDValue Y = RHS.getOperand(0);
8517     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8518       return SDValue();
8519 
8520     if (LCC == ISD::SETO) {
8521       if (X != LHS.getOperand(1))
8522         return SDValue();
8523 
8524       if (RCC == ISD::SETUNE) {
8525         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8526         if (!C1 || !C1->isInfinity() || C1->isNegative())
8527           return SDValue();
8528 
8529         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8530                               SIInstrFlags::N_SUBNORMAL |
8531                               SIInstrFlags::N_ZERO |
8532                               SIInstrFlags::P_ZERO |
8533                               SIInstrFlags::P_SUBNORMAL |
8534                               SIInstrFlags::P_NORMAL;
8535 
8536         static_assert(((~(SIInstrFlags::S_NAN |
8537                           SIInstrFlags::Q_NAN |
8538                           SIInstrFlags::N_INFINITY |
8539                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8540                       "mask not equal");
8541 
8542         SDLoc DL(N);
8543         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8544                            X, DAG.getConstant(Mask, DL, MVT::i32));
8545       }
8546     }
8547   }
8548 
8549   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8550     std::swap(LHS, RHS);
8551 
8552   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8553       RHS.hasOneUse()) {
8554     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8555     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8556     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8557     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8558     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8559         (RHS.getOperand(0) == LHS.getOperand(0) &&
8560          LHS.getOperand(0) == LHS.getOperand(1))) {
8561       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8562       unsigned NewMask = LCC == ISD::SETO ?
8563         Mask->getZExtValue() & ~OrdMask :
8564         Mask->getZExtValue() & OrdMask;
8565 
8566       SDLoc DL(N);
8567       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8568                          DAG.getConstant(NewMask, DL, MVT::i32));
8569     }
8570   }
8571 
8572   if (VT == MVT::i32 &&
8573       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8574     // and x, (sext cc from i1) => select cc, x, 0
8575     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8576       std::swap(LHS, RHS);
8577     if (isBoolSGPR(RHS.getOperand(0)))
8578       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8579                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8580   }
8581 
8582   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8583   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8584   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8585       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8586     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8587     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8588     if (LHSMask != ~0u && RHSMask != ~0u) {
8589       // Canonicalize the expression in an attempt to have fewer unique masks
8590       // and therefore fewer registers used to hold the masks.
8591       if (LHSMask > RHSMask) {
8592         std::swap(LHSMask, RHSMask);
8593         std::swap(LHS, RHS);
8594       }
8595 
8596       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8597       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8598       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8599       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8600 
8601       // Check of we need to combine values from two sources within a byte.
8602       if (!(LHSUsedLanes & RHSUsedLanes) &&
8603           // If we select high and lower word keep it for SDWA.
8604           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8605           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8606         // Each byte in each mask is either selector mask 0-3, or has higher
8607         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8608         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8609         // mask which is not 0xff wins. By anding both masks we have a correct
8610         // result except that 0x0c shall be corrected to give 0x0c only.
8611         uint32_t Mask = LHSMask & RHSMask;
8612         for (unsigned I = 0; I < 32; I += 8) {
8613           uint32_t ByteSel = 0xff << I;
8614           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8615             Mask &= (0x0c << I) & 0xffffffff;
8616         }
8617 
8618         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8619         // or 0x0c.
8620         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8621         SDLoc DL(N);
8622 
8623         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8624                            LHS.getOperand(0), RHS.getOperand(0),
8625                            DAG.getConstant(Sel, DL, MVT::i32));
8626       }
8627     }
8628   }
8629 
8630   return SDValue();
8631 }
8632 
8633 SDValue SITargetLowering::performOrCombine(SDNode *N,
8634                                            DAGCombinerInfo &DCI) const {
8635   SelectionDAG &DAG = DCI.DAG;
8636   SDValue LHS = N->getOperand(0);
8637   SDValue RHS = N->getOperand(1);
8638 
8639   EVT VT = N->getValueType(0);
8640   if (VT == MVT::i1) {
8641     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8642     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8643         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8644       SDValue Src = LHS.getOperand(0);
8645       if (Src != RHS.getOperand(0))
8646         return SDValue();
8647 
8648       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8649       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8650       if (!CLHS || !CRHS)
8651         return SDValue();
8652 
8653       // Only 10 bits are used.
8654       static const uint32_t MaxMask = 0x3ff;
8655 
8656       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8657       SDLoc DL(N);
8658       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8659                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8660     }
8661 
8662     return SDValue();
8663   }
8664 
8665   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8666   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8667       LHS.getOpcode() == AMDGPUISD::PERM &&
8668       isa<ConstantSDNode>(LHS.getOperand(2))) {
8669     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8670     if (!Sel)
8671       return SDValue();
8672 
8673     Sel |= LHS.getConstantOperandVal(2);
8674     SDLoc DL(N);
8675     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8676                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8677   }
8678 
8679   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8680   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8681   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8682       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8683     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8684     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8685     if (LHSMask != ~0u && RHSMask != ~0u) {
8686       // Canonicalize the expression in an attempt to have fewer unique masks
8687       // and therefore fewer registers used to hold the masks.
8688       if (LHSMask > RHSMask) {
8689         std::swap(LHSMask, RHSMask);
8690         std::swap(LHS, RHS);
8691       }
8692 
8693       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8694       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8695       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8696       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8697 
8698       // Check of we need to combine values from two sources within a byte.
8699       if (!(LHSUsedLanes & RHSUsedLanes) &&
8700           // If we select high and lower word keep it for SDWA.
8701           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8702           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8703         // Kill zero bytes selected by other mask. Zero value is 0xc.
8704         LHSMask &= ~RHSUsedLanes;
8705         RHSMask &= ~LHSUsedLanes;
8706         // Add 4 to each active LHS lane
8707         LHSMask |= LHSUsedLanes & 0x04040404;
8708         // Combine masks
8709         uint32_t Sel = LHSMask | RHSMask;
8710         SDLoc DL(N);
8711 
8712         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8713                            LHS.getOperand(0), RHS.getOperand(0),
8714                            DAG.getConstant(Sel, DL, MVT::i32));
8715       }
8716     }
8717   }
8718 
8719   if (VT != MVT::i64)
8720     return SDValue();
8721 
8722   // TODO: This could be a generic combine with a predicate for extracting the
8723   // high half of an integer being free.
8724 
8725   // (or i64:x, (zero_extend i32:y)) ->
8726   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8727   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8728       RHS.getOpcode() != ISD::ZERO_EXTEND)
8729     std::swap(LHS, RHS);
8730 
8731   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8732     SDValue ExtSrc = RHS.getOperand(0);
8733     EVT SrcVT = ExtSrc.getValueType();
8734     if (SrcVT == MVT::i32) {
8735       SDLoc SL(N);
8736       SDValue LowLHS, HiBits;
8737       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8738       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8739 
8740       DCI.AddToWorklist(LowOr.getNode());
8741       DCI.AddToWorklist(HiBits.getNode());
8742 
8743       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8744                                 LowOr, HiBits);
8745       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8746     }
8747   }
8748 
8749   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8750   if (CRHS) {
8751     if (SDValue Split
8752           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8753       return Split;
8754   }
8755 
8756   return SDValue();
8757 }
8758 
8759 SDValue SITargetLowering::performXorCombine(SDNode *N,
8760                                             DAGCombinerInfo &DCI) const {
8761   EVT VT = N->getValueType(0);
8762   if (VT != MVT::i64)
8763     return SDValue();
8764 
8765   SDValue LHS = N->getOperand(0);
8766   SDValue RHS = N->getOperand(1);
8767 
8768   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8769   if (CRHS) {
8770     if (SDValue Split
8771           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8772       return Split;
8773   }
8774 
8775   return SDValue();
8776 }
8777 
8778 // Instructions that will be lowered with a final instruction that zeros the
8779 // high result bits.
8780 // XXX - probably only need to list legal operations.
8781 static bool fp16SrcZerosHighBits(unsigned Opc) {
8782   switch (Opc) {
8783   case ISD::FADD:
8784   case ISD::FSUB:
8785   case ISD::FMUL:
8786   case ISD::FDIV:
8787   case ISD::FREM:
8788   case ISD::FMA:
8789   case ISD::FMAD:
8790   case ISD::FCANONICALIZE:
8791   case ISD::FP_ROUND:
8792   case ISD::UINT_TO_FP:
8793   case ISD::SINT_TO_FP:
8794   case ISD::FABS:
8795     // Fabs is lowered to a bit operation, but it's an and which will clear the
8796     // high bits anyway.
8797   case ISD::FSQRT:
8798   case ISD::FSIN:
8799   case ISD::FCOS:
8800   case ISD::FPOWI:
8801   case ISD::FPOW:
8802   case ISD::FLOG:
8803   case ISD::FLOG2:
8804   case ISD::FLOG10:
8805   case ISD::FEXP:
8806   case ISD::FEXP2:
8807   case ISD::FCEIL:
8808   case ISD::FTRUNC:
8809   case ISD::FRINT:
8810   case ISD::FNEARBYINT:
8811   case ISD::FROUND:
8812   case ISD::FFLOOR:
8813   case ISD::FMINNUM:
8814   case ISD::FMAXNUM:
8815   case AMDGPUISD::FRACT:
8816   case AMDGPUISD::CLAMP:
8817   case AMDGPUISD::COS_HW:
8818   case AMDGPUISD::SIN_HW:
8819   case AMDGPUISD::FMIN3:
8820   case AMDGPUISD::FMAX3:
8821   case AMDGPUISD::FMED3:
8822   case AMDGPUISD::FMAD_FTZ:
8823   case AMDGPUISD::RCP:
8824   case AMDGPUISD::RSQ:
8825   case AMDGPUISD::RCP_IFLAG:
8826   case AMDGPUISD::LDEXP:
8827     return true;
8828   default:
8829     // fcopysign, select and others may be lowered to 32-bit bit operations
8830     // which don't zero the high bits.
8831     return false;
8832   }
8833 }
8834 
8835 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8836                                                    DAGCombinerInfo &DCI) const {
8837   if (!Subtarget->has16BitInsts() ||
8838       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8839     return SDValue();
8840 
8841   EVT VT = N->getValueType(0);
8842   if (VT != MVT::i32)
8843     return SDValue();
8844 
8845   SDValue Src = N->getOperand(0);
8846   if (Src.getValueType() != MVT::i16)
8847     return SDValue();
8848 
8849   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8850   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8851   if (Src.getOpcode() == ISD::BITCAST) {
8852     SDValue BCSrc = Src.getOperand(0);
8853     if (BCSrc.getValueType() == MVT::f16 &&
8854         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8855       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8856   }
8857 
8858   return SDValue();
8859 }
8860 
8861 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8862                                                         DAGCombinerInfo &DCI)
8863                                                         const {
8864   SDValue Src = N->getOperand(0);
8865   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8866 
8867   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8868       VTSign->getVT() == MVT::i8) ||
8869       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8870       VTSign->getVT() == MVT::i16)) &&
8871       Src.hasOneUse()) {
8872     auto *M = cast<MemSDNode>(Src);
8873     SDValue Ops[] = {
8874       Src.getOperand(0), // Chain
8875       Src.getOperand(1), // rsrc
8876       Src.getOperand(2), // vindex
8877       Src.getOperand(3), // voffset
8878       Src.getOperand(4), // soffset
8879       Src.getOperand(5), // offset
8880       Src.getOperand(6),
8881       Src.getOperand(7)
8882     };
8883     // replace with BUFFER_LOAD_BYTE/SHORT
8884     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8885                                          Src.getOperand(0).getValueType());
8886     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8887                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8888     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8889                                                           ResList,
8890                                                           Ops, M->getMemoryVT(),
8891                                                           M->getMemOperand());
8892     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8893                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8894   }
8895   return SDValue();
8896 }
8897 
8898 SDValue SITargetLowering::performClassCombine(SDNode *N,
8899                                               DAGCombinerInfo &DCI) const {
8900   SelectionDAG &DAG = DCI.DAG;
8901   SDValue Mask = N->getOperand(1);
8902 
8903   // fp_class x, 0 -> false
8904   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8905     if (CMask->isNullValue())
8906       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8907   }
8908 
8909   if (N->getOperand(0).isUndef())
8910     return DAG.getUNDEF(MVT::i1);
8911 
8912   return SDValue();
8913 }
8914 
8915 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8916                                             DAGCombinerInfo &DCI) const {
8917   EVT VT = N->getValueType(0);
8918   SDValue N0 = N->getOperand(0);
8919 
8920   if (N0.isUndef())
8921     return N0;
8922 
8923   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8924                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8925     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8926                            N->getFlags());
8927   }
8928 
8929   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8930     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8931                            N0.getOperand(0), N->getFlags());
8932   }
8933 
8934   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8935 }
8936 
8937 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8938                                        unsigned MaxDepth) const {
8939   unsigned Opcode = Op.getOpcode();
8940   if (Opcode == ISD::FCANONICALIZE)
8941     return true;
8942 
8943   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8944     auto F = CFP->getValueAPF();
8945     if (F.isNaN() && F.isSignaling())
8946       return false;
8947     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8948   }
8949 
8950   // If source is a result of another standard FP operation it is already in
8951   // canonical form.
8952   if (MaxDepth == 0)
8953     return false;
8954 
8955   switch (Opcode) {
8956   // These will flush denorms if required.
8957   case ISD::FADD:
8958   case ISD::FSUB:
8959   case ISD::FMUL:
8960   case ISD::FCEIL:
8961   case ISD::FFLOOR:
8962   case ISD::FMA:
8963   case ISD::FMAD:
8964   case ISD::FSQRT:
8965   case ISD::FDIV:
8966   case ISD::FREM:
8967   case ISD::FP_ROUND:
8968   case ISD::FP_EXTEND:
8969   case AMDGPUISD::FMUL_LEGACY:
8970   case AMDGPUISD::FMAD_FTZ:
8971   case AMDGPUISD::RCP:
8972   case AMDGPUISD::RSQ:
8973   case AMDGPUISD::RSQ_CLAMP:
8974   case AMDGPUISD::RCP_LEGACY:
8975   case AMDGPUISD::RCP_IFLAG:
8976   case AMDGPUISD::TRIG_PREOP:
8977   case AMDGPUISD::DIV_SCALE:
8978   case AMDGPUISD::DIV_FMAS:
8979   case AMDGPUISD::DIV_FIXUP:
8980   case AMDGPUISD::FRACT:
8981   case AMDGPUISD::LDEXP:
8982   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8983   case AMDGPUISD::CVT_F32_UBYTE0:
8984   case AMDGPUISD::CVT_F32_UBYTE1:
8985   case AMDGPUISD::CVT_F32_UBYTE2:
8986   case AMDGPUISD::CVT_F32_UBYTE3:
8987     return true;
8988 
8989   // It can/will be lowered or combined as a bit operation.
8990   // Need to check their input recursively to handle.
8991   case ISD::FNEG:
8992   case ISD::FABS:
8993   case ISD::FCOPYSIGN:
8994     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8995 
8996   case ISD::FSIN:
8997   case ISD::FCOS:
8998   case ISD::FSINCOS:
8999     return Op.getValueType().getScalarType() != MVT::f16;
9000 
9001   case ISD::FMINNUM:
9002   case ISD::FMAXNUM:
9003   case ISD::FMINNUM_IEEE:
9004   case ISD::FMAXNUM_IEEE:
9005   case AMDGPUISD::CLAMP:
9006   case AMDGPUISD::FMED3:
9007   case AMDGPUISD::FMAX3:
9008   case AMDGPUISD::FMIN3: {
9009     // FIXME: Shouldn't treat the generic operations different based these.
9010     // However, we aren't really required to flush the result from
9011     // minnum/maxnum..
9012 
9013     // snans will be quieted, so we only need to worry about denormals.
9014     if (Subtarget->supportsMinMaxDenormModes() ||
9015         denormalsEnabledForType(DAG, Op.getValueType()))
9016       return true;
9017 
9018     // Flushing may be required.
9019     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9020     // targets need to check their input recursively.
9021 
9022     // FIXME: Does this apply with clamp? It's implemented with max.
9023     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9024       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9025         return false;
9026     }
9027 
9028     return true;
9029   }
9030   case ISD::SELECT: {
9031     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9032            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9033   }
9034   case ISD::BUILD_VECTOR: {
9035     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9036       SDValue SrcOp = Op.getOperand(i);
9037       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9038         return false;
9039     }
9040 
9041     return true;
9042   }
9043   case ISD::EXTRACT_VECTOR_ELT:
9044   case ISD::EXTRACT_SUBVECTOR: {
9045     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9046   }
9047   case ISD::INSERT_VECTOR_ELT: {
9048     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9049            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9050   }
9051   case ISD::UNDEF:
9052     // Could be anything.
9053     return false;
9054 
9055   case ISD::BITCAST: {
9056     // Hack round the mess we make when legalizing extract_vector_elt
9057     SDValue Src = Op.getOperand(0);
9058     if (Src.getValueType() == MVT::i16 &&
9059         Src.getOpcode() == ISD::TRUNCATE) {
9060       SDValue TruncSrc = Src.getOperand(0);
9061       if (TruncSrc.getValueType() == MVT::i32 &&
9062           TruncSrc.getOpcode() == ISD::BITCAST &&
9063           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9064         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9065       }
9066     }
9067 
9068     return false;
9069   }
9070   case ISD::INTRINSIC_WO_CHAIN: {
9071     unsigned IntrinsicID
9072       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9073     // TODO: Handle more intrinsics
9074     switch (IntrinsicID) {
9075     case Intrinsic::amdgcn_cvt_pkrtz:
9076     case Intrinsic::amdgcn_cubeid:
9077     case Intrinsic::amdgcn_frexp_mant:
9078     case Intrinsic::amdgcn_fdot2:
9079     case Intrinsic::amdgcn_rcp:
9080     case Intrinsic::amdgcn_rsq:
9081     case Intrinsic::amdgcn_rsq_clamp:
9082     case Intrinsic::amdgcn_rcp_legacy:
9083     case Intrinsic::amdgcn_rsq_legacy:
9084       return true;
9085     default:
9086       break;
9087     }
9088 
9089     LLVM_FALLTHROUGH;
9090   }
9091   default:
9092     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9093            DAG.isKnownNeverSNaN(Op);
9094   }
9095 
9096   llvm_unreachable("invalid operation");
9097 }
9098 
9099 // Constant fold canonicalize.
9100 SDValue SITargetLowering::getCanonicalConstantFP(
9101   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9102   // Flush denormals to 0 if not enabled.
9103   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9104     return DAG.getConstantFP(0.0, SL, VT);
9105 
9106   if (C.isNaN()) {
9107     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9108     if (C.isSignaling()) {
9109       // Quiet a signaling NaN.
9110       // FIXME: Is this supposed to preserve payload bits?
9111       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9112     }
9113 
9114     // Make sure it is the canonical NaN bitpattern.
9115     //
9116     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9117     // immediate?
9118     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9119       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9120   }
9121 
9122   // Already canonical.
9123   return DAG.getConstantFP(C, SL, VT);
9124 }
9125 
9126 static bool vectorEltWillFoldAway(SDValue Op) {
9127   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9128 }
9129 
9130 SDValue SITargetLowering::performFCanonicalizeCombine(
9131   SDNode *N,
9132   DAGCombinerInfo &DCI) const {
9133   SelectionDAG &DAG = DCI.DAG;
9134   SDValue N0 = N->getOperand(0);
9135   EVT VT = N->getValueType(0);
9136 
9137   // fcanonicalize undef -> qnan
9138   if (N0.isUndef()) {
9139     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9140     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9141   }
9142 
9143   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9144     EVT VT = N->getValueType(0);
9145     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9146   }
9147 
9148   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9149   //                                                   (fcanonicalize k)
9150   //
9151   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9152 
9153   // TODO: This could be better with wider vectors that will be split to v2f16,
9154   // and to consider uses since there aren't that many packed operations.
9155   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9156       isTypeLegal(MVT::v2f16)) {
9157     SDLoc SL(N);
9158     SDValue NewElts[2];
9159     SDValue Lo = N0.getOperand(0);
9160     SDValue Hi = N0.getOperand(1);
9161     EVT EltVT = Lo.getValueType();
9162 
9163     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9164       for (unsigned I = 0; I != 2; ++I) {
9165         SDValue Op = N0.getOperand(I);
9166         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9167           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9168                                               CFP->getValueAPF());
9169         } else if (Op.isUndef()) {
9170           // Handled below based on what the other operand is.
9171           NewElts[I] = Op;
9172         } else {
9173           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9174         }
9175       }
9176 
9177       // If one half is undef, and one is constant, perfer a splat vector rather
9178       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9179       // cheaper to use and may be free with a packed operation.
9180       if (NewElts[0].isUndef()) {
9181         if (isa<ConstantFPSDNode>(NewElts[1]))
9182           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9183             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9184       }
9185 
9186       if (NewElts[1].isUndef()) {
9187         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9188           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9189       }
9190 
9191       return DAG.getBuildVector(VT, SL, NewElts);
9192     }
9193   }
9194 
9195   unsigned SrcOpc = N0.getOpcode();
9196 
9197   // If it's free to do so, push canonicalizes further up the source, which may
9198   // find a canonical source.
9199   //
9200   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9201   // sNaNs.
9202   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9203     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9204     if (CRHS && N0.hasOneUse()) {
9205       SDLoc SL(N);
9206       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9207                                    N0.getOperand(0));
9208       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9209       DCI.AddToWorklist(Canon0.getNode());
9210 
9211       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9212     }
9213   }
9214 
9215   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9216 }
9217 
9218 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9219   switch (Opc) {
9220   case ISD::FMAXNUM:
9221   case ISD::FMAXNUM_IEEE:
9222     return AMDGPUISD::FMAX3;
9223   case ISD::SMAX:
9224     return AMDGPUISD::SMAX3;
9225   case ISD::UMAX:
9226     return AMDGPUISD::UMAX3;
9227   case ISD::FMINNUM:
9228   case ISD::FMINNUM_IEEE:
9229     return AMDGPUISD::FMIN3;
9230   case ISD::SMIN:
9231     return AMDGPUISD::SMIN3;
9232   case ISD::UMIN:
9233     return AMDGPUISD::UMIN3;
9234   default:
9235     llvm_unreachable("Not a min/max opcode");
9236   }
9237 }
9238 
9239 SDValue SITargetLowering::performIntMed3ImmCombine(
9240   SelectionDAG &DAG, const SDLoc &SL,
9241   SDValue Op0, SDValue Op1, bool Signed) const {
9242   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9243   if (!K1)
9244     return SDValue();
9245 
9246   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9247   if (!K0)
9248     return SDValue();
9249 
9250   if (Signed) {
9251     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9252       return SDValue();
9253   } else {
9254     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9255       return SDValue();
9256   }
9257 
9258   EVT VT = K0->getValueType(0);
9259   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9260   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9261     return DAG.getNode(Med3Opc, SL, VT,
9262                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9263   }
9264 
9265   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9266   MVT NVT = MVT::i32;
9267   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9268 
9269   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9270   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9271   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9272 
9273   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9274   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9275 }
9276 
9277 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9278   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9279     return C;
9280 
9281   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9282     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9283       return C;
9284   }
9285 
9286   return nullptr;
9287 }
9288 
9289 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9290                                                   const SDLoc &SL,
9291                                                   SDValue Op0,
9292                                                   SDValue Op1) const {
9293   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9294   if (!K1)
9295     return SDValue();
9296 
9297   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9298   if (!K0)
9299     return SDValue();
9300 
9301   // Ordered >= (although NaN inputs should have folded away by now).
9302   if (K0->getValueAPF() > K1->getValueAPF())
9303     return SDValue();
9304 
9305   const MachineFunction &MF = DAG.getMachineFunction();
9306   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9307 
9308   // TODO: Check IEEE bit enabled?
9309   EVT VT = Op0.getValueType();
9310   if (Info->getMode().DX10Clamp) {
9311     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9312     // hardware fmed3 behavior converting to a min.
9313     // FIXME: Should this be allowing -0.0?
9314     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9315       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9316   }
9317 
9318   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9319   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9320     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9321     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9322     // then give the other result, which is different from med3 with a NaN
9323     // input.
9324     SDValue Var = Op0.getOperand(0);
9325     if (!DAG.isKnownNeverSNaN(Var))
9326       return SDValue();
9327 
9328     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9329 
9330     if ((!K0->hasOneUse() ||
9331          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9332         (!K1->hasOneUse() ||
9333          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9334       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9335                          Var, SDValue(K0, 0), SDValue(K1, 0));
9336     }
9337   }
9338 
9339   return SDValue();
9340 }
9341 
9342 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9343                                                DAGCombinerInfo &DCI) const {
9344   SelectionDAG &DAG = DCI.DAG;
9345 
9346   EVT VT = N->getValueType(0);
9347   unsigned Opc = N->getOpcode();
9348   SDValue Op0 = N->getOperand(0);
9349   SDValue Op1 = N->getOperand(1);
9350 
9351   // Only do this if the inner op has one use since this will just increases
9352   // register pressure for no benefit.
9353 
9354   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9355       !VT.isVector() &&
9356       (VT == MVT::i32 || VT == MVT::f32 ||
9357        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9358     // max(max(a, b), c) -> max3(a, b, c)
9359     // min(min(a, b), c) -> min3(a, b, c)
9360     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9361       SDLoc DL(N);
9362       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9363                          DL,
9364                          N->getValueType(0),
9365                          Op0.getOperand(0),
9366                          Op0.getOperand(1),
9367                          Op1);
9368     }
9369 
9370     // Try commuted.
9371     // max(a, max(b, c)) -> max3(a, b, c)
9372     // min(a, min(b, c)) -> min3(a, b, c)
9373     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9374       SDLoc DL(N);
9375       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9376                          DL,
9377                          N->getValueType(0),
9378                          Op0,
9379                          Op1.getOperand(0),
9380                          Op1.getOperand(1));
9381     }
9382   }
9383 
9384   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9385   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9386     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9387       return Med3;
9388   }
9389 
9390   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9391     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9392       return Med3;
9393   }
9394 
9395   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9396   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9397        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9398        (Opc == AMDGPUISD::FMIN_LEGACY &&
9399         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9400       (VT == MVT::f32 || VT == MVT::f64 ||
9401        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9402        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9403       Op0.hasOneUse()) {
9404     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9405       return Res;
9406   }
9407 
9408   return SDValue();
9409 }
9410 
9411 static bool isClampZeroToOne(SDValue A, SDValue B) {
9412   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9413     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9414       // FIXME: Should this be allowing -0.0?
9415       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9416              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9417     }
9418   }
9419 
9420   return false;
9421 }
9422 
9423 // FIXME: Should only worry about snans for version with chain.
9424 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9425                                               DAGCombinerInfo &DCI) const {
9426   EVT VT = N->getValueType(0);
9427   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9428   // NaNs. With a NaN input, the order of the operands may change the result.
9429 
9430   SelectionDAG &DAG = DCI.DAG;
9431   SDLoc SL(N);
9432 
9433   SDValue Src0 = N->getOperand(0);
9434   SDValue Src1 = N->getOperand(1);
9435   SDValue Src2 = N->getOperand(2);
9436 
9437   if (isClampZeroToOne(Src0, Src1)) {
9438     // const_a, const_b, x -> clamp is safe in all cases including signaling
9439     // nans.
9440     // FIXME: Should this be allowing -0.0?
9441     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9442   }
9443 
9444   const MachineFunction &MF = DAG.getMachineFunction();
9445   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9446 
9447   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9448   // handling no dx10-clamp?
9449   if (Info->getMode().DX10Clamp) {
9450     // If NaNs is clamped to 0, we are free to reorder the inputs.
9451 
9452     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9453       std::swap(Src0, Src1);
9454 
9455     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9456       std::swap(Src1, Src2);
9457 
9458     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9459       std::swap(Src0, Src1);
9460 
9461     if (isClampZeroToOne(Src1, Src2))
9462       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9463   }
9464 
9465   return SDValue();
9466 }
9467 
9468 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9469                                                  DAGCombinerInfo &DCI) const {
9470   SDValue Src0 = N->getOperand(0);
9471   SDValue Src1 = N->getOperand(1);
9472   if (Src0.isUndef() && Src1.isUndef())
9473     return DCI.DAG.getUNDEF(N->getValueType(0));
9474   return SDValue();
9475 }
9476 
9477 SDValue SITargetLowering::performExtractVectorEltCombine(
9478   SDNode *N, DAGCombinerInfo &DCI) const {
9479   SDValue Vec = N->getOperand(0);
9480   SelectionDAG &DAG = DCI.DAG;
9481 
9482   EVT VecVT = Vec.getValueType();
9483   EVT EltVT = VecVT.getVectorElementType();
9484 
9485   if ((Vec.getOpcode() == ISD::FNEG ||
9486        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9487     SDLoc SL(N);
9488     EVT EltVT = N->getValueType(0);
9489     SDValue Idx = N->getOperand(1);
9490     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9491                               Vec.getOperand(0), Idx);
9492     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9493   }
9494 
9495   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9496   //    =>
9497   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9498   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9499   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9500   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9501     SDLoc SL(N);
9502     EVT EltVT = N->getValueType(0);
9503     SDValue Idx = N->getOperand(1);
9504     unsigned Opc = Vec.getOpcode();
9505 
9506     switch(Opc) {
9507     default:
9508       break;
9509       // TODO: Support other binary operations.
9510     case ISD::FADD:
9511     case ISD::FSUB:
9512     case ISD::FMUL:
9513     case ISD::ADD:
9514     case ISD::UMIN:
9515     case ISD::UMAX:
9516     case ISD::SMIN:
9517     case ISD::SMAX:
9518     case ISD::FMAXNUM:
9519     case ISD::FMINNUM:
9520     case ISD::FMAXNUM_IEEE:
9521     case ISD::FMINNUM_IEEE: {
9522       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9523                                  Vec.getOperand(0), Idx);
9524       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9525                                  Vec.getOperand(1), Idx);
9526 
9527       DCI.AddToWorklist(Elt0.getNode());
9528       DCI.AddToWorklist(Elt1.getNode());
9529       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9530     }
9531     }
9532   }
9533 
9534   unsigned VecSize = VecVT.getSizeInBits();
9535   unsigned EltSize = EltVT.getSizeInBits();
9536 
9537   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9538   // This elminates non-constant index and subsequent movrel or scratch access.
9539   // Sub-dword vectors of size 2 dword or less have better implementation.
9540   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9541   // instructions.
9542   // Always do this if var-idx is divergent, otherwise it will become a loop.
9543   if (!UseDivergentRegisterIndexing &&
9544       (VecSize <= 256 || N->getOperand(1)->isDivergent()) &&
9545       (VecSize > 64 || EltSize >= 32) &&
9546       !isa<ConstantSDNode>(N->getOperand(1))) {
9547     SDLoc SL(N);
9548     SDValue Idx = N->getOperand(1);
9549     SDValue V;
9550     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9551       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9552       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9553       if (I == 0)
9554         V = Elt;
9555       else
9556         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9557     }
9558     return V;
9559   }
9560 
9561   if (!DCI.isBeforeLegalize())
9562     return SDValue();
9563 
9564   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9565   // elements. This exposes more load reduction opportunities by replacing
9566   // multiple small extract_vector_elements with a single 32-bit extract.
9567   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9568   if (isa<MemSDNode>(Vec) &&
9569       EltSize <= 16 &&
9570       EltVT.isByteSized() &&
9571       VecSize > 32 &&
9572       VecSize % 32 == 0 &&
9573       Idx) {
9574     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9575 
9576     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9577     unsigned EltIdx = BitIndex / 32;
9578     unsigned LeftoverBitIdx = BitIndex % 32;
9579     SDLoc SL(N);
9580 
9581     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9582     DCI.AddToWorklist(Cast.getNode());
9583 
9584     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9585                               DAG.getConstant(EltIdx, SL, MVT::i32));
9586     DCI.AddToWorklist(Elt.getNode());
9587     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9588                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9589     DCI.AddToWorklist(Srl.getNode());
9590 
9591     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9592     DCI.AddToWorklist(Trunc.getNode());
9593     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9594   }
9595 
9596   return SDValue();
9597 }
9598 
9599 SDValue
9600 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9601                                                 DAGCombinerInfo &DCI) const {
9602   SDValue Vec = N->getOperand(0);
9603   SDValue Idx = N->getOperand(2);
9604   EVT VecVT = Vec.getValueType();
9605   EVT EltVT = VecVT.getVectorElementType();
9606   unsigned VecSize = VecVT.getSizeInBits();
9607   unsigned EltSize = EltVT.getSizeInBits();
9608 
9609   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9610   // => BUILD_VECTOR n x select (e, const-idx)
9611   // This elminates non-constant index and subsequent movrel or scratch access.
9612   // Sub-dword vectors of size 2 dword or less have better implementation.
9613   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9614   // instructions.
9615   // Always do this if var-idx is divergent, otherwise it will become a loop.
9616   if (UseDivergentRegisterIndexing || isa<ConstantSDNode>(Idx) ||
9617       (VecSize > 256 && !Idx->isDivergent()) ||
9618       (VecSize <= 64 && EltSize < 32))
9619     return SDValue();
9620 
9621   SelectionDAG &DAG = DCI.DAG;
9622   SDLoc SL(N);
9623   SDValue Ins = N->getOperand(1);
9624   EVT IdxVT = Idx.getValueType();
9625 
9626   SmallVector<SDValue, 16> Ops;
9627   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9628     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9629     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9630     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9631     Ops.push_back(V);
9632   }
9633 
9634   return DAG.getBuildVector(VecVT, SL, Ops);
9635 }
9636 
9637 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9638                                           const SDNode *N0,
9639                                           const SDNode *N1) const {
9640   EVT VT = N0->getValueType(0);
9641 
9642   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9643   // support denormals ever.
9644   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9645        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9646         getSubtarget()->hasMadF16())) &&
9647        isOperationLegal(ISD::FMAD, VT))
9648     return ISD::FMAD;
9649 
9650   const TargetOptions &Options = DAG.getTarget().Options;
9651   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9652        (N0->getFlags().hasAllowContract() &&
9653         N1->getFlags().hasAllowContract())) &&
9654       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9655     return ISD::FMA;
9656   }
9657 
9658   return 0;
9659 }
9660 
9661 // For a reassociatable opcode perform:
9662 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9663 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9664                                                SelectionDAG &DAG) const {
9665   EVT VT = N->getValueType(0);
9666   if (VT != MVT::i32 && VT != MVT::i64)
9667     return SDValue();
9668 
9669   unsigned Opc = N->getOpcode();
9670   SDValue Op0 = N->getOperand(0);
9671   SDValue Op1 = N->getOperand(1);
9672 
9673   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9674     return SDValue();
9675 
9676   if (Op0->isDivergent())
9677     std::swap(Op0, Op1);
9678 
9679   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9680     return SDValue();
9681 
9682   SDValue Op2 = Op1.getOperand(1);
9683   Op1 = Op1.getOperand(0);
9684   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9685     return SDValue();
9686 
9687   if (Op1->isDivergent())
9688     std::swap(Op1, Op2);
9689 
9690   // If either operand is constant this will conflict with
9691   // DAGCombiner::ReassociateOps().
9692   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9693       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9694     return SDValue();
9695 
9696   SDLoc SL(N);
9697   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9698   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9699 }
9700 
9701 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9702                            EVT VT,
9703                            SDValue N0, SDValue N1, SDValue N2,
9704                            bool Signed) {
9705   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9706   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9707   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9708   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9709 }
9710 
9711 SDValue SITargetLowering::performAddCombine(SDNode *N,
9712                                             DAGCombinerInfo &DCI) const {
9713   SelectionDAG &DAG = DCI.DAG;
9714   EVT VT = N->getValueType(0);
9715   SDLoc SL(N);
9716   SDValue LHS = N->getOperand(0);
9717   SDValue RHS = N->getOperand(1);
9718 
9719   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9720       && Subtarget->hasMad64_32() &&
9721       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9722       VT.getScalarSizeInBits() <= 64) {
9723     if (LHS.getOpcode() != ISD::MUL)
9724       std::swap(LHS, RHS);
9725 
9726     SDValue MulLHS = LHS.getOperand(0);
9727     SDValue MulRHS = LHS.getOperand(1);
9728     SDValue AddRHS = RHS;
9729 
9730     // TODO: Maybe restrict if SGPR inputs.
9731     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9732         numBitsUnsigned(MulRHS, DAG) <= 32) {
9733       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9734       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9735       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9736       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9737     }
9738 
9739     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9740       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9741       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9742       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9743       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9744     }
9745 
9746     return SDValue();
9747   }
9748 
9749   if (SDValue V = reassociateScalarOps(N, DAG)) {
9750     return V;
9751   }
9752 
9753   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9754     return SDValue();
9755 
9756   // add x, zext (setcc) => addcarry x, 0, setcc
9757   // add x, sext (setcc) => subcarry x, 0, setcc
9758   unsigned Opc = LHS.getOpcode();
9759   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9760       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9761     std::swap(RHS, LHS);
9762 
9763   Opc = RHS.getOpcode();
9764   switch (Opc) {
9765   default: break;
9766   case ISD::ZERO_EXTEND:
9767   case ISD::SIGN_EXTEND:
9768   case ISD::ANY_EXTEND: {
9769     auto Cond = RHS.getOperand(0);
9770     // If this won't be a real VOPC output, we would still need to insert an
9771     // extra instruction anyway.
9772     if (!isBoolSGPR(Cond))
9773       break;
9774     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9775     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9776     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9777     return DAG.getNode(Opc, SL, VTList, Args);
9778   }
9779   case ISD::ADDCARRY: {
9780     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9781     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9782     if (!C || C->getZExtValue() != 0) break;
9783     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9784     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9785   }
9786   }
9787   return SDValue();
9788 }
9789 
9790 SDValue SITargetLowering::performSubCombine(SDNode *N,
9791                                             DAGCombinerInfo &DCI) const {
9792   SelectionDAG &DAG = DCI.DAG;
9793   EVT VT = N->getValueType(0);
9794 
9795   if (VT != MVT::i32)
9796     return SDValue();
9797 
9798   SDLoc SL(N);
9799   SDValue LHS = N->getOperand(0);
9800   SDValue RHS = N->getOperand(1);
9801 
9802   // sub x, zext (setcc) => subcarry x, 0, setcc
9803   // sub x, sext (setcc) => addcarry x, 0, setcc
9804   unsigned Opc = RHS.getOpcode();
9805   switch (Opc) {
9806   default: break;
9807   case ISD::ZERO_EXTEND:
9808   case ISD::SIGN_EXTEND:
9809   case ISD::ANY_EXTEND: {
9810     auto Cond = RHS.getOperand(0);
9811     // If this won't be a real VOPC output, we would still need to insert an
9812     // extra instruction anyway.
9813     if (!isBoolSGPR(Cond))
9814       break;
9815     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9816     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9817     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9818     return DAG.getNode(Opc, SL, VTList, Args);
9819   }
9820   }
9821 
9822   if (LHS.getOpcode() == ISD::SUBCARRY) {
9823     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9824     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9825     if (!C || !C->isNullValue())
9826       return SDValue();
9827     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9828     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9829   }
9830   return SDValue();
9831 }
9832 
9833 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9834   DAGCombinerInfo &DCI) const {
9835 
9836   if (N->getValueType(0) != MVT::i32)
9837     return SDValue();
9838 
9839   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9840   if (!C || C->getZExtValue() != 0)
9841     return SDValue();
9842 
9843   SelectionDAG &DAG = DCI.DAG;
9844   SDValue LHS = N->getOperand(0);
9845 
9846   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9847   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9848   unsigned LHSOpc = LHS.getOpcode();
9849   unsigned Opc = N->getOpcode();
9850   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9851       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9852     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9853     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9854   }
9855   return SDValue();
9856 }
9857 
9858 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9859                                              DAGCombinerInfo &DCI) const {
9860   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9861     return SDValue();
9862 
9863   SelectionDAG &DAG = DCI.DAG;
9864   EVT VT = N->getValueType(0);
9865 
9866   SDLoc SL(N);
9867   SDValue LHS = N->getOperand(0);
9868   SDValue RHS = N->getOperand(1);
9869 
9870   // These should really be instruction patterns, but writing patterns with
9871   // source modiifiers is a pain.
9872 
9873   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9874   if (LHS.getOpcode() == ISD::FADD) {
9875     SDValue A = LHS.getOperand(0);
9876     if (A == LHS.getOperand(1)) {
9877       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9878       if (FusedOp != 0) {
9879         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9880         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9881       }
9882     }
9883   }
9884 
9885   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9886   if (RHS.getOpcode() == ISD::FADD) {
9887     SDValue A = RHS.getOperand(0);
9888     if (A == RHS.getOperand(1)) {
9889       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9890       if (FusedOp != 0) {
9891         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9892         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9893       }
9894     }
9895   }
9896 
9897   return SDValue();
9898 }
9899 
9900 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9901                                              DAGCombinerInfo &DCI) const {
9902   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9903     return SDValue();
9904 
9905   SelectionDAG &DAG = DCI.DAG;
9906   SDLoc SL(N);
9907   EVT VT = N->getValueType(0);
9908   assert(!VT.isVector());
9909 
9910   // Try to get the fneg to fold into the source modifier. This undoes generic
9911   // DAG combines and folds them into the mad.
9912   //
9913   // Only do this if we are not trying to support denormals. v_mad_f32 does
9914   // not support denormals ever.
9915   SDValue LHS = N->getOperand(0);
9916   SDValue RHS = N->getOperand(1);
9917   if (LHS.getOpcode() == ISD::FADD) {
9918     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9919     SDValue A = LHS.getOperand(0);
9920     if (A == LHS.getOperand(1)) {
9921       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9922       if (FusedOp != 0){
9923         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9924         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9925 
9926         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9927       }
9928     }
9929   }
9930 
9931   if (RHS.getOpcode() == ISD::FADD) {
9932     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9933 
9934     SDValue A = RHS.getOperand(0);
9935     if (A == RHS.getOperand(1)) {
9936       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9937       if (FusedOp != 0){
9938         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9939         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9940       }
9941     }
9942   }
9943 
9944   return SDValue();
9945 }
9946 
9947 SDValue SITargetLowering::performFMACombine(SDNode *N,
9948                                             DAGCombinerInfo &DCI) const {
9949   SelectionDAG &DAG = DCI.DAG;
9950   EVT VT = N->getValueType(0);
9951   SDLoc SL(N);
9952 
9953   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9954     return SDValue();
9955 
9956   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9957   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9958   SDValue Op1 = N->getOperand(0);
9959   SDValue Op2 = N->getOperand(1);
9960   SDValue FMA = N->getOperand(2);
9961 
9962   if (FMA.getOpcode() != ISD::FMA ||
9963       Op1.getOpcode() != ISD::FP_EXTEND ||
9964       Op2.getOpcode() != ISD::FP_EXTEND)
9965     return SDValue();
9966 
9967   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9968   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9969   // is sufficient to allow generaing fdot2.
9970   const TargetOptions &Options = DAG.getTarget().Options;
9971   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9972       (N->getFlags().hasAllowContract() &&
9973        FMA->getFlags().hasAllowContract())) {
9974     Op1 = Op1.getOperand(0);
9975     Op2 = Op2.getOperand(0);
9976     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9977         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9978       return SDValue();
9979 
9980     SDValue Vec1 = Op1.getOperand(0);
9981     SDValue Idx1 = Op1.getOperand(1);
9982     SDValue Vec2 = Op2.getOperand(0);
9983 
9984     SDValue FMAOp1 = FMA.getOperand(0);
9985     SDValue FMAOp2 = FMA.getOperand(1);
9986     SDValue FMAAcc = FMA.getOperand(2);
9987 
9988     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9989         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9990       return SDValue();
9991 
9992     FMAOp1 = FMAOp1.getOperand(0);
9993     FMAOp2 = FMAOp2.getOperand(0);
9994     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9995         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9996       return SDValue();
9997 
9998     SDValue Vec3 = FMAOp1.getOperand(0);
9999     SDValue Vec4 = FMAOp2.getOperand(0);
10000     SDValue Idx2 = FMAOp1.getOperand(1);
10001 
10002     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10003         // Idx1 and Idx2 cannot be the same.
10004         Idx1 == Idx2)
10005       return SDValue();
10006 
10007     if (Vec1 == Vec2 || Vec3 == Vec4)
10008       return SDValue();
10009 
10010     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10011       return SDValue();
10012 
10013     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10014         (Vec1 == Vec4 && Vec2 == Vec3)) {
10015       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10016                          DAG.getTargetConstant(0, SL, MVT::i1));
10017     }
10018   }
10019   return SDValue();
10020 }
10021 
10022 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10023                                               DAGCombinerInfo &DCI) const {
10024   SelectionDAG &DAG = DCI.DAG;
10025   SDLoc SL(N);
10026 
10027   SDValue LHS = N->getOperand(0);
10028   SDValue RHS = N->getOperand(1);
10029   EVT VT = LHS.getValueType();
10030   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10031 
10032   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10033   if (!CRHS) {
10034     CRHS = dyn_cast<ConstantSDNode>(LHS);
10035     if (CRHS) {
10036       std::swap(LHS, RHS);
10037       CC = getSetCCSwappedOperands(CC);
10038     }
10039   }
10040 
10041   if (CRHS) {
10042     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10043         isBoolSGPR(LHS.getOperand(0))) {
10044       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10045       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10046       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10047       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10048       if ((CRHS->isAllOnesValue() &&
10049            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10050           (CRHS->isNullValue() &&
10051            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10052         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10053                            DAG.getConstant(-1, SL, MVT::i1));
10054       if ((CRHS->isAllOnesValue() &&
10055            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10056           (CRHS->isNullValue() &&
10057            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10058         return LHS.getOperand(0);
10059     }
10060 
10061     uint64_t CRHSVal = CRHS->getZExtValue();
10062     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10063         LHS.getOpcode() == ISD::SELECT &&
10064         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10065         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10066         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10067         isBoolSGPR(LHS.getOperand(0))) {
10068       // Given CT != FT:
10069       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10070       // setcc (select cc, CT, CF), CF, ne => cc
10071       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10072       // setcc (select cc, CT, CF), CT, eq => cc
10073       uint64_t CT = LHS.getConstantOperandVal(1);
10074       uint64_t CF = LHS.getConstantOperandVal(2);
10075 
10076       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10077           (CT == CRHSVal && CC == ISD::SETNE))
10078         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10079                            DAG.getConstant(-1, SL, MVT::i1));
10080       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10081           (CT == CRHSVal && CC == ISD::SETEQ))
10082         return LHS.getOperand(0);
10083     }
10084   }
10085 
10086   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10087                                            VT != MVT::f16))
10088     return SDValue();
10089 
10090   // Match isinf/isfinite pattern
10091   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10092   // (fcmp one (fabs x), inf) -> (fp_class x,
10093   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10094   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10095     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10096     if (!CRHS)
10097       return SDValue();
10098 
10099     const APFloat &APF = CRHS->getValueAPF();
10100     if (APF.isInfinity() && !APF.isNegative()) {
10101       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10102                                  SIInstrFlags::N_INFINITY;
10103       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10104                                     SIInstrFlags::P_ZERO |
10105                                     SIInstrFlags::N_NORMAL |
10106                                     SIInstrFlags::P_NORMAL |
10107                                     SIInstrFlags::N_SUBNORMAL |
10108                                     SIInstrFlags::P_SUBNORMAL;
10109       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10110       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10111                          DAG.getConstant(Mask, SL, MVT::i32));
10112     }
10113   }
10114 
10115   return SDValue();
10116 }
10117 
10118 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10119                                                      DAGCombinerInfo &DCI) const {
10120   SelectionDAG &DAG = DCI.DAG;
10121   SDLoc SL(N);
10122   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10123 
10124   SDValue Src = N->getOperand(0);
10125   SDValue Shift = N->getOperand(0);
10126 
10127   // TODO: Extend type shouldn't matter (assuming legal types).
10128   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10129     Shift = Shift.getOperand(0);
10130 
10131   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10132     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10133     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10134     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10135     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10136     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10137     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10138       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10139                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10140 
10141       unsigned ShiftOffset = 8 * Offset;
10142       if (Shift.getOpcode() == ISD::SHL)
10143         ShiftOffset -= C->getZExtValue();
10144       else
10145         ShiftOffset += C->getZExtValue();
10146 
10147       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10148         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10149                            MVT::f32, Shift);
10150       }
10151     }
10152   }
10153 
10154   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10155   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10156   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10157     // We simplified Src. If this node is not dead, visit it again so it is
10158     // folded properly.
10159     if (N->getOpcode() != ISD::DELETED_NODE)
10160       DCI.AddToWorklist(N);
10161     return SDValue(N, 0);
10162   }
10163 
10164   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10165   if (SDValue DemandedSrc =
10166           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10167     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10168 
10169   return SDValue();
10170 }
10171 
10172 SDValue SITargetLowering::performClampCombine(SDNode *N,
10173                                               DAGCombinerInfo &DCI) const {
10174   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10175   if (!CSrc)
10176     return SDValue();
10177 
10178   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10179   const APFloat &F = CSrc->getValueAPF();
10180   APFloat Zero = APFloat::getZero(F.getSemantics());
10181   if (F < Zero ||
10182       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10183     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10184   }
10185 
10186   APFloat One(F.getSemantics(), "1.0");
10187   if (F > One)
10188     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10189 
10190   return SDValue(CSrc, 0);
10191 }
10192 
10193 
10194 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10195                                             DAGCombinerInfo &DCI) const {
10196   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10197     return SDValue();
10198   switch (N->getOpcode()) {
10199   default:
10200     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10201   case ISD::ADD:
10202     return performAddCombine(N, DCI);
10203   case ISD::SUB:
10204     return performSubCombine(N, DCI);
10205   case ISD::ADDCARRY:
10206   case ISD::SUBCARRY:
10207     return performAddCarrySubCarryCombine(N, DCI);
10208   case ISD::FADD:
10209     return performFAddCombine(N, DCI);
10210   case ISD::FSUB:
10211     return performFSubCombine(N, DCI);
10212   case ISD::SETCC:
10213     return performSetCCCombine(N, DCI);
10214   case ISD::FMAXNUM:
10215   case ISD::FMINNUM:
10216   case ISD::FMAXNUM_IEEE:
10217   case ISD::FMINNUM_IEEE:
10218   case ISD::SMAX:
10219   case ISD::SMIN:
10220   case ISD::UMAX:
10221   case ISD::UMIN:
10222   case AMDGPUISD::FMIN_LEGACY:
10223   case AMDGPUISD::FMAX_LEGACY:
10224     return performMinMaxCombine(N, DCI);
10225   case ISD::FMA:
10226     return performFMACombine(N, DCI);
10227   case ISD::LOAD: {
10228     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10229       return Widended;
10230     LLVM_FALLTHROUGH;
10231   }
10232   case ISD::STORE:
10233   case ISD::ATOMIC_LOAD:
10234   case ISD::ATOMIC_STORE:
10235   case ISD::ATOMIC_CMP_SWAP:
10236   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10237   case ISD::ATOMIC_SWAP:
10238   case ISD::ATOMIC_LOAD_ADD:
10239   case ISD::ATOMIC_LOAD_SUB:
10240   case ISD::ATOMIC_LOAD_AND:
10241   case ISD::ATOMIC_LOAD_OR:
10242   case ISD::ATOMIC_LOAD_XOR:
10243   case ISD::ATOMIC_LOAD_NAND:
10244   case ISD::ATOMIC_LOAD_MIN:
10245   case ISD::ATOMIC_LOAD_MAX:
10246   case ISD::ATOMIC_LOAD_UMIN:
10247   case ISD::ATOMIC_LOAD_UMAX:
10248   case ISD::ATOMIC_LOAD_FADD:
10249   case AMDGPUISD::ATOMIC_INC:
10250   case AMDGPUISD::ATOMIC_DEC:
10251   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10252   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10253     if (DCI.isBeforeLegalize())
10254       break;
10255     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10256   case ISD::AND:
10257     return performAndCombine(N, DCI);
10258   case ISD::OR:
10259     return performOrCombine(N, DCI);
10260   case ISD::XOR:
10261     return performXorCombine(N, DCI);
10262   case ISD::ZERO_EXTEND:
10263     return performZeroExtendCombine(N, DCI);
10264   case ISD::SIGN_EXTEND_INREG:
10265     return performSignExtendInRegCombine(N , DCI);
10266   case AMDGPUISD::FP_CLASS:
10267     return performClassCombine(N, DCI);
10268   case ISD::FCANONICALIZE:
10269     return performFCanonicalizeCombine(N, DCI);
10270   case AMDGPUISD::RCP:
10271     return performRcpCombine(N, DCI);
10272   case AMDGPUISD::FRACT:
10273   case AMDGPUISD::RSQ:
10274   case AMDGPUISD::RCP_LEGACY:
10275   case AMDGPUISD::RCP_IFLAG:
10276   case AMDGPUISD::RSQ_CLAMP:
10277   case AMDGPUISD::LDEXP: {
10278     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10279     SDValue Src = N->getOperand(0);
10280     if (Src.isUndef())
10281       return Src;
10282     break;
10283   }
10284   case ISD::SINT_TO_FP:
10285   case ISD::UINT_TO_FP:
10286     return performUCharToFloatCombine(N, DCI);
10287   case AMDGPUISD::CVT_F32_UBYTE0:
10288   case AMDGPUISD::CVT_F32_UBYTE1:
10289   case AMDGPUISD::CVT_F32_UBYTE2:
10290   case AMDGPUISD::CVT_F32_UBYTE3:
10291     return performCvtF32UByteNCombine(N, DCI);
10292   case AMDGPUISD::FMED3:
10293     return performFMed3Combine(N, DCI);
10294   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10295     return performCvtPkRTZCombine(N, DCI);
10296   case AMDGPUISD::CLAMP:
10297     return performClampCombine(N, DCI);
10298   case ISD::SCALAR_TO_VECTOR: {
10299     SelectionDAG &DAG = DCI.DAG;
10300     EVT VT = N->getValueType(0);
10301 
10302     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10303     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10304       SDLoc SL(N);
10305       SDValue Src = N->getOperand(0);
10306       EVT EltVT = Src.getValueType();
10307       if (EltVT == MVT::f16)
10308         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10309 
10310       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10311       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10312     }
10313 
10314     break;
10315   }
10316   case ISD::EXTRACT_VECTOR_ELT:
10317     return performExtractVectorEltCombine(N, DCI);
10318   case ISD::INSERT_VECTOR_ELT:
10319     return performInsertVectorEltCombine(N, DCI);
10320   }
10321   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10322 }
10323 
10324 /// Helper function for adjustWritemask
10325 static unsigned SubIdx2Lane(unsigned Idx) {
10326   switch (Idx) {
10327   default: return 0;
10328   case AMDGPU::sub0: return 0;
10329   case AMDGPU::sub1: return 1;
10330   case AMDGPU::sub2: return 2;
10331   case AMDGPU::sub3: return 3;
10332   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10333   }
10334 }
10335 
10336 /// Adjust the writemask of MIMG instructions
10337 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10338                                           SelectionDAG &DAG) const {
10339   unsigned Opcode = Node->getMachineOpcode();
10340 
10341   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10342   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10343   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10344     return Node; // not implemented for D16
10345 
10346   SDNode *Users[5] = { nullptr };
10347   unsigned Lane = 0;
10348   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10349   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10350   unsigned NewDmask = 0;
10351   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10352   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10353   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10354                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10355   unsigned TFCLane = 0;
10356   bool HasChain = Node->getNumValues() > 1;
10357 
10358   if (OldDmask == 0) {
10359     // These are folded out, but on the chance it happens don't assert.
10360     return Node;
10361   }
10362 
10363   unsigned OldBitsSet = countPopulation(OldDmask);
10364   // Work out which is the TFE/LWE lane if that is enabled.
10365   if (UsesTFC) {
10366     TFCLane = OldBitsSet;
10367   }
10368 
10369   // Try to figure out the used register components
10370   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10371        I != E; ++I) {
10372 
10373     // Don't look at users of the chain.
10374     if (I.getUse().getResNo() != 0)
10375       continue;
10376 
10377     // Abort if we can't understand the usage
10378     if (!I->isMachineOpcode() ||
10379         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10380       return Node;
10381 
10382     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10383     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10384     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10385     // set, etc.
10386     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10387 
10388     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10389     if (UsesTFC && Lane == TFCLane) {
10390       Users[Lane] = *I;
10391     } else {
10392       // Set which texture component corresponds to the lane.
10393       unsigned Comp;
10394       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10395         Comp = countTrailingZeros(Dmask);
10396         Dmask &= ~(1 << Comp);
10397       }
10398 
10399       // Abort if we have more than one user per component.
10400       if (Users[Lane])
10401         return Node;
10402 
10403       Users[Lane] = *I;
10404       NewDmask |= 1 << Comp;
10405     }
10406   }
10407 
10408   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10409   bool NoChannels = !NewDmask;
10410   if (NoChannels) {
10411     if (!UsesTFC) {
10412       // No uses of the result and not using TFC. Then do nothing.
10413       return Node;
10414     }
10415     // If the original dmask has one channel - then nothing to do
10416     if (OldBitsSet == 1)
10417       return Node;
10418     // Use an arbitrary dmask - required for the instruction to work
10419     NewDmask = 1;
10420   }
10421   // Abort if there's no change
10422   if (NewDmask == OldDmask)
10423     return Node;
10424 
10425   unsigned BitsSet = countPopulation(NewDmask);
10426 
10427   // Check for TFE or LWE - increase the number of channels by one to account
10428   // for the extra return value
10429   // This will need adjustment for D16 if this is also included in
10430   // adjustWriteMask (this function) but at present D16 are excluded.
10431   unsigned NewChannels = BitsSet + UsesTFC;
10432 
10433   int NewOpcode =
10434       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10435   assert(NewOpcode != -1 &&
10436          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10437          "failed to find equivalent MIMG op");
10438 
10439   // Adjust the writemask in the node
10440   SmallVector<SDValue, 12> Ops;
10441   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10442   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10443   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10444 
10445   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10446 
10447   MVT ResultVT = NewChannels == 1 ?
10448     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10449                            NewChannels == 5 ? 8 : NewChannels);
10450   SDVTList NewVTList = HasChain ?
10451     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10452 
10453 
10454   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10455                                               NewVTList, Ops);
10456 
10457   if (HasChain) {
10458     // Update chain.
10459     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10460     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10461   }
10462 
10463   if (NewChannels == 1) {
10464     assert(Node->hasNUsesOfValue(1, 0));
10465     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10466                                       SDLoc(Node), Users[Lane]->getValueType(0),
10467                                       SDValue(NewNode, 0));
10468     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10469     return nullptr;
10470   }
10471 
10472   // Update the users of the node with the new indices
10473   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10474     SDNode *User = Users[i];
10475     if (!User) {
10476       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10477       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10478       if (i || !NoChannels)
10479         continue;
10480     } else {
10481       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10482       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10483     }
10484 
10485     switch (Idx) {
10486     default: break;
10487     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10488     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10489     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10490     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10491     }
10492   }
10493 
10494   DAG.RemoveDeadNode(Node);
10495   return nullptr;
10496 }
10497 
10498 static bool isFrameIndexOp(SDValue Op) {
10499   if (Op.getOpcode() == ISD::AssertZext)
10500     Op = Op.getOperand(0);
10501 
10502   return isa<FrameIndexSDNode>(Op);
10503 }
10504 
10505 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10506 /// with frame index operands.
10507 /// LLVM assumes that inputs are to these instructions are registers.
10508 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10509                                                         SelectionDAG &DAG) const {
10510   if (Node->getOpcode() == ISD::CopyToReg) {
10511     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10512     SDValue SrcVal = Node->getOperand(2);
10513 
10514     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10515     // to try understanding copies to physical registers.
10516     if (SrcVal.getValueType() == MVT::i1 &&
10517         Register::isPhysicalRegister(DestReg->getReg())) {
10518       SDLoc SL(Node);
10519       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10520       SDValue VReg = DAG.getRegister(
10521         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10522 
10523       SDNode *Glued = Node->getGluedNode();
10524       SDValue ToVReg
10525         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10526                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10527       SDValue ToResultReg
10528         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10529                            VReg, ToVReg.getValue(1));
10530       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10531       DAG.RemoveDeadNode(Node);
10532       return ToResultReg.getNode();
10533     }
10534   }
10535 
10536   SmallVector<SDValue, 8> Ops;
10537   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10538     if (!isFrameIndexOp(Node->getOperand(i))) {
10539       Ops.push_back(Node->getOperand(i));
10540       continue;
10541     }
10542 
10543     SDLoc DL(Node);
10544     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10545                                      Node->getOperand(i).getValueType(),
10546                                      Node->getOperand(i)), 0));
10547   }
10548 
10549   return DAG.UpdateNodeOperands(Node, Ops);
10550 }
10551 
10552 /// Fold the instructions after selecting them.
10553 /// Returns null if users were already updated.
10554 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10555                                           SelectionDAG &DAG) const {
10556   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10557   unsigned Opcode = Node->getMachineOpcode();
10558 
10559   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10560       !TII->isGather4(Opcode)) {
10561     return adjustWritemask(Node, DAG);
10562   }
10563 
10564   if (Opcode == AMDGPU::INSERT_SUBREG ||
10565       Opcode == AMDGPU::REG_SEQUENCE) {
10566     legalizeTargetIndependentNode(Node, DAG);
10567     return Node;
10568   }
10569 
10570   switch (Opcode) {
10571   case AMDGPU::V_DIV_SCALE_F32:
10572   case AMDGPU::V_DIV_SCALE_F64: {
10573     // Satisfy the operand register constraint when one of the inputs is
10574     // undefined. Ordinarily each undef value will have its own implicit_def of
10575     // a vreg, so force these to use a single register.
10576     SDValue Src0 = Node->getOperand(0);
10577     SDValue Src1 = Node->getOperand(1);
10578     SDValue Src2 = Node->getOperand(2);
10579 
10580     if ((Src0.isMachineOpcode() &&
10581          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10582         (Src0 == Src1 || Src0 == Src2))
10583       break;
10584 
10585     MVT VT = Src0.getValueType().getSimpleVT();
10586     const TargetRegisterClass *RC =
10587         getRegClassFor(VT, Src0.getNode()->isDivergent());
10588 
10589     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10590     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10591 
10592     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10593                                       UndefReg, Src0, SDValue());
10594 
10595     // src0 must be the same register as src1 or src2, even if the value is
10596     // undefined, so make sure we don't violate this constraint.
10597     if (Src0.isMachineOpcode() &&
10598         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10599       if (Src1.isMachineOpcode() &&
10600           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10601         Src0 = Src1;
10602       else if (Src2.isMachineOpcode() &&
10603                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10604         Src0 = Src2;
10605       else {
10606         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10607         Src0 = UndefReg;
10608         Src1 = UndefReg;
10609       }
10610     } else
10611       break;
10612 
10613     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10614     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10615       Ops.push_back(Node->getOperand(I));
10616 
10617     Ops.push_back(ImpDef.getValue(1));
10618     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10619   }
10620   default:
10621     break;
10622   }
10623 
10624   return Node;
10625 }
10626 
10627 /// Assign the register class depending on the number of
10628 /// bits set in the writemask
10629 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10630                                                      SDNode *Node) const {
10631   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10632 
10633   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10634 
10635   if (TII->isVOP3(MI.getOpcode())) {
10636     // Make sure constant bus requirements are respected.
10637     TII->legalizeOperandsVOP3(MRI, MI);
10638 
10639     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10640     // This saves a chain-copy of registers and better ballance register
10641     // use between vgpr and agpr as agpr tuples tend to be big.
10642     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10643       unsigned Opc = MI.getOpcode();
10644       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10645       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10646                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10647         if (I == -1)
10648           break;
10649         MachineOperand &Op = MI.getOperand(I);
10650         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10651              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10652             !Register::isVirtualRegister(Op.getReg()) ||
10653             !TRI->isAGPR(MRI, Op.getReg()))
10654           continue;
10655         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10656         if (!Src || !Src->isCopy() ||
10657             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10658           continue;
10659         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10660         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10661         // All uses of agpr64 and agpr32 can also accept vgpr except for
10662         // v_accvgpr_read, but we do not produce agpr reads during selection,
10663         // so no use checks are needed.
10664         MRI.setRegClass(Op.getReg(), NewRC);
10665       }
10666     }
10667 
10668     return;
10669   }
10670 
10671   // Replace unused atomics with the no return version.
10672   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10673   if (NoRetAtomicOp != -1) {
10674     if (!Node->hasAnyUseOfValue(0)) {
10675       MI.setDesc(TII->get(NoRetAtomicOp));
10676       MI.RemoveOperand(0);
10677       return;
10678     }
10679 
10680     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10681     // instruction, because the return type of these instructions is a vec2 of
10682     // the memory type, so it can be tied to the input operand.
10683     // This means these instructions always have a use, so we need to add a
10684     // special case to check if the atomic has only one extract_subreg use,
10685     // which itself has no uses.
10686     if ((Node->hasNUsesOfValue(1, 0) &&
10687          Node->use_begin()->isMachineOpcode() &&
10688          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10689          !Node->use_begin()->hasAnyUseOfValue(0))) {
10690       Register Def = MI.getOperand(0).getReg();
10691 
10692       // Change this into a noret atomic.
10693       MI.setDesc(TII->get(NoRetAtomicOp));
10694       MI.RemoveOperand(0);
10695 
10696       // If we only remove the def operand from the atomic instruction, the
10697       // extract_subreg will be left with a use of a vreg without a def.
10698       // So we need to insert an implicit_def to avoid machine verifier
10699       // errors.
10700       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10701               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10702     }
10703     return;
10704   }
10705 }
10706 
10707 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10708                               uint64_t Val) {
10709   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10710   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10711 }
10712 
10713 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10714                                                 const SDLoc &DL,
10715                                                 SDValue Ptr) const {
10716   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10717 
10718   // Build the half of the subregister with the constants before building the
10719   // full 128-bit register. If we are building multiple resource descriptors,
10720   // this will allow CSEing of the 2-component register.
10721   const SDValue Ops0[] = {
10722     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10723     buildSMovImm32(DAG, DL, 0),
10724     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10725     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10726     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10727   };
10728 
10729   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10730                                                 MVT::v2i32, Ops0), 0);
10731 
10732   // Combine the constants and the pointer.
10733   const SDValue Ops1[] = {
10734     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10735     Ptr,
10736     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10737     SubRegHi,
10738     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10739   };
10740 
10741   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10742 }
10743 
10744 /// Return a resource descriptor with the 'Add TID' bit enabled
10745 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10746 ///        of the resource descriptor) to create an offset, which is added to
10747 ///        the resource pointer.
10748 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10749                                            SDValue Ptr, uint32_t RsrcDword1,
10750                                            uint64_t RsrcDword2And3) const {
10751   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10752   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10753   if (RsrcDword1) {
10754     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10755                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10756                     0);
10757   }
10758 
10759   SDValue DataLo = buildSMovImm32(DAG, DL,
10760                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10761   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10762 
10763   const SDValue Ops[] = {
10764     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10765     PtrLo,
10766     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10767     PtrHi,
10768     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10769     DataLo,
10770     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10771     DataHi,
10772     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10773   };
10774 
10775   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10776 }
10777 
10778 //===----------------------------------------------------------------------===//
10779 //                         SI Inline Assembly Support
10780 //===----------------------------------------------------------------------===//
10781 
10782 std::pair<unsigned, const TargetRegisterClass *>
10783 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10784                                                StringRef Constraint,
10785                                                MVT VT) const {
10786   const TargetRegisterClass *RC = nullptr;
10787   if (Constraint.size() == 1) {
10788     const unsigned BitWidth = VT.getSizeInBits();
10789     switch (Constraint[0]) {
10790     default:
10791       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10792     case 's':
10793     case 'r':
10794       switch (BitWidth) {
10795       case 16:
10796         RC = &AMDGPU::SReg_32RegClass;
10797         break;
10798       case 64:
10799         RC = &AMDGPU::SGPR_64RegClass;
10800         break;
10801       default:
10802         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
10803         if (!RC)
10804           return std::make_pair(0U, nullptr);
10805         break;
10806       }
10807       break;
10808     case 'v':
10809       switch (BitWidth) {
10810       case 16:
10811         RC = &AMDGPU::VGPR_32RegClass;
10812         break;
10813       default:
10814         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
10815         if (!RC)
10816           return std::make_pair(0U, nullptr);
10817         break;
10818       }
10819       break;
10820     case 'a':
10821       if (!Subtarget->hasMAIInsts())
10822         break;
10823       switch (BitWidth) {
10824       case 16:
10825         RC = &AMDGPU::AGPR_32RegClass;
10826         break;
10827       default:
10828         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
10829         if (!RC)
10830           return std::make_pair(0U, nullptr);
10831         break;
10832       }
10833       break;
10834     }
10835     // We actually support i128, i16 and f16 as inline parameters
10836     // even if they are not reported as legal
10837     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10838                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10839       return std::make_pair(0U, RC);
10840   }
10841 
10842   if (Constraint.size() > 1) {
10843     if (Constraint[1] == 'v') {
10844       RC = &AMDGPU::VGPR_32RegClass;
10845     } else if (Constraint[1] == 's') {
10846       RC = &AMDGPU::SGPR_32RegClass;
10847     } else if (Constraint[1] == 'a') {
10848       RC = &AMDGPU::AGPR_32RegClass;
10849     }
10850 
10851     if (RC) {
10852       uint32_t Idx;
10853       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10854       if (!Failed && Idx < RC->getNumRegs())
10855         return std::make_pair(RC->getRegister(Idx), RC);
10856     }
10857   }
10858 
10859   // FIXME: Returns VS_32 for physical SGPR constraints
10860   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10861 }
10862 
10863 SITargetLowering::ConstraintType
10864 SITargetLowering::getConstraintType(StringRef Constraint) const {
10865   if (Constraint.size() == 1) {
10866     switch (Constraint[0]) {
10867     default: break;
10868     case 's':
10869     case 'v':
10870     case 'a':
10871       return C_RegisterClass;
10872     }
10873   }
10874   return TargetLowering::getConstraintType(Constraint);
10875 }
10876 
10877 // Figure out which registers should be reserved for stack access. Only after
10878 // the function is legalized do we know all of the non-spill stack objects or if
10879 // calls are present.
10880 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10881   MachineRegisterInfo &MRI = MF.getRegInfo();
10882   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10883   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10884   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10885 
10886   if (Info->isEntryFunction()) {
10887     // Callable functions have fixed registers used for stack access.
10888     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10889   }
10890 
10891   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10892                              Info->getStackPtrOffsetReg()));
10893   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10894     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10895 
10896   // We need to worry about replacing the default register with itself in case
10897   // of MIR testcases missing the MFI.
10898   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10899     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10900 
10901   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10902     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10903 
10904   Info->limitOccupancy(MF);
10905 
10906   if (ST.isWave32() && !MF.empty()) {
10907     // Add VCC_HI def because many instructions marked as imp-use VCC where
10908     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10909     // having a use of undef.
10910 
10911     const SIInstrInfo *TII = ST.getInstrInfo();
10912     DebugLoc DL;
10913 
10914     MachineBasicBlock &MBB = MF.front();
10915     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10916     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10917 
10918     for (auto &MBB : MF) {
10919       for (auto &MI : MBB) {
10920         TII->fixImplicitOperands(MI);
10921       }
10922     }
10923   }
10924 
10925   TargetLoweringBase::finalizeLowering(MF);
10926 
10927   // Allocate a VGPR for future SGPR Spill if
10928   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
10929   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
10930   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
10931       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
10932     Info->reserveVGPRforSGPRSpills(MF);
10933 }
10934 
10935 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10936                                                      KnownBits &Known,
10937                                                      const APInt &DemandedElts,
10938                                                      const SelectionDAG &DAG,
10939                                                      unsigned Depth) const {
10940   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10941                                                 DAG, Depth);
10942 
10943   // Set the high bits to zero based on the maximum allowed scratch size per
10944   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10945   // calculation won't overflow, so assume the sign bit is never set.
10946   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10947 }
10948 
10949 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10950   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10951   const Align CacheLineAlign = Align(64);
10952 
10953   // Pre-GFX10 target did not benefit from loop alignment
10954   if (!ML || DisableLoopAlignment ||
10955       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10956       getSubtarget()->hasInstFwdPrefetchBug())
10957     return PrefAlign;
10958 
10959   // On GFX10 I$ is 4 x 64 bytes cache lines.
10960   // By default prefetcher keeps one cache line behind and reads two ahead.
10961   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10962   // behind and one ahead.
10963   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10964   // If loop fits 64 bytes it always spans no more than two cache lines and
10965   // does not need an alignment.
10966   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10967   // Else if loop is less or equal 192 bytes we need two lines behind.
10968 
10969   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10970   const MachineBasicBlock *Header = ML->getHeader();
10971   if (Header->getAlignment() != PrefAlign)
10972     return Header->getAlignment(); // Already processed.
10973 
10974   unsigned LoopSize = 0;
10975   for (const MachineBasicBlock *MBB : ML->blocks()) {
10976     // If inner loop block is aligned assume in average half of the alignment
10977     // size to be added as nops.
10978     if (MBB != Header)
10979       LoopSize += MBB->getAlignment().value() / 2;
10980 
10981     for (const MachineInstr &MI : *MBB) {
10982       LoopSize += TII->getInstSizeInBytes(MI);
10983       if (LoopSize > 192)
10984         return PrefAlign;
10985     }
10986   }
10987 
10988   if (LoopSize <= 64)
10989     return PrefAlign;
10990 
10991   if (LoopSize <= 128)
10992     return CacheLineAlign;
10993 
10994   // If any of parent loops is surrounded by prefetch instructions do not
10995   // insert new for inner loop, which would reset parent's settings.
10996   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10997     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10998       auto I = Exit->getFirstNonDebugInstr();
10999       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11000         return CacheLineAlign;
11001     }
11002   }
11003 
11004   MachineBasicBlock *Pre = ML->getLoopPreheader();
11005   MachineBasicBlock *Exit = ML->getExitBlock();
11006 
11007   if (Pre && Exit) {
11008     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11009             TII->get(AMDGPU::S_INST_PREFETCH))
11010       .addImm(1); // prefetch 2 lines behind PC
11011 
11012     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11013             TII->get(AMDGPU::S_INST_PREFETCH))
11014       .addImm(2); // prefetch 1 line behind PC
11015   }
11016 
11017   return CacheLineAlign;
11018 }
11019 
11020 LLVM_ATTRIBUTE_UNUSED
11021 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11022   assert(N->getOpcode() == ISD::CopyFromReg);
11023   do {
11024     // Follow the chain until we find an INLINEASM node.
11025     N = N->getOperand(0).getNode();
11026     if (N->getOpcode() == ISD::INLINEASM ||
11027         N->getOpcode() == ISD::INLINEASM_BR)
11028       return true;
11029   } while (N->getOpcode() == ISD::CopyFromReg);
11030   return false;
11031 }
11032 
11033 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11034   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11035 {
11036   switch (N->getOpcode()) {
11037     case ISD::CopyFromReg:
11038     {
11039       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11040       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11041       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11042       Register Reg = R->getReg();
11043 
11044       // FIXME: Why does this need to consider isLiveIn?
11045       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11046         return !TRI->isSGPRReg(MRI, Reg);
11047 
11048       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11049         return KDA->isDivergent(V);
11050 
11051       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11052       return !TRI->isSGPRReg(MRI, Reg);
11053     }
11054     break;
11055     case ISD::LOAD: {
11056       const LoadSDNode *L = cast<LoadSDNode>(N);
11057       unsigned AS = L->getAddressSpace();
11058       // A flat load may access private memory.
11059       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11060     } break;
11061     case ISD::CALLSEQ_END:
11062     return true;
11063     break;
11064     case ISD::INTRINSIC_WO_CHAIN:
11065     {
11066 
11067     }
11068       return AMDGPU::isIntrinsicSourceOfDivergence(
11069       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11070     case ISD::INTRINSIC_W_CHAIN:
11071       return AMDGPU::isIntrinsicSourceOfDivergence(
11072       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11073   }
11074   return false;
11075 }
11076 
11077 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11078                                                EVT VT) const {
11079   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11080   case MVT::f32:
11081     return hasFP32Denormals(DAG.getMachineFunction());
11082   case MVT::f64:
11083   case MVT::f16:
11084     return hasFP64FP16Denormals(DAG.getMachineFunction());
11085   default:
11086     return false;
11087   }
11088 }
11089 
11090 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11091                                                     const SelectionDAG &DAG,
11092                                                     bool SNaN,
11093                                                     unsigned Depth) const {
11094   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11095     const MachineFunction &MF = DAG.getMachineFunction();
11096     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11097 
11098     if (Info->getMode().DX10Clamp)
11099       return true; // Clamped to 0.
11100     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11101   }
11102 
11103   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11104                                                             SNaN, Depth);
11105 }
11106 
11107 TargetLowering::AtomicExpansionKind
11108 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11109   switch (RMW->getOperation()) {
11110   case AtomicRMWInst::FAdd: {
11111     Type *Ty = RMW->getType();
11112 
11113     // We don't have a way to support 16-bit atomics now, so just leave them
11114     // as-is.
11115     if (Ty->isHalfTy())
11116       return AtomicExpansionKind::None;
11117 
11118     if (!Ty->isFloatTy())
11119       return AtomicExpansionKind::CmpXChg;
11120 
11121     // TODO: Do have these for flat. Older targets also had them for buffers.
11122     unsigned AS = RMW->getPointerAddressSpace();
11123 
11124     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11125       return RMW->use_empty() ? AtomicExpansionKind::None :
11126                                 AtomicExpansionKind::CmpXChg;
11127     }
11128 
11129     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11130       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11131   }
11132   default:
11133     break;
11134   }
11135 
11136   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11137 }
11138 
11139 const TargetRegisterClass *
11140 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11141   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11142   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11143   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11144     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11145                                                : &AMDGPU::SReg_32RegClass;
11146   if (!TRI->isSGPRClass(RC) && !isDivergent)
11147     return TRI->getEquivalentSGPRClass(RC);
11148   else if (TRI->isSGPRClass(RC) && isDivergent)
11149     return TRI->getEquivalentVGPRClass(RC);
11150 
11151   return RC;
11152 }
11153 
11154 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11155 // uniform values (as produced by the mask results of control flow intrinsics)
11156 // used outside of divergent blocks. The phi users need to also be treated as
11157 // always uniform.
11158 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11159                       unsigned WaveSize) {
11160   // FIXME: We asssume we never cast the mask results of a control flow
11161   // intrinsic.
11162   // Early exit if the type won't be consistent as a compile time hack.
11163   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11164   if (!IT || IT->getBitWidth() != WaveSize)
11165     return false;
11166 
11167   if (!isa<Instruction>(V))
11168     return false;
11169   if (!Visited.insert(V).second)
11170     return false;
11171   bool Result = false;
11172   for (auto U : V->users()) {
11173     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11174       if (V == U->getOperand(1)) {
11175         switch (Intrinsic->getIntrinsicID()) {
11176         default:
11177           Result = false;
11178           break;
11179         case Intrinsic::amdgcn_if_break:
11180         case Intrinsic::amdgcn_if:
11181         case Intrinsic::amdgcn_else:
11182           Result = true;
11183           break;
11184         }
11185       }
11186       if (V == U->getOperand(0)) {
11187         switch (Intrinsic->getIntrinsicID()) {
11188         default:
11189           Result = false;
11190           break;
11191         case Intrinsic::amdgcn_end_cf:
11192         case Intrinsic::amdgcn_loop:
11193           Result = true;
11194           break;
11195         }
11196       }
11197     } else {
11198       Result = hasCFUser(U, Visited, WaveSize);
11199     }
11200     if (Result)
11201       break;
11202   }
11203   return Result;
11204 }
11205 
11206 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11207                                                const Value *V) const {
11208   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11209     if (CI->isInlineAsm()) {
11210       // FIXME: This cannot give a correct answer. This should only trigger in
11211       // the case where inline asm returns mixed SGPR and VGPR results, used
11212       // outside the defining block. We don't have a specific result to
11213       // consider, so this assumes if any value is SGPR, the overall register
11214       // also needs to be SGPR.
11215       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11216       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11217           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11218       for (auto &TC : TargetConstraints) {
11219         if (TC.Type == InlineAsm::isOutput) {
11220           ComputeConstraintToUse(TC, SDValue());
11221           unsigned AssignedReg;
11222           const TargetRegisterClass *RC;
11223           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11224               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11225           if (RC) {
11226             MachineRegisterInfo &MRI = MF.getRegInfo();
11227             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11228               return true;
11229             else if (SIRI->isSGPRClass(RC))
11230               return true;
11231           }
11232         }
11233       }
11234     }
11235   }
11236   SmallPtrSet<const Value *, 16> Visited;
11237   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11238 }
11239