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 bool hasFP32Denormals(const MachineFunction &MF) {
99   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
100   return Info->getMode().allFP32Denormals();
101 }
102 
103 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
104   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
105   return Info->getMode().allFP64FP16Denormals();
106 }
107 
108 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
109   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
110   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
111     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
112       return AMDGPU::SGPR0 + Reg;
113     }
114   }
115   llvm_unreachable("Cannot allocate sgpr");
116 }
117 
118 SITargetLowering::SITargetLowering(const TargetMachine &TM,
119                                    const GCNSubtarget &STI)
120     : AMDGPUTargetLowering(TM, STI),
121       Subtarget(&STI) {
122   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
123   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
124 
125   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
126   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
127 
128   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
129   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
130   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
131 
132   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
133   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
134 
135   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
136   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
137 
138   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
139   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
140 
141   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
142   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
143 
144   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
145   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
146 
147   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
148   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
149 
150   if (Subtarget->has16BitInsts()) {
151     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
152     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
153 
154     // Unless there are also VOP3P operations, not operations are really legal.
155     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
156     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
157     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
158     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
159   }
160 
161   if (Subtarget->hasMAIInsts()) {
162     addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
163     addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
164   }
165 
166   computeRegisterProperties(Subtarget->getRegisterInfo());
167 
168   // The boolean content concept here is too inflexible. Compares only ever
169   // really produce a 1-bit result. Any copy/extend from these will turn into a
170   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
171   // it's what most targets use.
172   setBooleanContents(ZeroOrOneBooleanContent);
173   setBooleanVectorContents(ZeroOrOneBooleanContent);
174 
175   // We need to custom lower vector stores from local memory
176   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
177   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
178   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
179   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
180   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
181   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
182   setOperationAction(ISD::LOAD, MVT::i1, Custom);
183   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
184 
185   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
186   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
187   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
188   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
189   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
190   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
191   setOperationAction(ISD::STORE, MVT::i1, Custom);
192   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
193 
194   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
195   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
196   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
197   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
198   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
199   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
200   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
201   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
202   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
203   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
204   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
205   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
206   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
207   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
208   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
209   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
210 
211   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
212   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
213 
214   setOperationAction(ISD::SELECT, MVT::i1, Promote);
215   setOperationAction(ISD::SELECT, MVT::i64, Custom);
216   setOperationAction(ISD::SELECT, MVT::f64, Promote);
217   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
218 
219   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
220   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
221   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
222   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
223   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
224 
225   setOperationAction(ISD::SETCC, MVT::i1, Promote);
226   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
227   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
228   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
229 
230   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
232 
233   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
234   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
235   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
236   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
237   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
241 
242   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
243   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
244   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
245   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
246   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
247   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
248 
249   setOperationAction(ISD::UADDO, MVT::i32, Legal);
250   setOperationAction(ISD::USUBO, MVT::i32, Legal);
251 
252   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
253   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
254 
255   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
256   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
257   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
258 
259 #if 0
260   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
261   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
262 #endif
263 
264   // We only support LOAD/STORE and vector manipulation ops for vectors
265   // with > 4 elements.
266   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
267                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
268                   MVT::v32i32, MVT::v32f32 }) {
269     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
270       switch (Op) {
271       case ISD::LOAD:
272       case ISD::STORE:
273       case ISD::BUILD_VECTOR:
274       case ISD::BITCAST:
275       case ISD::EXTRACT_VECTOR_ELT:
276       case ISD::INSERT_VECTOR_ELT:
277       case ISD::INSERT_SUBVECTOR:
278       case ISD::EXTRACT_SUBVECTOR:
279       case ISD::SCALAR_TO_VECTOR:
280         break;
281       case ISD::CONCAT_VECTORS:
282         setOperationAction(Op, VT, Custom);
283         break;
284       default:
285         setOperationAction(Op, VT, Expand);
286         break;
287       }
288     }
289   }
290 
291   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
292 
293   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
294   // is expanded to avoid having two separate loops in case the index is a VGPR.
295 
296   // Most operations are naturally 32-bit vector operations. We only support
297   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
298   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
299     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
300     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
301 
302     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
303     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
304 
305     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
306     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
307 
308     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
309     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
310   }
311 
312   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
313   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
314   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
315   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
316 
317   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
318   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
319 
320   // Avoid stack access for these.
321   // TODO: Generalize to more vector types.
322   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
323   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
324   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
325   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
326 
327   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
328   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
329   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
330   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
331   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
332 
333   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
334   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
335   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
336 
337   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
338   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
339   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
340   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
341 
342   // Deal with vec3 vector operations when widened to vec4.
343   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
344   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
345   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
346   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
347 
348   // Deal with vec5 vector operations when widened to vec8.
349   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
350   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
351   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
352   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
353 
354   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
355   // and output demarshalling
356   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
357   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
358 
359   // We can't return success/failure, only the old value,
360   // let LLVM add the comparison
361   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
362   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
363 
364   if (Subtarget->hasFlatAddressSpace()) {
365     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
366     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
367   }
368 
369   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
370 
371   // FIXME: This should be narrowed to i32, but that only happens if i64 is
372   // illegal.
373   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
374   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
375   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
376 
377   // On SI this is s_memtime and s_memrealtime on VI.
378   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
379   setOperationAction(ISD::TRAP, MVT::Other, Custom);
380   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
381 
382   if (Subtarget->has16BitInsts()) {
383     setOperationAction(ISD::FPOW, MVT::f16, Promote);
384     setOperationAction(ISD::FLOG, MVT::f16, Custom);
385     setOperationAction(ISD::FEXP, MVT::f16, Custom);
386     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
387   }
388 
389   // v_mad_f32 does not support denormals. We report it as unconditionally
390   // legal, and the context where it is formed will disallow it when fp32
391   // denormals are enabled.
392   setOperationAction(ISD::FMAD, MVT::f32, Legal);
393 
394   if (!Subtarget->hasBFI()) {
395     // fcopysign can be done in a single instruction with BFI.
396     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
397     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
398   }
399 
400   if (!Subtarget->hasBCNT(32))
401     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
402 
403   if (!Subtarget->hasBCNT(64))
404     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
405 
406   if (Subtarget->hasFFBH())
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
408 
409   if (Subtarget->hasFFBL())
410     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
411 
412   // We only really have 32-bit BFE instructions (and 16-bit on VI).
413   //
414   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
415   // effort to match them now. We want this to be false for i64 cases when the
416   // extraction isn't restricted to the upper or lower half. Ideally we would
417   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
418   // span the midpoint are probably relatively rare, so don't worry about them
419   // for now.
420   if (Subtarget->hasBFE())
421     setHasExtractBitsInsn(true);
422 
423   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
424   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
425   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
426   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
427 
428 
429   // These are really only legal for ieee_mode functions. We should be avoiding
430   // them for functions that don't have ieee_mode enabled, so just say they are
431   // legal.
432   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
433   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
434   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
435   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
436 
437 
438   if (Subtarget->haveRoundOpsF64()) {
439     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
440     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
441     setOperationAction(ISD::FRINT, MVT::f64, Legal);
442   } else {
443     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
444     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
445     setOperationAction(ISD::FRINT, MVT::f64, Custom);
446     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
447   }
448 
449   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
450 
451   setOperationAction(ISD::FSIN, MVT::f32, Custom);
452   setOperationAction(ISD::FCOS, MVT::f32, Custom);
453   setOperationAction(ISD::FDIV, MVT::f32, Custom);
454   setOperationAction(ISD::FDIV, MVT::f64, Custom);
455 
456   if (Subtarget->has16BitInsts()) {
457     setOperationAction(ISD::Constant, MVT::i16, Legal);
458 
459     setOperationAction(ISD::SMIN, MVT::i16, Legal);
460     setOperationAction(ISD::SMAX, MVT::i16, Legal);
461 
462     setOperationAction(ISD::UMIN, MVT::i16, Legal);
463     setOperationAction(ISD::UMAX, MVT::i16, Legal);
464 
465     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
466     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
467 
468     setOperationAction(ISD::ROTR, MVT::i16, Promote);
469     setOperationAction(ISD::ROTL, MVT::i16, Promote);
470 
471     setOperationAction(ISD::SDIV, MVT::i16, Promote);
472     setOperationAction(ISD::UDIV, MVT::i16, Promote);
473     setOperationAction(ISD::SREM, MVT::i16, Promote);
474     setOperationAction(ISD::UREM, MVT::i16, Promote);
475 
476     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
477 
478     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
479     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
480     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
482     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
483 
484     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
485 
486     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
487 
488     setOperationAction(ISD::LOAD, MVT::i16, Custom);
489 
490     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
491 
492     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
493     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
494     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
495     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
496 
497     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
498     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
499 
500     // F16 - Constant Actions.
501     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
502 
503     // F16 - Load/Store Actions.
504     setOperationAction(ISD::LOAD, MVT::f16, Promote);
505     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
506     setOperationAction(ISD::STORE, MVT::f16, Promote);
507     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
508 
509     // F16 - VOP1 Actions.
510     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
511     setOperationAction(ISD::FCOS, MVT::f16, Custom);
512     setOperationAction(ISD::FSIN, MVT::f16, Custom);
513 
514     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
515     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
516 
517     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
518     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
519     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
520     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
521     setOperationAction(ISD::FROUND, MVT::f16, Custom);
522 
523     // F16 - VOP2 Actions.
524     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
525     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
526 
527     setOperationAction(ISD::FDIV, MVT::f16, Custom);
528 
529     // F16 - VOP3 Actions.
530     setOperationAction(ISD::FMA, MVT::f16, Legal);
531     if (STI.hasMadF16())
532       setOperationAction(ISD::FMAD, MVT::f16, Legal);
533 
534     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
535       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
536         switch (Op) {
537         case ISD::LOAD:
538         case ISD::STORE:
539         case ISD::BUILD_VECTOR:
540         case ISD::BITCAST:
541         case ISD::EXTRACT_VECTOR_ELT:
542         case ISD::INSERT_VECTOR_ELT:
543         case ISD::INSERT_SUBVECTOR:
544         case ISD::EXTRACT_SUBVECTOR:
545         case ISD::SCALAR_TO_VECTOR:
546           break;
547         case ISD::CONCAT_VECTORS:
548           setOperationAction(Op, VT, Custom);
549           break;
550         default:
551           setOperationAction(Op, VT, Expand);
552           break;
553         }
554       }
555     }
556 
557     // v_perm_b32 can handle either of these.
558     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
559     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
560     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
561 
562     // XXX - Do these do anything? Vector constants turn into build_vector.
563     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
564     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
565 
566     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
567     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
568 
569     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
570     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
571     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
572     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
573 
574     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
575     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
576     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
577     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
578 
579     setOperationAction(ISD::AND, MVT::v2i16, Promote);
580     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
581     setOperationAction(ISD::OR, MVT::v2i16, Promote);
582     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
583     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
584     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
585 
586     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
587     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
588     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
589     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
590 
591     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
592     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
593     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
594     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
595 
596     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
597     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
598     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
599     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
600 
601     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
602     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
603     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
604 
605     if (!Subtarget->hasVOP3PInsts()) {
606       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
607       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
608     }
609 
610     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
611     // This isn't really legal, but this avoids the legalizer unrolling it (and
612     // allows matching fneg (fabs x) patterns)
613     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
614 
615     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
616     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
617     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
618     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
619 
620     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
621     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
622 
623     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
624     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
625   }
626 
627   if (Subtarget->hasVOP3PInsts()) {
628     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
629     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
630     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
631     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
632     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
633     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
634     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
635     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
636     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
637     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
638 
639     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
640     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
641     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
642 
643     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
644     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
645 
646     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
647 
648     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
649     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
650 
651     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
652     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
653 
654     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
655     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
656     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
657     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
658     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
659     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
660 
661     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
662     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
663     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
664     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
665 
666     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
667     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
668     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
669 
670     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
671     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
672 
673     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
674     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
675     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
676 
677     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
678     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
679     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
680   }
681 
682   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
683   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
684 
685   if (Subtarget->has16BitInsts()) {
686     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
687     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
688     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
689     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
690   } else {
691     // Legalization hack.
692     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
693     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
694 
695     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
696     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
697   }
698 
699   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
700     setOperationAction(ISD::SELECT, VT, Custom);
701   }
702 
703   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
704   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
705   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
706   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
707   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
708   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
709   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
710 
711   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
712   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
713   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
714   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
715   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
716   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
717   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
718   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
719   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
720 
721   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
722   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
723   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
724   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
725   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
726   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
727   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
728   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
729 
730   setTargetDAGCombine(ISD::ADD);
731   setTargetDAGCombine(ISD::ADDCARRY);
732   setTargetDAGCombine(ISD::SUB);
733   setTargetDAGCombine(ISD::SUBCARRY);
734   setTargetDAGCombine(ISD::FADD);
735   setTargetDAGCombine(ISD::FSUB);
736   setTargetDAGCombine(ISD::FMINNUM);
737   setTargetDAGCombine(ISD::FMAXNUM);
738   setTargetDAGCombine(ISD::FMINNUM_IEEE);
739   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
740   setTargetDAGCombine(ISD::FMA);
741   setTargetDAGCombine(ISD::SMIN);
742   setTargetDAGCombine(ISD::SMAX);
743   setTargetDAGCombine(ISD::UMIN);
744   setTargetDAGCombine(ISD::UMAX);
745   setTargetDAGCombine(ISD::SETCC);
746   setTargetDAGCombine(ISD::AND);
747   setTargetDAGCombine(ISD::OR);
748   setTargetDAGCombine(ISD::XOR);
749   setTargetDAGCombine(ISD::SINT_TO_FP);
750   setTargetDAGCombine(ISD::UINT_TO_FP);
751   setTargetDAGCombine(ISD::FCANONICALIZE);
752   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
753   setTargetDAGCombine(ISD::ZERO_EXTEND);
754   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
755   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
756   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
757 
758   // All memory operations. Some folding on the pointer operand is done to help
759   // matching the constant offsets in the addressing modes.
760   setTargetDAGCombine(ISD::LOAD);
761   setTargetDAGCombine(ISD::STORE);
762   setTargetDAGCombine(ISD::ATOMIC_LOAD);
763   setTargetDAGCombine(ISD::ATOMIC_STORE);
764   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
765   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
766   setTargetDAGCombine(ISD::ATOMIC_SWAP);
767   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
768   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
769   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
770   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
771   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
772   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
773   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
774   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
775   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
776   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
777   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
778 
779   setSchedulingPreference(Sched::RegPressure);
780 }
781 
782 const GCNSubtarget *SITargetLowering::getSubtarget() const {
783   return Subtarget;
784 }
785 
786 //===----------------------------------------------------------------------===//
787 // TargetLowering queries
788 //===----------------------------------------------------------------------===//
789 
790 // v_mad_mix* support a conversion from f16 to f32.
791 //
792 // There is only one special case when denormals are enabled we don't currently,
793 // where this is OK to use.
794 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
795                                        EVT DestVT, EVT SrcVT) const {
796   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
797           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
798     DestVT.getScalarType() == MVT::f32 &&
799     SrcVT.getScalarType() == MVT::f16 &&
800     // TODO: This probably only requires no input flushing?
801     !hasFP32Denormals(DAG.getMachineFunction());
802 }
803 
804 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
805   // SI has some legal vector types, but no legal vector operations. Say no
806   // shuffles are legal in order to prefer scalarizing some vector operations.
807   return false;
808 }
809 
810 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
811                                                     CallingConv::ID CC,
812                                                     EVT VT) const {
813   if (CC == CallingConv::AMDGPU_KERNEL)
814     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
815 
816   if (VT.isVector()) {
817     EVT ScalarVT = VT.getScalarType();
818     unsigned Size = ScalarVT.getSizeInBits();
819     if (Size == 32)
820       return ScalarVT.getSimpleVT();
821 
822     if (Size > 32)
823       return MVT::i32;
824 
825     if (Size == 16 && Subtarget->has16BitInsts())
826       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
827   } else if (VT.getSizeInBits() > 32)
828     return MVT::i32;
829 
830   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
831 }
832 
833 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
834                                                          CallingConv::ID CC,
835                                                          EVT VT) const {
836   if (CC == CallingConv::AMDGPU_KERNEL)
837     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
838 
839   if (VT.isVector()) {
840     unsigned NumElts = VT.getVectorNumElements();
841     EVT ScalarVT = VT.getScalarType();
842     unsigned Size = ScalarVT.getSizeInBits();
843 
844     if (Size == 32)
845       return NumElts;
846 
847     if (Size > 32)
848       return NumElts * ((Size + 31) / 32);
849 
850     if (Size == 16 && Subtarget->has16BitInsts())
851       return (NumElts + 1) / 2;
852   } else if (VT.getSizeInBits() > 32)
853     return (VT.getSizeInBits() + 31) / 32;
854 
855   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
856 }
857 
858 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
859   LLVMContext &Context, CallingConv::ID CC,
860   EVT VT, EVT &IntermediateVT,
861   unsigned &NumIntermediates, MVT &RegisterVT) const {
862   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
863     unsigned NumElts = VT.getVectorNumElements();
864     EVT ScalarVT = VT.getScalarType();
865     unsigned Size = ScalarVT.getSizeInBits();
866     if (Size == 32) {
867       RegisterVT = ScalarVT.getSimpleVT();
868       IntermediateVT = RegisterVT;
869       NumIntermediates = NumElts;
870       return NumIntermediates;
871     }
872 
873     if (Size > 32) {
874       RegisterVT = MVT::i32;
875       IntermediateVT = RegisterVT;
876       NumIntermediates = NumElts * ((Size + 31) / 32);
877       return NumIntermediates;
878     }
879 
880     // FIXME: We should fix the ABI to be the same on targets without 16-bit
881     // support, but unless we can properly handle 3-vectors, it will be still be
882     // inconsistent.
883     if (Size == 16 && Subtarget->has16BitInsts()) {
884       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
885       IntermediateVT = RegisterVT;
886       NumIntermediates = (NumElts + 1) / 2;
887       return NumIntermediates;
888     }
889   }
890 
891   return TargetLowering::getVectorTypeBreakdownForCallingConv(
892     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
893 }
894 
895 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
896   assert(DMaskLanes != 0);
897 
898   if (auto *VT = dyn_cast<VectorType>(Ty)) {
899     unsigned NumElts = std::min(DMaskLanes,
900                                 static_cast<unsigned>(VT->getNumElements()));
901     return EVT::getVectorVT(Ty->getContext(),
902                             EVT::getEVT(VT->getElementType()),
903                             NumElts);
904   }
905 
906   return EVT::getEVT(Ty);
907 }
908 
909 // Peek through TFE struct returns to only use the data size.
910 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
911   auto *ST = dyn_cast<StructType>(Ty);
912   if (!ST)
913     return memVTFromImageData(Ty, DMaskLanes);
914 
915   // Some intrinsics return an aggregate type - special case to work out the
916   // correct memVT.
917   //
918   // Only limited forms of aggregate type currently expected.
919   if (ST->getNumContainedTypes() != 2 ||
920       !ST->getContainedType(1)->isIntegerTy(32))
921     return EVT();
922   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
923 }
924 
925 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
926                                           const CallInst &CI,
927                                           MachineFunction &MF,
928                                           unsigned IntrID) const {
929   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
930           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
931     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
932                                                   (Intrinsic::ID)IntrID);
933     if (Attr.hasFnAttribute(Attribute::ReadNone))
934       return false;
935 
936     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
937 
938     if (RsrcIntr->IsImage) {
939       Info.ptrVal = MFI->getImagePSV(
940         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
941         CI.getArgOperand(RsrcIntr->RsrcArg));
942       Info.align.reset();
943     } else {
944       Info.ptrVal = MFI->getBufferPSV(
945         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
946         CI.getArgOperand(RsrcIntr->RsrcArg));
947     }
948 
949     Info.flags = MachineMemOperand::MODereferenceable;
950     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
951       unsigned DMaskLanes = 4;
952 
953       if (RsrcIntr->IsImage) {
954         const AMDGPU::ImageDimIntrinsicInfo *Intr
955           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
956         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
957           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
958 
959         if (!BaseOpcode->Gather4) {
960           // If this isn't a gather, we may have excess loaded elements in the
961           // IR type. Check the dmask for the real number of elements loaded.
962           unsigned DMask
963             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
964           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
965         }
966 
967         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
968       } else
969         Info.memVT = EVT::getEVT(CI.getType());
970 
971       // FIXME: What does alignment mean for an image?
972       Info.opc = ISD::INTRINSIC_W_CHAIN;
973       Info.flags |= MachineMemOperand::MOLoad;
974     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
975       Info.opc = ISD::INTRINSIC_VOID;
976 
977       Type *DataTy = CI.getArgOperand(0)->getType();
978       if (RsrcIntr->IsImage) {
979         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
980         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
981         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
982       } else
983         Info.memVT = EVT::getEVT(DataTy);
984 
985       Info.flags |= MachineMemOperand::MOStore;
986     } else {
987       // Atomic
988       Info.opc = ISD::INTRINSIC_W_CHAIN;
989       Info.memVT = MVT::getVT(CI.getType());
990       Info.flags = MachineMemOperand::MOLoad |
991                    MachineMemOperand::MOStore |
992                    MachineMemOperand::MODereferenceable;
993 
994       // XXX - Should this be volatile without known ordering?
995       Info.flags |= MachineMemOperand::MOVolatile;
996     }
997     return true;
998   }
999 
1000   switch (IntrID) {
1001   case Intrinsic::amdgcn_atomic_inc:
1002   case Intrinsic::amdgcn_atomic_dec:
1003   case Intrinsic::amdgcn_ds_ordered_add:
1004   case Intrinsic::amdgcn_ds_ordered_swap:
1005   case Intrinsic::amdgcn_ds_fadd:
1006   case Intrinsic::amdgcn_ds_fmin:
1007   case Intrinsic::amdgcn_ds_fmax: {
1008     Info.opc = ISD::INTRINSIC_W_CHAIN;
1009     Info.memVT = MVT::getVT(CI.getType());
1010     Info.ptrVal = CI.getOperand(0);
1011     Info.align.reset();
1012     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1013 
1014     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1015     if (!Vol->isZero())
1016       Info.flags |= MachineMemOperand::MOVolatile;
1017 
1018     return true;
1019   }
1020   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1021     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1022 
1023     Info.opc = ISD::INTRINSIC_VOID;
1024     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1025     Info.ptrVal = MFI->getBufferPSV(
1026       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1027       CI.getArgOperand(1));
1028     Info.align.reset();
1029     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1030 
1031     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1032     if (!Vol || !Vol->isZero())
1033       Info.flags |= MachineMemOperand::MOVolatile;
1034 
1035     return true;
1036   }
1037   case Intrinsic::amdgcn_global_atomic_fadd: {
1038     Info.opc = ISD::INTRINSIC_VOID;
1039     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1040                             ->getPointerElementType());
1041     Info.ptrVal = CI.getOperand(0);
1042     Info.align.reset();
1043     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1044 
1045     return true;
1046   }
1047   case Intrinsic::amdgcn_ds_append:
1048   case Intrinsic::amdgcn_ds_consume: {
1049     Info.opc = ISD::INTRINSIC_W_CHAIN;
1050     Info.memVT = MVT::getVT(CI.getType());
1051     Info.ptrVal = CI.getOperand(0);
1052     Info.align.reset();
1053     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1054 
1055     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1056     if (!Vol->isZero())
1057       Info.flags |= MachineMemOperand::MOVolatile;
1058 
1059     return true;
1060   }
1061   case Intrinsic::amdgcn_ds_gws_init:
1062   case Intrinsic::amdgcn_ds_gws_barrier:
1063   case Intrinsic::amdgcn_ds_gws_sema_v:
1064   case Intrinsic::amdgcn_ds_gws_sema_br:
1065   case Intrinsic::amdgcn_ds_gws_sema_p:
1066   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1067     Info.opc = ISD::INTRINSIC_VOID;
1068 
1069     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1070     Info.ptrVal =
1071         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1072 
1073     // This is an abstract access, but we need to specify a type and size.
1074     Info.memVT = MVT::i32;
1075     Info.size = 4;
1076     Info.align = Align(4);
1077 
1078     Info.flags = MachineMemOperand::MOStore;
1079     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1080       Info.flags = MachineMemOperand::MOLoad;
1081     return true;
1082   }
1083   default:
1084     return false;
1085   }
1086 }
1087 
1088 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1089                                             SmallVectorImpl<Value*> &Ops,
1090                                             Type *&AccessTy) const {
1091   switch (II->getIntrinsicID()) {
1092   case Intrinsic::amdgcn_atomic_inc:
1093   case Intrinsic::amdgcn_atomic_dec:
1094   case Intrinsic::amdgcn_ds_ordered_add:
1095   case Intrinsic::amdgcn_ds_ordered_swap:
1096   case Intrinsic::amdgcn_ds_fadd:
1097   case Intrinsic::amdgcn_ds_fmin:
1098   case Intrinsic::amdgcn_ds_fmax: {
1099     Value *Ptr = II->getArgOperand(0);
1100     AccessTy = II->getType();
1101     Ops.push_back(Ptr);
1102     return true;
1103   }
1104   default:
1105     return false;
1106   }
1107 }
1108 
1109 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1110   if (!Subtarget->hasFlatInstOffsets()) {
1111     // Flat instructions do not have offsets, and only have the register
1112     // address.
1113     return AM.BaseOffs == 0 && AM.Scale == 0;
1114   }
1115 
1116   return AM.Scale == 0 &&
1117          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1118                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1119                                   /*Signed=*/false));
1120 }
1121 
1122 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1123   if (Subtarget->hasFlatGlobalInsts())
1124     return AM.Scale == 0 &&
1125            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1126                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1127                                     /*Signed=*/true));
1128 
1129   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1130       // Assume the we will use FLAT for all global memory accesses
1131       // on VI.
1132       // FIXME: This assumption is currently wrong.  On VI we still use
1133       // MUBUF instructions for the r + i addressing mode.  As currently
1134       // implemented, the MUBUF instructions only work on buffer < 4GB.
1135       // It may be possible to support > 4GB buffers with MUBUF instructions,
1136       // by setting the stride value in the resource descriptor which would
1137       // increase the size limit to (stride * 4GB).  However, this is risky,
1138       // because it has never been validated.
1139     return isLegalFlatAddressingMode(AM);
1140   }
1141 
1142   return isLegalMUBUFAddressingMode(AM);
1143 }
1144 
1145 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1146   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1147   // additionally can do r + r + i with addr64. 32-bit has more addressing
1148   // mode options. Depending on the resource constant, it can also do
1149   // (i64 r0) + (i32 r1) * (i14 i).
1150   //
1151   // Private arrays end up using a scratch buffer most of the time, so also
1152   // assume those use MUBUF instructions. Scratch loads / stores are currently
1153   // implemented as mubuf instructions with offen bit set, so slightly
1154   // different than the normal addr64.
1155   if (!isUInt<12>(AM.BaseOffs))
1156     return false;
1157 
1158   // FIXME: Since we can split immediate into soffset and immediate offset,
1159   // would it make sense to allow any immediate?
1160 
1161   switch (AM.Scale) {
1162   case 0: // r + i or just i, depending on HasBaseReg.
1163     return true;
1164   case 1:
1165     return true; // We have r + r or r + i.
1166   case 2:
1167     if (AM.HasBaseReg) {
1168       // Reject 2 * r + r.
1169       return false;
1170     }
1171 
1172     // Allow 2 * r as r + r
1173     // Or  2 * r + i is allowed as r + r + i.
1174     return true;
1175   default: // Don't allow n * r
1176     return false;
1177   }
1178 }
1179 
1180 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1181                                              const AddrMode &AM, Type *Ty,
1182                                              unsigned AS, Instruction *I) const {
1183   // No global is ever allowed as a base.
1184   if (AM.BaseGV)
1185     return false;
1186 
1187   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1188     return isLegalGlobalAddressingMode(AM);
1189 
1190   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1191       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1192       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1193     // If the offset isn't a multiple of 4, it probably isn't going to be
1194     // correctly aligned.
1195     // FIXME: Can we get the real alignment here?
1196     if (AM.BaseOffs % 4 != 0)
1197       return isLegalMUBUFAddressingMode(AM);
1198 
1199     // There are no SMRD extloads, so if we have to do a small type access we
1200     // will use a MUBUF load.
1201     // FIXME?: We also need to do this if unaligned, but we don't know the
1202     // alignment here.
1203     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1204       return isLegalGlobalAddressingMode(AM);
1205 
1206     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1207       // SMRD instructions have an 8-bit, dword offset on SI.
1208       if (!isUInt<8>(AM.BaseOffs / 4))
1209         return false;
1210     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1211       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1212       // in 8-bits, it can use a smaller encoding.
1213       if (!isUInt<32>(AM.BaseOffs / 4))
1214         return false;
1215     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1216       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1217       if (!isUInt<20>(AM.BaseOffs))
1218         return false;
1219     } else
1220       llvm_unreachable("unhandled generation");
1221 
1222     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1223       return true;
1224 
1225     if (AM.Scale == 1 && AM.HasBaseReg)
1226       return true;
1227 
1228     return false;
1229 
1230   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1231     return isLegalMUBUFAddressingMode(AM);
1232   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1233              AS == AMDGPUAS::REGION_ADDRESS) {
1234     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1235     // field.
1236     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1237     // an 8-bit dword offset but we don't know the alignment here.
1238     if (!isUInt<16>(AM.BaseOffs))
1239       return false;
1240 
1241     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1242       return true;
1243 
1244     if (AM.Scale == 1 && AM.HasBaseReg)
1245       return true;
1246 
1247     return false;
1248   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1249              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1250     // For an unknown address space, this usually means that this is for some
1251     // reason being used for pure arithmetic, and not based on some addressing
1252     // computation. We don't have instructions that compute pointers with any
1253     // addressing modes, so treat them as having no offset like flat
1254     // instructions.
1255     return isLegalFlatAddressingMode(AM);
1256   } else {
1257     llvm_unreachable("unhandled address space");
1258   }
1259 }
1260 
1261 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1262                                         const SelectionDAG &DAG) const {
1263   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1264     return (MemVT.getSizeInBits() <= 4 * 32);
1265   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1266     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1267     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1268   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1269     return (MemVT.getSizeInBits() <= 2 * 32);
1270   }
1271   return true;
1272 }
1273 
1274 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1275     unsigned Size, unsigned AddrSpace, unsigned Align,
1276     MachineMemOperand::Flags Flags, bool *IsFast) const {
1277   if (IsFast)
1278     *IsFast = false;
1279 
1280   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1281       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1282     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1283     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1284     // with adjacent offsets.
1285     bool AlignedBy4 = (Align % 4 == 0);
1286     if (IsFast)
1287       *IsFast = AlignedBy4;
1288 
1289     return AlignedBy4;
1290   }
1291 
1292   // FIXME: We have to be conservative here and assume that flat operations
1293   // will access scratch.  If we had access to the IR function, then we
1294   // could determine if any private memory was used in the function.
1295   if (!Subtarget->hasUnalignedScratchAccess() &&
1296       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1297        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1298     bool AlignedBy4 = Align >= 4;
1299     if (IsFast)
1300       *IsFast = AlignedBy4;
1301 
1302     return AlignedBy4;
1303   }
1304 
1305   if (Subtarget->hasUnalignedBufferAccess()) {
1306     // If we have an uniform constant load, it still requires using a slow
1307     // buffer instruction if unaligned.
1308     if (IsFast) {
1309       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1310       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1311       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1312                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1313         Align >= 4 : Align != 2;
1314     }
1315 
1316     return true;
1317   }
1318 
1319   // Smaller than dword value must be aligned.
1320   if (Size < 32)
1321     return false;
1322 
1323   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1324   // byte-address are ignored, thus forcing Dword alignment.
1325   // This applies to private, global, and constant memory.
1326   if (IsFast)
1327     *IsFast = true;
1328 
1329   return Size >= 32 && Align >= 4;
1330 }
1331 
1332 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1333     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1334     bool *IsFast) const {
1335   if (IsFast)
1336     *IsFast = false;
1337 
1338   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1339   // which isn't a simple VT.
1340   // Until MVT is extended to handle this, simply check for the size and
1341   // rely on the condition below: allow accesses if the size is a multiple of 4.
1342   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1343                            VT.getStoreSize() > 16)) {
1344     return false;
1345   }
1346 
1347   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1348                                             Align, Flags, IsFast);
1349 }
1350 
1351 EVT SITargetLowering::getOptimalMemOpType(
1352     const MemOp &Op, const AttributeList &FuncAttributes) const {
1353   // FIXME: Should account for address space here.
1354 
1355   // The default fallback uses the private pointer size as a guess for a type to
1356   // use. Make sure we switch these to 64-bit accesses.
1357 
1358   if (Op.size() >= 16 &&
1359       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1360     return MVT::v4i32;
1361 
1362   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1363     return MVT::v2i32;
1364 
1365   // Use the default.
1366   return MVT::Other;
1367 }
1368 
1369 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1370                                            unsigned DestAS) const {
1371   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1372 }
1373 
1374 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1375   const MemSDNode *MemNode = cast<MemSDNode>(N);
1376   const Value *Ptr = MemNode->getMemOperand()->getValue();
1377   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1378   return I && I->getMetadata("amdgpu.noclobber");
1379 }
1380 
1381 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1382                                            unsigned DestAS) const {
1383   // Flat -> private/local is a simple truncate.
1384   // Flat -> global is no-op
1385   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1386     return true;
1387 
1388   return isNoopAddrSpaceCast(SrcAS, DestAS);
1389 }
1390 
1391 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1392   const MemSDNode *MemNode = cast<MemSDNode>(N);
1393 
1394   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1395 }
1396 
1397 TargetLoweringBase::LegalizeTypeAction
1398 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1399   int NumElts = VT.getVectorNumElements();
1400   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1401     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1402   return TargetLoweringBase::getPreferredVectorAction(VT);
1403 }
1404 
1405 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1406                                                          Type *Ty) const {
1407   // FIXME: Could be smarter if called for vector constants.
1408   return true;
1409 }
1410 
1411 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1412   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1413     switch (Op) {
1414     case ISD::LOAD:
1415     case ISD::STORE:
1416 
1417     // These operations are done with 32-bit instructions anyway.
1418     case ISD::AND:
1419     case ISD::OR:
1420     case ISD::XOR:
1421     case ISD::SELECT:
1422       // TODO: Extensions?
1423       return true;
1424     default:
1425       return false;
1426     }
1427   }
1428 
1429   // SimplifySetCC uses this function to determine whether or not it should
1430   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1431   if (VT == MVT::i1 && Op == ISD::SETCC)
1432     return false;
1433 
1434   return TargetLowering::isTypeDesirableForOp(Op, VT);
1435 }
1436 
1437 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1438                                                    const SDLoc &SL,
1439                                                    SDValue Chain,
1440                                                    uint64_t Offset) const {
1441   const DataLayout &DL = DAG.getDataLayout();
1442   MachineFunction &MF = DAG.getMachineFunction();
1443   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1444 
1445   const ArgDescriptor *InputPtrReg;
1446   const TargetRegisterClass *RC;
1447 
1448   std::tie(InputPtrReg, RC)
1449     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1450 
1451   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1452   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1453   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1454     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1455 
1456   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1457 }
1458 
1459 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1460                                             const SDLoc &SL) const {
1461   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1462                                                FIRST_IMPLICIT);
1463   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1464 }
1465 
1466 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1467                                          const SDLoc &SL, SDValue Val,
1468                                          bool Signed,
1469                                          const ISD::InputArg *Arg) const {
1470   // First, if it is a widened vector, narrow it.
1471   if (VT.isVector() &&
1472       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1473     EVT NarrowedVT =
1474         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1475                          VT.getVectorNumElements());
1476     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1477                       DAG.getConstant(0, SL, MVT::i32));
1478   }
1479 
1480   // Then convert the vector elements or scalar value.
1481   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1482       VT.bitsLT(MemVT)) {
1483     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1484     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1485   }
1486 
1487   if (MemVT.isFloatingPoint())
1488     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1489   else if (Signed)
1490     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1491   else
1492     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1493 
1494   return Val;
1495 }
1496 
1497 SDValue SITargetLowering::lowerKernargMemParameter(
1498   SelectionDAG &DAG, EVT VT, EVT MemVT,
1499   const SDLoc &SL, SDValue Chain,
1500   uint64_t Offset, unsigned Align, bool Signed,
1501   const ISD::InputArg *Arg) const {
1502   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1503 
1504   // Try to avoid using an extload by loading earlier than the argument address,
1505   // and extracting the relevant bits. The load should hopefully be merged with
1506   // the previous argument.
1507   if (MemVT.getStoreSize() < 4 && Align < 4) {
1508     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1509     int64_t AlignDownOffset = alignDown(Offset, 4);
1510     int64_t OffsetDiff = Offset - AlignDownOffset;
1511 
1512     EVT IntVT = MemVT.changeTypeToInteger();
1513 
1514     // TODO: If we passed in the base kernel offset we could have a better
1515     // alignment than 4, but we don't really need it.
1516     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1517     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1518                                MachineMemOperand::MODereferenceable |
1519                                MachineMemOperand::MOInvariant);
1520 
1521     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1522     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1523 
1524     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1525     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1526     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1527 
1528 
1529     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1530   }
1531 
1532   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1533   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1534                              MachineMemOperand::MODereferenceable |
1535                              MachineMemOperand::MOInvariant);
1536 
1537   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1538   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1539 }
1540 
1541 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1542                                               const SDLoc &SL, SDValue Chain,
1543                                               const ISD::InputArg &Arg) const {
1544   MachineFunction &MF = DAG.getMachineFunction();
1545   MachineFrameInfo &MFI = MF.getFrameInfo();
1546 
1547   if (Arg.Flags.isByVal()) {
1548     unsigned Size = Arg.Flags.getByValSize();
1549     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1550     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1551   }
1552 
1553   unsigned ArgOffset = VA.getLocMemOffset();
1554   unsigned ArgSize = VA.getValVT().getStoreSize();
1555 
1556   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1557 
1558   // Create load nodes to retrieve arguments from the stack.
1559   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1560   SDValue ArgValue;
1561 
1562   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1563   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1564   MVT MemVT = VA.getValVT();
1565 
1566   switch (VA.getLocInfo()) {
1567   default:
1568     break;
1569   case CCValAssign::BCvt:
1570     MemVT = VA.getLocVT();
1571     break;
1572   case CCValAssign::SExt:
1573     ExtType = ISD::SEXTLOAD;
1574     break;
1575   case CCValAssign::ZExt:
1576     ExtType = ISD::ZEXTLOAD;
1577     break;
1578   case CCValAssign::AExt:
1579     ExtType = ISD::EXTLOAD;
1580     break;
1581   }
1582 
1583   ArgValue = DAG.getExtLoad(
1584     ExtType, SL, VA.getLocVT(), Chain, FIN,
1585     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1586     MemVT);
1587   return ArgValue;
1588 }
1589 
1590 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1591   const SIMachineFunctionInfo &MFI,
1592   EVT VT,
1593   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1594   const ArgDescriptor *Reg;
1595   const TargetRegisterClass *RC;
1596 
1597   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1598   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1599 }
1600 
1601 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1602                                    CallingConv::ID CallConv,
1603                                    ArrayRef<ISD::InputArg> Ins,
1604                                    BitVector &Skipped,
1605                                    FunctionType *FType,
1606                                    SIMachineFunctionInfo *Info) {
1607   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1608     const ISD::InputArg *Arg = &Ins[I];
1609 
1610     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1611            "vector type argument should have been split");
1612 
1613     // First check if it's a PS input addr.
1614     if (CallConv == CallingConv::AMDGPU_PS &&
1615         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1616       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1617 
1618       // Inconveniently only the first part of the split is marked as isSplit,
1619       // so skip to the end. We only want to increment PSInputNum once for the
1620       // entire split argument.
1621       if (Arg->Flags.isSplit()) {
1622         while (!Arg->Flags.isSplitEnd()) {
1623           assert((!Arg->VT.isVector() ||
1624                   Arg->VT.getScalarSizeInBits() == 16) &&
1625                  "unexpected vector split in ps argument type");
1626           if (!SkipArg)
1627             Splits.push_back(*Arg);
1628           Arg = &Ins[++I];
1629         }
1630       }
1631 
1632       if (SkipArg) {
1633         // We can safely skip PS inputs.
1634         Skipped.set(Arg->getOrigArgIndex());
1635         ++PSInputNum;
1636         continue;
1637       }
1638 
1639       Info->markPSInputAllocated(PSInputNum);
1640       if (Arg->Used)
1641         Info->markPSInputEnabled(PSInputNum);
1642 
1643       ++PSInputNum;
1644     }
1645 
1646     Splits.push_back(*Arg);
1647   }
1648 }
1649 
1650 // Allocate special inputs passed in VGPRs.
1651 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1652                                                       MachineFunction &MF,
1653                                                       const SIRegisterInfo &TRI,
1654                                                       SIMachineFunctionInfo &Info) const {
1655   const LLT S32 = LLT::scalar(32);
1656   MachineRegisterInfo &MRI = MF.getRegInfo();
1657 
1658   if (Info.hasWorkItemIDX()) {
1659     Register Reg = AMDGPU::VGPR0;
1660     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1661 
1662     CCInfo.AllocateReg(Reg);
1663     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1664   }
1665 
1666   if (Info.hasWorkItemIDY()) {
1667     Register Reg = AMDGPU::VGPR1;
1668     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1669 
1670     CCInfo.AllocateReg(Reg);
1671     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1672   }
1673 
1674   if (Info.hasWorkItemIDZ()) {
1675     Register Reg = AMDGPU::VGPR2;
1676     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1677 
1678     CCInfo.AllocateReg(Reg);
1679     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1680   }
1681 }
1682 
1683 // Try to allocate a VGPR at the end of the argument list, or if no argument
1684 // VGPRs are left allocating a stack slot.
1685 // If \p Mask is is given it indicates bitfield position in the register.
1686 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1687 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1688                                          ArgDescriptor Arg = ArgDescriptor()) {
1689   if (Arg.isSet())
1690     return ArgDescriptor::createArg(Arg, Mask);
1691 
1692   ArrayRef<MCPhysReg> ArgVGPRs
1693     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1694   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1695   if (RegIdx == ArgVGPRs.size()) {
1696     // Spill to stack required.
1697     int64_t Offset = CCInfo.AllocateStack(4, 4);
1698 
1699     return ArgDescriptor::createStack(Offset, Mask);
1700   }
1701 
1702   unsigned Reg = ArgVGPRs[RegIdx];
1703   Reg = CCInfo.AllocateReg(Reg);
1704   assert(Reg != AMDGPU::NoRegister);
1705 
1706   MachineFunction &MF = CCInfo.getMachineFunction();
1707   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1708   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1709   return ArgDescriptor::createRegister(Reg, Mask);
1710 }
1711 
1712 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1713                                              const TargetRegisterClass *RC,
1714                                              unsigned NumArgRegs) {
1715   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1716   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1717   if (RegIdx == ArgSGPRs.size())
1718     report_fatal_error("ran out of SGPRs for arguments");
1719 
1720   unsigned Reg = ArgSGPRs[RegIdx];
1721   Reg = CCInfo.AllocateReg(Reg);
1722   assert(Reg != AMDGPU::NoRegister);
1723 
1724   MachineFunction &MF = CCInfo.getMachineFunction();
1725   MF.addLiveIn(Reg, RC);
1726   return ArgDescriptor::createRegister(Reg);
1727 }
1728 
1729 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1730   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1731 }
1732 
1733 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1734   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1735 }
1736 
1737 /// Allocate implicit function VGPR arguments at the end of allocated user
1738 /// arguments.
1739 void SITargetLowering::allocateSpecialInputVGPRs(
1740   CCState &CCInfo, MachineFunction &MF,
1741   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1742   const unsigned Mask = 0x3ff;
1743   ArgDescriptor Arg;
1744 
1745   if (Info.hasWorkItemIDX()) {
1746     Arg = allocateVGPR32Input(CCInfo, Mask);
1747     Info.setWorkItemIDX(Arg);
1748   }
1749 
1750   if (Info.hasWorkItemIDY()) {
1751     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1752     Info.setWorkItemIDY(Arg);
1753   }
1754 
1755   if (Info.hasWorkItemIDZ())
1756     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1757 }
1758 
1759 /// Allocate implicit function VGPR arguments in fixed registers.
1760 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1761   CCState &CCInfo, MachineFunction &MF,
1762   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1763   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1764   if (!Reg)
1765     report_fatal_error("failed to allocated VGPR for implicit arguments");
1766 
1767   const unsigned Mask = 0x3ff;
1768   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1769   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1770   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1771 }
1772 
1773 void SITargetLowering::allocateSpecialInputSGPRs(
1774   CCState &CCInfo,
1775   MachineFunction &MF,
1776   const SIRegisterInfo &TRI,
1777   SIMachineFunctionInfo &Info) const {
1778   auto &ArgInfo = Info.getArgInfo();
1779 
1780   // TODO: Unify handling with private memory pointers.
1781 
1782   if (Info.hasDispatchPtr())
1783     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1784 
1785   if (Info.hasQueuePtr())
1786     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1787 
1788   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1789   // constant offset from the kernarg segment.
1790   if (Info.hasImplicitArgPtr())
1791     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1792 
1793   if (Info.hasDispatchID())
1794     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1795 
1796   // flat_scratch_init is not applicable for non-kernel functions.
1797 
1798   if (Info.hasWorkGroupIDX())
1799     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1800 
1801   if (Info.hasWorkGroupIDY())
1802     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1803 
1804   if (Info.hasWorkGroupIDZ())
1805     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1806 }
1807 
1808 // Allocate special inputs passed in user SGPRs.
1809 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1810                                             MachineFunction &MF,
1811                                             const SIRegisterInfo &TRI,
1812                                             SIMachineFunctionInfo &Info) const {
1813   if (Info.hasImplicitBufferPtr()) {
1814     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1815     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1816     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1817   }
1818 
1819   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1820   if (Info.hasPrivateSegmentBuffer()) {
1821     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1822     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1823     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1824   }
1825 
1826   if (Info.hasDispatchPtr()) {
1827     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1828     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1829     CCInfo.AllocateReg(DispatchPtrReg);
1830   }
1831 
1832   if (Info.hasQueuePtr()) {
1833     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1834     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1835     CCInfo.AllocateReg(QueuePtrReg);
1836   }
1837 
1838   if (Info.hasKernargSegmentPtr()) {
1839     MachineRegisterInfo &MRI = MF.getRegInfo();
1840     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1841     CCInfo.AllocateReg(InputPtrReg);
1842 
1843     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1844     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1845   }
1846 
1847   if (Info.hasDispatchID()) {
1848     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1849     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1850     CCInfo.AllocateReg(DispatchIDReg);
1851   }
1852 
1853   if (Info.hasFlatScratchInit()) {
1854     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1855     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1856     CCInfo.AllocateReg(FlatScratchInitReg);
1857   }
1858 
1859   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1860   // these from the dispatch pointer.
1861 }
1862 
1863 // Allocate special input registers that are initialized per-wave.
1864 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1865                                            MachineFunction &MF,
1866                                            SIMachineFunctionInfo &Info,
1867                                            CallingConv::ID CallConv,
1868                                            bool IsShader) const {
1869   if (Info.hasWorkGroupIDX()) {
1870     unsigned Reg = Info.addWorkGroupIDX();
1871     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1872     CCInfo.AllocateReg(Reg);
1873   }
1874 
1875   if (Info.hasWorkGroupIDY()) {
1876     unsigned Reg = Info.addWorkGroupIDY();
1877     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1878     CCInfo.AllocateReg(Reg);
1879   }
1880 
1881   if (Info.hasWorkGroupIDZ()) {
1882     unsigned Reg = Info.addWorkGroupIDZ();
1883     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1884     CCInfo.AllocateReg(Reg);
1885   }
1886 
1887   if (Info.hasWorkGroupInfo()) {
1888     unsigned Reg = Info.addWorkGroupInfo();
1889     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1890     CCInfo.AllocateReg(Reg);
1891   }
1892 
1893   if (Info.hasPrivateSegmentWaveByteOffset()) {
1894     // Scratch wave offset passed in system SGPR.
1895     unsigned PrivateSegmentWaveByteOffsetReg;
1896 
1897     if (IsShader) {
1898       PrivateSegmentWaveByteOffsetReg =
1899         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1900 
1901       // This is true if the scratch wave byte offset doesn't have a fixed
1902       // location.
1903       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1904         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1905         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1906       }
1907     } else
1908       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1909 
1910     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1911     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1912   }
1913 }
1914 
1915 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1916                                      MachineFunction &MF,
1917                                      const SIRegisterInfo &TRI,
1918                                      SIMachineFunctionInfo &Info) {
1919   // Now that we've figured out where the scratch register inputs are, see if
1920   // should reserve the arguments and use them directly.
1921   MachineFrameInfo &MFI = MF.getFrameInfo();
1922   bool HasStackObjects = MFI.hasStackObjects();
1923   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1924 
1925   // Record that we know we have non-spill stack objects so we don't need to
1926   // check all stack objects later.
1927   if (HasStackObjects)
1928     Info.setHasNonSpillStackObjects(true);
1929 
1930   // Everything live out of a block is spilled with fast regalloc, so it's
1931   // almost certain that spilling will be required.
1932   if (TM.getOptLevel() == CodeGenOpt::None)
1933     HasStackObjects = true;
1934 
1935   // For now assume stack access is needed in any callee functions, so we need
1936   // the scratch registers to pass in.
1937   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1938 
1939   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1940     // If we have stack objects, we unquestionably need the private buffer
1941     // resource. For the Code Object V2 ABI, this will be the first 4 user
1942     // SGPR inputs. We can reserve those and use them directly.
1943 
1944     Register PrivateSegmentBufferReg =
1945         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1946     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1947   } else {
1948     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1949     // We tentatively reserve the last registers (skipping the last registers
1950     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1951     // we'll replace these with the ones immediately after those which were
1952     // really allocated. In the prologue copies will be inserted from the
1953     // argument to these reserved registers.
1954 
1955     // Without HSA, relocations are used for the scratch pointer and the
1956     // buffer resource setup is always inserted in the prologue. Scratch wave
1957     // offset is still in an input SGPR.
1958     Info.setScratchRSrcReg(ReservedBufferReg);
1959   }
1960 
1961   MachineRegisterInfo &MRI = MF.getRegInfo();
1962 
1963   // For entry functions we have to set up the stack pointer if we use it,
1964   // whereas non-entry functions get this "for free". This means there is no
1965   // intrinsic advantage to using S32 over S34 in cases where we do not have
1966   // calls but do need a frame pointer (i.e. if we are requested to have one
1967   // because frame pointer elimination is disabled). To keep things simple we
1968   // only ever use S32 as the call ABI stack pointer, and so using it does not
1969   // imply we need a separate frame pointer.
1970   //
1971   // Try to use s32 as the SP, but move it if it would interfere with input
1972   // arguments. This won't work with calls though.
1973   //
1974   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1975   // registers.
1976   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1977     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1978   } else {
1979     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1980 
1981     if (MFI.hasCalls())
1982       report_fatal_error("call in graphics shader with too many input SGPRs");
1983 
1984     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1985       if (!MRI.isLiveIn(Reg)) {
1986         Info.setStackPtrOffsetReg(Reg);
1987         break;
1988       }
1989     }
1990 
1991     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1992       report_fatal_error("failed to find register for SP");
1993   }
1994 
1995   // hasFP should be accurate for entry functions even before the frame is
1996   // finalized, because it does not rely on the known stack size, only
1997   // properties like whether variable sized objects are present.
1998   if (ST.getFrameLowering()->hasFP(MF)) {
1999     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2000   }
2001 }
2002 
2003 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2004   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2005   return !Info->isEntryFunction();
2006 }
2007 
2008 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2009 
2010 }
2011 
2012 void SITargetLowering::insertCopiesSplitCSR(
2013   MachineBasicBlock *Entry,
2014   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2015   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2016 
2017   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2018   if (!IStart)
2019     return;
2020 
2021   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2022   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2023   MachineBasicBlock::iterator MBBI = Entry->begin();
2024   for (const MCPhysReg *I = IStart; *I; ++I) {
2025     const TargetRegisterClass *RC = nullptr;
2026     if (AMDGPU::SReg_64RegClass.contains(*I))
2027       RC = &AMDGPU::SGPR_64RegClass;
2028     else if (AMDGPU::SReg_32RegClass.contains(*I))
2029       RC = &AMDGPU::SGPR_32RegClass;
2030     else
2031       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2032 
2033     Register NewVR = MRI->createVirtualRegister(RC);
2034     // Create copy from CSR to a virtual register.
2035     Entry->addLiveIn(*I);
2036     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2037       .addReg(*I);
2038 
2039     // Insert the copy-back instructions right before the terminator.
2040     for (auto *Exit : Exits)
2041       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2042               TII->get(TargetOpcode::COPY), *I)
2043         .addReg(NewVR);
2044   }
2045 }
2046 
2047 SDValue SITargetLowering::LowerFormalArguments(
2048     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2049     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2050     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2051   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2052 
2053   MachineFunction &MF = DAG.getMachineFunction();
2054   const Function &Fn = MF.getFunction();
2055   FunctionType *FType = MF.getFunction().getFunctionType();
2056   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2057 
2058   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2059     DiagnosticInfoUnsupported NoGraphicsHSA(
2060         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2061     DAG.getContext()->diagnose(NoGraphicsHSA);
2062     return DAG.getEntryNode();
2063   }
2064 
2065   SmallVector<ISD::InputArg, 16> Splits;
2066   SmallVector<CCValAssign, 16> ArgLocs;
2067   BitVector Skipped(Ins.size());
2068   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2069                  *DAG.getContext());
2070 
2071   bool IsShader = AMDGPU::isShader(CallConv);
2072   bool IsKernel = AMDGPU::isKernel(CallConv);
2073   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2074 
2075   if (IsShader) {
2076     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2077 
2078     // At least one interpolation mode must be enabled or else the GPU will
2079     // hang.
2080     //
2081     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2082     // set PSInputAddr, the user wants to enable some bits after the compilation
2083     // based on run-time states. Since we can't know what the final PSInputEna
2084     // will look like, so we shouldn't do anything here and the user should take
2085     // responsibility for the correct programming.
2086     //
2087     // Otherwise, the following restrictions apply:
2088     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2089     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2090     //   enabled too.
2091     if (CallConv == CallingConv::AMDGPU_PS) {
2092       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2093            ((Info->getPSInputAddr() & 0xF) == 0 &&
2094             Info->isPSInputAllocated(11))) {
2095         CCInfo.AllocateReg(AMDGPU::VGPR0);
2096         CCInfo.AllocateReg(AMDGPU::VGPR1);
2097         Info->markPSInputAllocated(0);
2098         Info->markPSInputEnabled(0);
2099       }
2100       if (Subtarget->isAmdPalOS()) {
2101         // For isAmdPalOS, the user does not enable some bits after compilation
2102         // based on run-time states; the register values being generated here are
2103         // the final ones set in hardware. Therefore we need to apply the
2104         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2105         // a bit is set in PSInputAddr but not PSInputEnable is where the
2106         // frontend set up an input arg for a particular interpolation mode, but
2107         // nothing uses that input arg. Really we should have an earlier pass
2108         // that removes such an arg.)
2109         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2110         if ((PsInputBits & 0x7F) == 0 ||
2111             ((PsInputBits & 0xF) == 0 &&
2112              (PsInputBits >> 11 & 1)))
2113           Info->markPSInputEnabled(
2114               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2115       }
2116     }
2117 
2118     assert(!Info->hasDispatchPtr() &&
2119            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2120            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2121            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2122            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2123            !Info->hasWorkItemIDZ());
2124   } else if (IsKernel) {
2125     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2126   } else {
2127     Splits.append(Ins.begin(), Ins.end());
2128   }
2129 
2130   if (IsEntryFunc) {
2131     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2132     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2133   } else {
2134     // For the fixed ABI, pass workitem IDs in the last argument register.
2135     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2136       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2137   }
2138 
2139   if (IsKernel) {
2140     analyzeFormalArgumentsCompute(CCInfo, Ins);
2141   } else {
2142     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2143     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2144   }
2145 
2146   SmallVector<SDValue, 16> Chains;
2147 
2148   // FIXME: This is the minimum kernel argument alignment. We should improve
2149   // this to the maximum alignment of the arguments.
2150   //
2151   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2152   // kern arg offset.
2153   const unsigned KernelArgBaseAlign = 16;
2154 
2155    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2156     const ISD::InputArg &Arg = Ins[i];
2157     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2158       InVals.push_back(DAG.getUNDEF(Arg.VT));
2159       continue;
2160     }
2161 
2162     CCValAssign &VA = ArgLocs[ArgIdx++];
2163     MVT VT = VA.getLocVT();
2164 
2165     if (IsEntryFunc && VA.isMemLoc()) {
2166       VT = Ins[i].VT;
2167       EVT MemVT = VA.getLocVT();
2168 
2169       const uint64_t Offset = VA.getLocMemOffset();
2170       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2171 
2172       SDValue Arg = lowerKernargMemParameter(
2173         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2174       Chains.push_back(Arg.getValue(1));
2175 
2176       auto *ParamTy =
2177         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2178       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2179           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2180                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2181         // On SI local pointers are just offsets into LDS, so they are always
2182         // less than 16-bits.  On CI and newer they could potentially be
2183         // real pointers, so we can't guarantee their size.
2184         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2185                           DAG.getValueType(MVT::i16));
2186       }
2187 
2188       InVals.push_back(Arg);
2189       continue;
2190     } else if (!IsEntryFunc && VA.isMemLoc()) {
2191       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2192       InVals.push_back(Val);
2193       if (!Arg.Flags.isByVal())
2194         Chains.push_back(Val.getValue(1));
2195       continue;
2196     }
2197 
2198     assert(VA.isRegLoc() && "Parameter must be in a register!");
2199 
2200     Register Reg = VA.getLocReg();
2201     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2202     EVT ValVT = VA.getValVT();
2203 
2204     Reg = MF.addLiveIn(Reg, RC);
2205     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2206 
2207     if (Arg.Flags.isSRet()) {
2208       // The return object should be reasonably addressable.
2209 
2210       // FIXME: This helps when the return is a real sret. If it is a
2211       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2212       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2213       unsigned NumBits
2214         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2215       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2216         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2217     }
2218 
2219     // If this is an 8 or 16-bit value, it is really passed promoted
2220     // to 32 bits. Insert an assert[sz]ext to capture this, then
2221     // truncate to the right size.
2222     switch (VA.getLocInfo()) {
2223     case CCValAssign::Full:
2224       break;
2225     case CCValAssign::BCvt:
2226       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2227       break;
2228     case CCValAssign::SExt:
2229       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2230                         DAG.getValueType(ValVT));
2231       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2232       break;
2233     case CCValAssign::ZExt:
2234       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2235                         DAG.getValueType(ValVT));
2236       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2237       break;
2238     case CCValAssign::AExt:
2239       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2240       break;
2241     default:
2242       llvm_unreachable("Unknown loc info!");
2243     }
2244 
2245     InVals.push_back(Val);
2246   }
2247 
2248   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2249     // Special inputs come after user arguments.
2250     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2251   }
2252 
2253   // Start adding system SGPRs.
2254   if (IsEntryFunc) {
2255     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2256   } else {
2257     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2258     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2259   }
2260 
2261   auto &ArgUsageInfo =
2262     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2263   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2264 
2265   unsigned StackArgSize = CCInfo.getNextStackOffset();
2266   Info->setBytesInStackArgArea(StackArgSize);
2267 
2268   return Chains.empty() ? Chain :
2269     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2270 }
2271 
2272 // TODO: If return values can't fit in registers, we should return as many as
2273 // possible in registers before passing on stack.
2274 bool SITargetLowering::CanLowerReturn(
2275   CallingConv::ID CallConv,
2276   MachineFunction &MF, bool IsVarArg,
2277   const SmallVectorImpl<ISD::OutputArg> &Outs,
2278   LLVMContext &Context) const {
2279   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2280   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2281   // for shaders. Vector types should be explicitly handled by CC.
2282   if (AMDGPU::isEntryFunctionCC(CallConv))
2283     return true;
2284 
2285   SmallVector<CCValAssign, 16> RVLocs;
2286   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2287   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2288 }
2289 
2290 SDValue
2291 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2292                               bool isVarArg,
2293                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2294                               const SmallVectorImpl<SDValue> &OutVals,
2295                               const SDLoc &DL, SelectionDAG &DAG) const {
2296   MachineFunction &MF = DAG.getMachineFunction();
2297   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2298 
2299   if (AMDGPU::isKernel(CallConv)) {
2300     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2301                                              OutVals, DL, DAG);
2302   }
2303 
2304   bool IsShader = AMDGPU::isShader(CallConv);
2305 
2306   Info->setIfReturnsVoid(Outs.empty());
2307   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2308 
2309   // CCValAssign - represent the assignment of the return value to a location.
2310   SmallVector<CCValAssign, 48> RVLocs;
2311   SmallVector<ISD::OutputArg, 48> Splits;
2312 
2313   // CCState - Info about the registers and stack slots.
2314   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2315                  *DAG.getContext());
2316 
2317   // Analyze outgoing return values.
2318   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2319 
2320   SDValue Flag;
2321   SmallVector<SDValue, 48> RetOps;
2322   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2323 
2324   // Add return address for callable functions.
2325   if (!Info->isEntryFunction()) {
2326     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2327     SDValue ReturnAddrReg = CreateLiveInRegister(
2328       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2329 
2330     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2331         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2332         MVT::i64);
2333     Chain =
2334         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2335     Flag = Chain.getValue(1);
2336     RetOps.push_back(ReturnAddrVirtualReg);
2337   }
2338 
2339   // Copy the result values into the output registers.
2340   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2341        ++I, ++RealRVLocIdx) {
2342     CCValAssign &VA = RVLocs[I];
2343     assert(VA.isRegLoc() && "Can only return in registers!");
2344     // TODO: Partially return in registers if return values don't fit.
2345     SDValue Arg = OutVals[RealRVLocIdx];
2346 
2347     // Copied from other backends.
2348     switch (VA.getLocInfo()) {
2349     case CCValAssign::Full:
2350       break;
2351     case CCValAssign::BCvt:
2352       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2353       break;
2354     case CCValAssign::SExt:
2355       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2356       break;
2357     case CCValAssign::ZExt:
2358       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2359       break;
2360     case CCValAssign::AExt:
2361       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2362       break;
2363     default:
2364       llvm_unreachable("Unknown loc info!");
2365     }
2366 
2367     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2368     Flag = Chain.getValue(1);
2369     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2370   }
2371 
2372   // FIXME: Does sret work properly?
2373   if (!Info->isEntryFunction()) {
2374     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2375     const MCPhysReg *I =
2376       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2377     if (I) {
2378       for (; *I; ++I) {
2379         if (AMDGPU::SReg_64RegClass.contains(*I))
2380           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2381         else if (AMDGPU::SReg_32RegClass.contains(*I))
2382           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2383         else
2384           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2385       }
2386     }
2387   }
2388 
2389   // Update chain and glue.
2390   RetOps[0] = Chain;
2391   if (Flag.getNode())
2392     RetOps.push_back(Flag);
2393 
2394   unsigned Opc = AMDGPUISD::ENDPGM;
2395   if (!IsWaveEnd)
2396     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2397   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2398 }
2399 
2400 SDValue SITargetLowering::LowerCallResult(
2401     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2402     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2403     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2404     SDValue ThisVal) const {
2405   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2406 
2407   // Assign locations to each value returned by this call.
2408   SmallVector<CCValAssign, 16> RVLocs;
2409   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2410                  *DAG.getContext());
2411   CCInfo.AnalyzeCallResult(Ins, RetCC);
2412 
2413   // Copy all of the result registers out of their specified physreg.
2414   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2415     CCValAssign VA = RVLocs[i];
2416     SDValue Val;
2417 
2418     if (VA.isRegLoc()) {
2419       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2420       Chain = Val.getValue(1);
2421       InFlag = Val.getValue(2);
2422     } else if (VA.isMemLoc()) {
2423       report_fatal_error("TODO: return values in memory");
2424     } else
2425       llvm_unreachable("unknown argument location type");
2426 
2427     switch (VA.getLocInfo()) {
2428     case CCValAssign::Full:
2429       break;
2430     case CCValAssign::BCvt:
2431       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2432       break;
2433     case CCValAssign::ZExt:
2434       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2435                         DAG.getValueType(VA.getValVT()));
2436       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2437       break;
2438     case CCValAssign::SExt:
2439       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2440                         DAG.getValueType(VA.getValVT()));
2441       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2442       break;
2443     case CCValAssign::AExt:
2444       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2445       break;
2446     default:
2447       llvm_unreachable("Unknown loc info!");
2448     }
2449 
2450     InVals.push_back(Val);
2451   }
2452 
2453   return Chain;
2454 }
2455 
2456 // Add code to pass special inputs required depending on used features separate
2457 // from the explicit user arguments present in the IR.
2458 void SITargetLowering::passSpecialInputs(
2459     CallLoweringInfo &CLI,
2460     CCState &CCInfo,
2461     const SIMachineFunctionInfo &Info,
2462     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2463     SmallVectorImpl<SDValue> &MemOpChains,
2464     SDValue Chain) const {
2465   // If we don't have a call site, this was a call inserted by
2466   // legalization. These can never use special inputs.
2467   if (!CLI.CB)
2468     return;
2469 
2470   SelectionDAG &DAG = CLI.DAG;
2471   const SDLoc &DL = CLI.DL;
2472 
2473   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2474   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2475 
2476   const AMDGPUFunctionArgInfo *CalleeArgInfo
2477     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2478   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2479     auto &ArgUsageInfo =
2480       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2481     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2482   }
2483 
2484   // TODO: Unify with private memory register handling. This is complicated by
2485   // the fact that at least in kernels, the input argument is not necessarily
2486   // in the same location as the input.
2487   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2488     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2489     AMDGPUFunctionArgInfo::QUEUE_PTR,
2490     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2491     AMDGPUFunctionArgInfo::DISPATCH_ID,
2492     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2493     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2494     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2495   };
2496 
2497   for (auto InputID : InputRegs) {
2498     const ArgDescriptor *OutgoingArg;
2499     const TargetRegisterClass *ArgRC;
2500 
2501     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2502     if (!OutgoingArg)
2503       continue;
2504 
2505     const ArgDescriptor *IncomingArg;
2506     const TargetRegisterClass *IncomingArgRC;
2507     std::tie(IncomingArg, IncomingArgRC)
2508       = CallerArgInfo.getPreloadedValue(InputID);
2509     assert(IncomingArgRC == ArgRC);
2510 
2511     // All special arguments are ints for now.
2512     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2513     SDValue InputReg;
2514 
2515     if (IncomingArg) {
2516       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2517     } else {
2518       // The implicit arg ptr is special because it doesn't have a corresponding
2519       // input for kernels, and is computed from the kernarg segment pointer.
2520       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2521       InputReg = getImplicitArgPtr(DAG, DL);
2522     }
2523 
2524     if (OutgoingArg->isRegister()) {
2525       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2526       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2527         report_fatal_error("failed to allocate implicit input argument");
2528     } else {
2529       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2530       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2531                                               SpecialArgOffset);
2532       MemOpChains.push_back(ArgStore);
2533     }
2534   }
2535 
2536   // Pack workitem IDs into a single register or pass it as is if already
2537   // packed.
2538   const ArgDescriptor *OutgoingArg;
2539   const TargetRegisterClass *ArgRC;
2540 
2541   std::tie(OutgoingArg, ArgRC) =
2542     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2543   if (!OutgoingArg)
2544     std::tie(OutgoingArg, ArgRC) =
2545       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2546   if (!OutgoingArg)
2547     std::tie(OutgoingArg, ArgRC) =
2548       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2549   if (!OutgoingArg)
2550     return;
2551 
2552   const ArgDescriptor *IncomingArgX
2553     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2554   const ArgDescriptor *IncomingArgY
2555     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2556   const ArgDescriptor *IncomingArgZ
2557     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2558 
2559   SDValue InputReg;
2560   SDLoc SL;
2561 
2562   // If incoming ids are not packed we need to pack them.
2563   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2564     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2565 
2566   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2567     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2568     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2569                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2570     InputReg = InputReg.getNode() ?
2571                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2572   }
2573 
2574   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2575     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2576     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2577                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2578     InputReg = InputReg.getNode() ?
2579                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2580   }
2581 
2582   if (!InputReg.getNode()) {
2583     // Workitem ids are already packed, any of present incoming arguments
2584     // will carry all required fields.
2585     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2586       IncomingArgX ? *IncomingArgX :
2587       IncomingArgY ? *IncomingArgY :
2588                      *IncomingArgZ, ~0u);
2589     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2590   }
2591 
2592   if (OutgoingArg->isRegister()) {
2593     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2594     CCInfo.AllocateReg(OutgoingArg->getRegister());
2595   } else {
2596     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2597     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2598                                             SpecialArgOffset);
2599     MemOpChains.push_back(ArgStore);
2600   }
2601 }
2602 
2603 static bool canGuaranteeTCO(CallingConv::ID CC) {
2604   return CC == CallingConv::Fast;
2605 }
2606 
2607 /// Return true if we might ever do TCO for calls with this calling convention.
2608 static bool mayTailCallThisCC(CallingConv::ID CC) {
2609   switch (CC) {
2610   case CallingConv::C:
2611     return true;
2612   default:
2613     return canGuaranteeTCO(CC);
2614   }
2615 }
2616 
2617 bool SITargetLowering::isEligibleForTailCallOptimization(
2618     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2619     const SmallVectorImpl<ISD::OutputArg> &Outs,
2620     const SmallVectorImpl<SDValue> &OutVals,
2621     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2622   if (!mayTailCallThisCC(CalleeCC))
2623     return false;
2624 
2625   MachineFunction &MF = DAG.getMachineFunction();
2626   const Function &CallerF = MF.getFunction();
2627   CallingConv::ID CallerCC = CallerF.getCallingConv();
2628   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2629   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2630 
2631   // Kernels aren't callable, and don't have a live in return address so it
2632   // doesn't make sense to do a tail call with entry functions.
2633   if (!CallerPreserved)
2634     return false;
2635 
2636   bool CCMatch = CallerCC == CalleeCC;
2637 
2638   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2639     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2640       return true;
2641     return false;
2642   }
2643 
2644   // TODO: Can we handle var args?
2645   if (IsVarArg)
2646     return false;
2647 
2648   for (const Argument &Arg : CallerF.args()) {
2649     if (Arg.hasByValAttr())
2650       return false;
2651   }
2652 
2653   LLVMContext &Ctx = *DAG.getContext();
2654 
2655   // Check that the call results are passed in the same way.
2656   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2657                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2658                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2659     return false;
2660 
2661   // The callee has to preserve all registers the caller needs to preserve.
2662   if (!CCMatch) {
2663     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2664     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2665       return false;
2666   }
2667 
2668   // Nothing more to check if the callee is taking no arguments.
2669   if (Outs.empty())
2670     return true;
2671 
2672   SmallVector<CCValAssign, 16> ArgLocs;
2673   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2674 
2675   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2676 
2677   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2678   // If the stack arguments for this call do not fit into our own save area then
2679   // the call cannot be made tail.
2680   // TODO: Is this really necessary?
2681   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2682     return false;
2683 
2684   const MachineRegisterInfo &MRI = MF.getRegInfo();
2685   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2686 }
2687 
2688 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2689   if (!CI->isTailCall())
2690     return false;
2691 
2692   const Function *ParentFn = CI->getParent()->getParent();
2693   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2694     return false;
2695   return true;
2696 }
2697 
2698 // The wave scratch offset register is used as the global base pointer.
2699 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2700                                     SmallVectorImpl<SDValue> &InVals) const {
2701   SelectionDAG &DAG = CLI.DAG;
2702   const SDLoc &DL = CLI.DL;
2703   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2704   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2705   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2706   SDValue Chain = CLI.Chain;
2707   SDValue Callee = CLI.Callee;
2708   bool &IsTailCall = CLI.IsTailCall;
2709   CallingConv::ID CallConv = CLI.CallConv;
2710   bool IsVarArg = CLI.IsVarArg;
2711   bool IsSibCall = false;
2712   bool IsThisReturn = false;
2713   MachineFunction &MF = DAG.getMachineFunction();
2714 
2715   if (Callee.isUndef() || isNullConstant(Callee)) {
2716     if (!CLI.IsTailCall) {
2717       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2718         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2719     }
2720 
2721     return Chain;
2722   }
2723 
2724   if (IsVarArg) {
2725     return lowerUnhandledCall(CLI, InVals,
2726                               "unsupported call to variadic function ");
2727   }
2728 
2729   if (!CLI.CB)
2730     report_fatal_error("unsupported libcall legalization");
2731 
2732   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2733       !CLI.CB->getCalledFunction()) {
2734     return lowerUnhandledCall(CLI, InVals,
2735                               "unsupported indirect call to function ");
2736   }
2737 
2738   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2739     return lowerUnhandledCall(CLI, InVals,
2740                               "unsupported required tail call to function ");
2741   }
2742 
2743   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2744     // Note the issue is with the CC of the calling function, not of the call
2745     // itself.
2746     return lowerUnhandledCall(CLI, InVals,
2747                           "unsupported call from graphics shader of function ");
2748   }
2749 
2750   if (IsTailCall) {
2751     IsTailCall = isEligibleForTailCallOptimization(
2752       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2753     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2754       report_fatal_error("failed to perform tail call elimination on a call "
2755                          "site marked musttail");
2756     }
2757 
2758     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2759 
2760     // A sibling call is one where we're under the usual C ABI and not planning
2761     // to change that but can still do a tail call:
2762     if (!TailCallOpt && IsTailCall)
2763       IsSibCall = true;
2764 
2765     if (IsTailCall)
2766       ++NumTailCalls;
2767   }
2768 
2769   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2770   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2771   SmallVector<SDValue, 8> MemOpChains;
2772 
2773   // Analyze operands of the call, assigning locations to each operand.
2774   SmallVector<CCValAssign, 16> ArgLocs;
2775   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2776   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2777 
2778   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2779     // With a fixed ABI, allocate fixed registers before user arguments.
2780     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2781   }
2782 
2783   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2784 
2785   // Get a count of how many bytes are to be pushed on the stack.
2786   unsigned NumBytes = CCInfo.getNextStackOffset();
2787 
2788   if (IsSibCall) {
2789     // Since we're not changing the ABI to make this a tail call, the memory
2790     // operands are already available in the caller's incoming argument space.
2791     NumBytes = 0;
2792   }
2793 
2794   // FPDiff is the byte offset of the call's argument area from the callee's.
2795   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2796   // by this amount for a tail call. In a sibling call it must be 0 because the
2797   // caller will deallocate the entire stack and the callee still expects its
2798   // arguments to begin at SP+0. Completely unused for non-tail calls.
2799   int32_t FPDiff = 0;
2800   MachineFrameInfo &MFI = MF.getFrameInfo();
2801 
2802   // Adjust the stack pointer for the new arguments...
2803   // These operations are automatically eliminated by the prolog/epilog pass
2804   if (!IsSibCall) {
2805     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2806 
2807     SmallVector<SDValue, 4> CopyFromChains;
2808 
2809     // In the HSA case, this should be an identity copy.
2810     SDValue ScratchRSrcReg
2811       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2812     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2813     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2814     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2815   }
2816 
2817   MVT PtrVT = MVT::i32;
2818 
2819   // Walk the register/memloc assignments, inserting copies/loads.
2820   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2821     CCValAssign &VA = ArgLocs[i];
2822     SDValue Arg = OutVals[i];
2823 
2824     // Promote the value if needed.
2825     switch (VA.getLocInfo()) {
2826     case CCValAssign::Full:
2827       break;
2828     case CCValAssign::BCvt:
2829       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2830       break;
2831     case CCValAssign::ZExt:
2832       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2833       break;
2834     case CCValAssign::SExt:
2835       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2836       break;
2837     case CCValAssign::AExt:
2838       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2839       break;
2840     case CCValAssign::FPExt:
2841       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2842       break;
2843     default:
2844       llvm_unreachable("Unknown loc info!");
2845     }
2846 
2847     if (VA.isRegLoc()) {
2848       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2849     } else {
2850       assert(VA.isMemLoc());
2851 
2852       SDValue DstAddr;
2853       MachinePointerInfo DstInfo;
2854 
2855       unsigned LocMemOffset = VA.getLocMemOffset();
2856       int32_t Offset = LocMemOffset;
2857 
2858       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2859       MaybeAlign Alignment;
2860 
2861       if (IsTailCall) {
2862         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2863         unsigned OpSize = Flags.isByVal() ?
2864           Flags.getByValSize() : VA.getValVT().getStoreSize();
2865 
2866         // FIXME: We can have better than the minimum byval required alignment.
2867         Alignment =
2868             Flags.isByVal()
2869                 ? Flags.getNonZeroByValAlign()
2870                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2871 
2872         Offset = Offset + FPDiff;
2873         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2874 
2875         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2876         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2877 
2878         // Make sure any stack arguments overlapping with where we're storing
2879         // are loaded before this eventual operation. Otherwise they'll be
2880         // clobbered.
2881 
2882         // FIXME: Why is this really necessary? This seems to just result in a
2883         // lot of code to copy the stack and write them back to the same
2884         // locations, which are supposed to be immutable?
2885         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2886       } else {
2887         DstAddr = PtrOff;
2888         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2889         Alignment =
2890             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2891       }
2892 
2893       if (Outs[i].Flags.isByVal()) {
2894         SDValue SizeNode =
2895             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2896         SDValue Cpy =
2897             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2898                           Outs[i].Flags.getNonZeroByValAlign(),
2899                           /*isVol = */ false, /*AlwaysInline = */ true,
2900                           /*isTailCall = */ false, DstInfo,
2901                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2902 
2903         MemOpChains.push_back(Cpy);
2904       } else {
2905         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2906                                      Alignment ? Alignment->value() : 0);
2907         MemOpChains.push_back(Store);
2908       }
2909     }
2910   }
2911 
2912   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2913     // Copy special input registers after user input arguments.
2914     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2915   }
2916 
2917   if (!MemOpChains.empty())
2918     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2919 
2920   // Build a sequence of copy-to-reg nodes chained together with token chain
2921   // and flag operands which copy the outgoing args into the appropriate regs.
2922   SDValue InFlag;
2923   for (auto &RegToPass : RegsToPass) {
2924     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2925                              RegToPass.second, InFlag);
2926     InFlag = Chain.getValue(1);
2927   }
2928 
2929 
2930   SDValue PhysReturnAddrReg;
2931   if (IsTailCall) {
2932     // Since the return is being combined with the call, we need to pass on the
2933     // return address.
2934 
2935     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2936     SDValue ReturnAddrReg = CreateLiveInRegister(
2937       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2938 
2939     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2940                                         MVT::i64);
2941     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2942     InFlag = Chain.getValue(1);
2943   }
2944 
2945   // We don't usually want to end the call-sequence here because we would tidy
2946   // the frame up *after* the call, however in the ABI-changing tail-call case
2947   // we've carefully laid out the parameters so that when sp is reset they'll be
2948   // in the correct location.
2949   if (IsTailCall && !IsSibCall) {
2950     Chain = DAG.getCALLSEQ_END(Chain,
2951                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2952                                DAG.getTargetConstant(0, DL, MVT::i32),
2953                                InFlag, DL);
2954     InFlag = Chain.getValue(1);
2955   }
2956 
2957   std::vector<SDValue> Ops;
2958   Ops.push_back(Chain);
2959   Ops.push_back(Callee);
2960   // Add a redundant copy of the callee global which will not be legalized, as
2961   // we need direct access to the callee later.
2962   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
2963     const GlobalValue *GV = GSD->getGlobal();
2964     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2965   } else {
2966     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
2967   }
2968 
2969   if (IsTailCall) {
2970     // Each tail call may have to adjust the stack by a different amount, so
2971     // this information must travel along with the operation for eventual
2972     // consumption by emitEpilogue.
2973     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2974 
2975     Ops.push_back(PhysReturnAddrReg);
2976   }
2977 
2978   // Add argument registers to the end of the list so that they are known live
2979   // into the call.
2980   for (auto &RegToPass : RegsToPass) {
2981     Ops.push_back(DAG.getRegister(RegToPass.first,
2982                                   RegToPass.second.getValueType()));
2983   }
2984 
2985   // Add a register mask operand representing the call-preserved registers.
2986 
2987   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2988   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2989   assert(Mask && "Missing call preserved mask for calling convention");
2990   Ops.push_back(DAG.getRegisterMask(Mask));
2991 
2992   if (InFlag.getNode())
2993     Ops.push_back(InFlag);
2994 
2995   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2996 
2997   // If we're doing a tall call, use a TC_RETURN here rather than an
2998   // actual call instruction.
2999   if (IsTailCall) {
3000     MFI.setHasTailCall();
3001     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3002   }
3003 
3004   // Returns a chain and a flag for retval copy to use.
3005   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3006   Chain = Call.getValue(0);
3007   InFlag = Call.getValue(1);
3008 
3009   uint64_t CalleePopBytes = NumBytes;
3010   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3011                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3012                              InFlag, DL);
3013   if (!Ins.empty())
3014     InFlag = Chain.getValue(1);
3015 
3016   // Handle result values, copying them out of physregs into vregs that we
3017   // return.
3018   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3019                          InVals, IsThisReturn,
3020                          IsThisReturn ? OutVals[0] : SDValue());
3021 }
3022 
3023 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3024                                              const MachineFunction &MF) const {
3025   Register Reg = StringSwitch<Register>(RegName)
3026     .Case("m0", AMDGPU::M0)
3027     .Case("exec", AMDGPU::EXEC)
3028     .Case("exec_lo", AMDGPU::EXEC_LO)
3029     .Case("exec_hi", AMDGPU::EXEC_HI)
3030     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3031     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3032     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3033     .Default(Register());
3034 
3035   if (Reg == AMDGPU::NoRegister) {
3036     report_fatal_error(Twine("invalid register name \""
3037                              + StringRef(RegName)  + "\"."));
3038 
3039   }
3040 
3041   if (!Subtarget->hasFlatScrRegister() &&
3042        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3043     report_fatal_error(Twine("invalid register \""
3044                              + StringRef(RegName)  + "\" for subtarget."));
3045   }
3046 
3047   switch (Reg) {
3048   case AMDGPU::M0:
3049   case AMDGPU::EXEC_LO:
3050   case AMDGPU::EXEC_HI:
3051   case AMDGPU::FLAT_SCR_LO:
3052   case AMDGPU::FLAT_SCR_HI:
3053     if (VT.getSizeInBits() == 32)
3054       return Reg;
3055     break;
3056   case AMDGPU::EXEC:
3057   case AMDGPU::FLAT_SCR:
3058     if (VT.getSizeInBits() == 64)
3059       return Reg;
3060     break;
3061   default:
3062     llvm_unreachable("missing register type checking");
3063   }
3064 
3065   report_fatal_error(Twine("invalid type for register \""
3066                            + StringRef(RegName) + "\"."));
3067 }
3068 
3069 // If kill is not the last instruction, split the block so kill is always a
3070 // proper terminator.
3071 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3072                                                     MachineBasicBlock *BB) const {
3073   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3074 
3075   MachineBasicBlock::iterator SplitPoint(&MI);
3076   ++SplitPoint;
3077 
3078   if (SplitPoint == BB->end()) {
3079     // Don't bother with a new block.
3080     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3081     return BB;
3082   }
3083 
3084   MachineFunction *MF = BB->getParent();
3085   MachineBasicBlock *SplitBB
3086     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3087 
3088   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3089   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3090 
3091   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3092   BB->addSuccessor(SplitBB);
3093 
3094   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3095   return SplitBB;
3096 }
3097 
3098 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3099 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3100 // be the first instruction in the remainder block.
3101 //
3102 /// \returns { LoopBody, Remainder }
3103 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3104 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3105   MachineFunction *MF = MBB.getParent();
3106   MachineBasicBlock::iterator I(&MI);
3107 
3108   // To insert the loop we need to split the block. Move everything after this
3109   // point to a new block, and insert a new empty block between the two.
3110   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3111   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3112   MachineFunction::iterator MBBI(MBB);
3113   ++MBBI;
3114 
3115   MF->insert(MBBI, LoopBB);
3116   MF->insert(MBBI, RemainderBB);
3117 
3118   LoopBB->addSuccessor(LoopBB);
3119   LoopBB->addSuccessor(RemainderBB);
3120 
3121   // Move the rest of the block into a new block.
3122   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3123 
3124   if (InstInLoop) {
3125     auto Next = std::next(I);
3126 
3127     // Move instruction to loop body.
3128     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3129 
3130     // Move the rest of the block.
3131     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3132   } else {
3133     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3134   }
3135 
3136   MBB.addSuccessor(LoopBB);
3137 
3138   return std::make_pair(LoopBB, RemainderBB);
3139 }
3140 
3141 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3142 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3143   MachineBasicBlock *MBB = MI.getParent();
3144   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3145   auto I = MI.getIterator();
3146   auto E = std::next(I);
3147 
3148   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3149     .addImm(0);
3150 
3151   MIBundleBuilder Bundler(*MBB, I, E);
3152   finalizeBundle(*MBB, Bundler.begin());
3153 }
3154 
3155 MachineBasicBlock *
3156 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3157                                          MachineBasicBlock *BB) const {
3158   const DebugLoc &DL = MI.getDebugLoc();
3159 
3160   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3161 
3162   MachineBasicBlock *LoopBB;
3163   MachineBasicBlock *RemainderBB;
3164   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3165 
3166   // Apparently kill flags are only valid if the def is in the same block?
3167   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3168     Src->setIsKill(false);
3169 
3170   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3171 
3172   MachineBasicBlock::iterator I = LoopBB->end();
3173 
3174   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3175     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3176 
3177   // Clear TRAP_STS.MEM_VIOL
3178   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3179     .addImm(0)
3180     .addImm(EncodedReg);
3181 
3182   bundleInstWithWaitcnt(MI);
3183 
3184   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3185 
3186   // Load and check TRAP_STS.MEM_VIOL
3187   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3188     .addImm(EncodedReg);
3189 
3190   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3191   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3192     .addReg(Reg, RegState::Kill)
3193     .addImm(0);
3194   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3195     .addMBB(LoopBB);
3196 
3197   return RemainderBB;
3198 }
3199 
3200 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3201 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3202 // will only do one iteration. In the worst case, this will loop 64 times.
3203 //
3204 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3205 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3206   const SIInstrInfo *TII,
3207   MachineRegisterInfo &MRI,
3208   MachineBasicBlock &OrigBB,
3209   MachineBasicBlock &LoopBB,
3210   const DebugLoc &DL,
3211   const MachineOperand &IdxReg,
3212   unsigned InitReg,
3213   unsigned ResultReg,
3214   unsigned PhiReg,
3215   unsigned InitSaveExecReg,
3216   int Offset,
3217   bool UseGPRIdxMode,
3218   bool IsIndirectSrc) {
3219   MachineFunction *MF = OrigBB.getParent();
3220   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3221   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3222   MachineBasicBlock::iterator I = LoopBB.begin();
3223 
3224   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3225   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3226   Register NewExec = MRI.createVirtualRegister(BoolRC);
3227   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3228   Register CondReg = MRI.createVirtualRegister(BoolRC);
3229 
3230   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3231     .addReg(InitReg)
3232     .addMBB(&OrigBB)
3233     .addReg(ResultReg)
3234     .addMBB(&LoopBB);
3235 
3236   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3237     .addReg(InitSaveExecReg)
3238     .addMBB(&OrigBB)
3239     .addReg(NewExec)
3240     .addMBB(&LoopBB);
3241 
3242   // Read the next variant <- also loop target.
3243   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3244     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3245 
3246   // Compare the just read M0 value to all possible Idx values.
3247   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3248     .addReg(CurrentIdxReg)
3249     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3250 
3251   // Update EXEC, save the original EXEC value to VCC.
3252   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3253                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3254           NewExec)
3255     .addReg(CondReg, RegState::Kill);
3256 
3257   MRI.setSimpleHint(NewExec, CondReg);
3258 
3259   if (UseGPRIdxMode) {
3260     unsigned IdxReg;
3261     if (Offset == 0) {
3262       IdxReg = CurrentIdxReg;
3263     } else {
3264       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3265       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3266         .addReg(CurrentIdxReg, RegState::Kill)
3267         .addImm(Offset);
3268     }
3269     unsigned IdxMode = IsIndirectSrc ?
3270       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3271     MachineInstr *SetOn =
3272       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3273       .addReg(IdxReg, RegState::Kill)
3274       .addImm(IdxMode);
3275     SetOn->getOperand(3).setIsUndef();
3276   } else {
3277     // Move index from VCC into M0
3278     if (Offset == 0) {
3279       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3280         .addReg(CurrentIdxReg, RegState::Kill);
3281     } else {
3282       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3283         .addReg(CurrentIdxReg, RegState::Kill)
3284         .addImm(Offset);
3285     }
3286   }
3287 
3288   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3289   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3290   MachineInstr *InsertPt =
3291     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3292                                                   : AMDGPU::S_XOR_B64_term), Exec)
3293       .addReg(Exec)
3294       .addReg(NewExec);
3295 
3296   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3297   // s_cbranch_scc0?
3298 
3299   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3300   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3301     .addMBB(&LoopBB);
3302 
3303   return InsertPt->getIterator();
3304 }
3305 
3306 // This has slightly sub-optimal regalloc when the source vector is killed by
3307 // the read. The register allocator does not understand that the kill is
3308 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3309 // subregister from it, using 1 more VGPR than necessary. This was saved when
3310 // this was expanded after register allocation.
3311 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3312                                                   MachineBasicBlock &MBB,
3313                                                   MachineInstr &MI,
3314                                                   unsigned InitResultReg,
3315                                                   unsigned PhiReg,
3316                                                   int Offset,
3317                                                   bool UseGPRIdxMode,
3318                                                   bool IsIndirectSrc) {
3319   MachineFunction *MF = MBB.getParent();
3320   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3321   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3322   MachineRegisterInfo &MRI = MF->getRegInfo();
3323   const DebugLoc &DL = MI.getDebugLoc();
3324   MachineBasicBlock::iterator I(&MI);
3325 
3326   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3327   Register DstReg = MI.getOperand(0).getReg();
3328   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3329   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3330   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3331   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3332 
3333   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3334 
3335   // Save the EXEC mask
3336   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3337     .addReg(Exec);
3338 
3339   MachineBasicBlock *LoopBB;
3340   MachineBasicBlock *RemainderBB;
3341   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3342 
3343   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3344 
3345   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3346                                       InitResultReg, DstReg, PhiReg, TmpExec,
3347                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3348   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3349   MachineFunction::iterator MBBI(LoopBB);
3350   ++MBBI;
3351   MF->insert(MBBI, LandingPad);
3352   LoopBB->removeSuccessor(RemainderBB);
3353   LandingPad->addSuccessor(RemainderBB);
3354   LoopBB->addSuccessor(LandingPad);
3355   MachineBasicBlock::iterator First = LandingPad->begin();
3356   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3357     .addReg(SaveExec);
3358 
3359   return InsPt;
3360 }
3361 
3362 // Returns subreg index, offset
3363 static std::pair<unsigned, int>
3364 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3365                             const TargetRegisterClass *SuperRC,
3366                             unsigned VecReg,
3367                             int Offset) {
3368   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3369 
3370   // Skip out of bounds offsets, or else we would end up using an undefined
3371   // register.
3372   if (Offset >= NumElts || Offset < 0)
3373     return std::make_pair(AMDGPU::sub0, Offset);
3374 
3375   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3376 }
3377 
3378 // Return true if the index is an SGPR and was set.
3379 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3380                                  MachineRegisterInfo &MRI,
3381                                  MachineInstr &MI,
3382                                  int Offset,
3383                                  bool UseGPRIdxMode,
3384                                  bool IsIndirectSrc) {
3385   MachineBasicBlock *MBB = MI.getParent();
3386   const DebugLoc &DL = MI.getDebugLoc();
3387   MachineBasicBlock::iterator I(&MI);
3388 
3389   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3390   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3391 
3392   assert(Idx->getReg() != AMDGPU::NoRegister);
3393 
3394   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3395     return false;
3396 
3397   if (UseGPRIdxMode) {
3398     unsigned IdxMode = IsIndirectSrc ?
3399       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3400     if (Offset == 0) {
3401       MachineInstr *SetOn =
3402           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3403               .add(*Idx)
3404               .addImm(IdxMode);
3405 
3406       SetOn->getOperand(3).setIsUndef();
3407     } else {
3408       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3409       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3410           .add(*Idx)
3411           .addImm(Offset);
3412       MachineInstr *SetOn =
3413         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3414         .addReg(Tmp, RegState::Kill)
3415         .addImm(IdxMode);
3416 
3417       SetOn->getOperand(3).setIsUndef();
3418     }
3419 
3420     return true;
3421   }
3422 
3423   if (Offset == 0) {
3424     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3425       .add(*Idx);
3426   } else {
3427     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3428       .add(*Idx)
3429       .addImm(Offset);
3430   }
3431 
3432   return true;
3433 }
3434 
3435 // Control flow needs to be inserted if indexing with a VGPR.
3436 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3437                                           MachineBasicBlock &MBB,
3438                                           const GCNSubtarget &ST) {
3439   const SIInstrInfo *TII = ST.getInstrInfo();
3440   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3441   MachineFunction *MF = MBB.getParent();
3442   MachineRegisterInfo &MRI = MF->getRegInfo();
3443 
3444   Register Dst = MI.getOperand(0).getReg();
3445   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3446   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3447 
3448   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3449 
3450   unsigned SubReg;
3451   std::tie(SubReg, Offset)
3452     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3453 
3454   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3455 
3456   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3457     MachineBasicBlock::iterator I(&MI);
3458     const DebugLoc &DL = MI.getDebugLoc();
3459 
3460     if (UseGPRIdxMode) {
3461       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3462       // to avoid interfering with other uses, so probably requires a new
3463       // optimization pass.
3464       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3465         .addReg(SrcReg, RegState::Undef, SubReg)
3466         .addReg(SrcReg, RegState::Implicit)
3467         .addReg(AMDGPU::M0, RegState::Implicit);
3468       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3469     } else {
3470       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3471         .addReg(SrcReg, RegState::Undef, SubReg)
3472         .addReg(SrcReg, RegState::Implicit);
3473     }
3474 
3475     MI.eraseFromParent();
3476 
3477     return &MBB;
3478   }
3479 
3480   const DebugLoc &DL = MI.getDebugLoc();
3481   MachineBasicBlock::iterator I(&MI);
3482 
3483   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3484   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3485 
3486   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3487 
3488   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3489                               Offset, UseGPRIdxMode, true);
3490   MachineBasicBlock *LoopBB = InsPt->getParent();
3491 
3492   if (UseGPRIdxMode) {
3493     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3494       .addReg(SrcReg, RegState::Undef, SubReg)
3495       .addReg(SrcReg, RegState::Implicit)
3496       .addReg(AMDGPU::M0, RegState::Implicit);
3497     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3498   } else {
3499     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3500       .addReg(SrcReg, RegState::Undef, SubReg)
3501       .addReg(SrcReg, RegState::Implicit);
3502   }
3503 
3504   MI.eraseFromParent();
3505 
3506   return LoopBB;
3507 }
3508 
3509 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3510                                           MachineBasicBlock &MBB,
3511                                           const GCNSubtarget &ST) {
3512   const SIInstrInfo *TII = ST.getInstrInfo();
3513   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3514   MachineFunction *MF = MBB.getParent();
3515   MachineRegisterInfo &MRI = MF->getRegInfo();
3516 
3517   Register Dst = MI.getOperand(0).getReg();
3518   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3519   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3520   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3521   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3522   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3523 
3524   // This can be an immediate, but will be folded later.
3525   assert(Val->getReg());
3526 
3527   unsigned SubReg;
3528   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3529                                                          SrcVec->getReg(),
3530                                                          Offset);
3531   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3532 
3533   if (Idx->getReg() == AMDGPU::NoRegister) {
3534     MachineBasicBlock::iterator I(&MI);
3535     const DebugLoc &DL = MI.getDebugLoc();
3536 
3537     assert(Offset == 0);
3538 
3539     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3540         .add(*SrcVec)
3541         .add(*Val)
3542         .addImm(SubReg);
3543 
3544     MI.eraseFromParent();
3545     return &MBB;
3546   }
3547 
3548   const MCInstrDesc &MovRelDesc
3549     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3550 
3551   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3552     MachineBasicBlock::iterator I(&MI);
3553     const DebugLoc &DL = MI.getDebugLoc();
3554     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3555       .addReg(SrcVec->getReg())
3556       .add(*Val)
3557       .addImm(SubReg);
3558     if (UseGPRIdxMode)
3559       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3560 
3561     MI.eraseFromParent();
3562     return &MBB;
3563   }
3564 
3565   if (Val->isReg())
3566     MRI.clearKillFlags(Val->getReg());
3567 
3568   const DebugLoc &DL = MI.getDebugLoc();
3569 
3570   Register PhiReg = MRI.createVirtualRegister(VecRC);
3571 
3572   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3573                               Offset, UseGPRIdxMode, false);
3574   MachineBasicBlock *LoopBB = InsPt->getParent();
3575 
3576   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3577     .addReg(PhiReg)
3578     .add(*Val)
3579     .addImm(AMDGPU::sub0);
3580   if (UseGPRIdxMode)
3581     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3582 
3583   MI.eraseFromParent();
3584   return LoopBB;
3585 }
3586 
3587 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3588   MachineInstr &MI, MachineBasicBlock *BB) const {
3589 
3590   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3591   MachineFunction *MF = BB->getParent();
3592   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3593 
3594   if (TII->isMIMG(MI)) {
3595     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3596       report_fatal_error("missing mem operand from MIMG instruction");
3597     }
3598     // Add a memoperand for mimg instructions so that they aren't assumed to
3599     // be ordered memory instuctions.
3600 
3601     return BB;
3602   }
3603 
3604   switch (MI.getOpcode()) {
3605   case AMDGPU::S_ADD_U64_PSEUDO:
3606   case AMDGPU::S_SUB_U64_PSEUDO: {
3607     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3608     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3609     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3610     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3611     const DebugLoc &DL = MI.getDebugLoc();
3612 
3613     MachineOperand &Dest = MI.getOperand(0);
3614     MachineOperand &Src0 = MI.getOperand(1);
3615     MachineOperand &Src1 = MI.getOperand(2);
3616 
3617     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3618     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3619 
3620     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3621      Src0, BoolRC, AMDGPU::sub0,
3622      &AMDGPU::SReg_32RegClass);
3623     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3624       Src0, BoolRC, AMDGPU::sub1,
3625       &AMDGPU::SReg_32RegClass);
3626 
3627     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3628       Src1, BoolRC, AMDGPU::sub0,
3629       &AMDGPU::SReg_32RegClass);
3630     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3631       Src1, BoolRC, AMDGPU::sub1,
3632       &AMDGPU::SReg_32RegClass);
3633 
3634     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3635 
3636     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3637     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3638     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3639       .add(Src0Sub0)
3640       .add(Src1Sub0);
3641     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3642       .add(Src0Sub1)
3643       .add(Src1Sub1);
3644     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3645       .addReg(DestSub0)
3646       .addImm(AMDGPU::sub0)
3647       .addReg(DestSub1)
3648       .addImm(AMDGPU::sub1);
3649     MI.eraseFromParent();
3650     return BB;
3651   }
3652   case AMDGPU::SI_INIT_M0: {
3653     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3654             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3655         .add(MI.getOperand(0));
3656     MI.eraseFromParent();
3657     return BB;
3658   }
3659   case AMDGPU::SI_INIT_EXEC:
3660     // This should be before all vector instructions.
3661     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3662             AMDGPU::EXEC)
3663         .addImm(MI.getOperand(0).getImm());
3664     MI.eraseFromParent();
3665     return BB;
3666 
3667   case AMDGPU::SI_INIT_EXEC_LO:
3668     // This should be before all vector instructions.
3669     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3670             AMDGPU::EXEC_LO)
3671         .addImm(MI.getOperand(0).getImm());
3672     MI.eraseFromParent();
3673     return BB;
3674 
3675   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3676     // Extract the thread count from an SGPR input and set EXEC accordingly.
3677     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3678     //
3679     // S_BFE_U32 count, input, {shift, 7}
3680     // S_BFM_B64 exec, count, 0
3681     // S_CMP_EQ_U32 count, 64
3682     // S_CMOV_B64 exec, -1
3683     MachineInstr *FirstMI = &*BB->begin();
3684     MachineRegisterInfo &MRI = MF->getRegInfo();
3685     Register InputReg = MI.getOperand(0).getReg();
3686     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3687     bool Found = false;
3688 
3689     // Move the COPY of the input reg to the beginning, so that we can use it.
3690     for (auto I = BB->begin(); I != &MI; I++) {
3691       if (I->getOpcode() != TargetOpcode::COPY ||
3692           I->getOperand(0).getReg() != InputReg)
3693         continue;
3694 
3695       if (I == FirstMI) {
3696         FirstMI = &*++BB->begin();
3697       } else {
3698         I->removeFromParent();
3699         BB->insert(FirstMI, &*I);
3700       }
3701       Found = true;
3702       break;
3703     }
3704     assert(Found);
3705     (void)Found;
3706 
3707     // This should be before all vector instructions.
3708     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3709     bool isWave32 = getSubtarget()->isWave32();
3710     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3711     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3712         .addReg(InputReg)
3713         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3714     BuildMI(*BB, FirstMI, DebugLoc(),
3715             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3716             Exec)
3717         .addReg(CountReg)
3718         .addImm(0);
3719     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3720         .addReg(CountReg, RegState::Kill)
3721         .addImm(getSubtarget()->getWavefrontSize());
3722     BuildMI(*BB, FirstMI, DebugLoc(),
3723             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3724             Exec)
3725         .addImm(-1);
3726     MI.eraseFromParent();
3727     return BB;
3728   }
3729 
3730   case AMDGPU::GET_GROUPSTATICSIZE: {
3731     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3732            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3733     DebugLoc DL = MI.getDebugLoc();
3734     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3735         .add(MI.getOperand(0))
3736         .addImm(MFI->getLDSSize());
3737     MI.eraseFromParent();
3738     return BB;
3739   }
3740   case AMDGPU::SI_INDIRECT_SRC_V1:
3741   case AMDGPU::SI_INDIRECT_SRC_V2:
3742   case AMDGPU::SI_INDIRECT_SRC_V4:
3743   case AMDGPU::SI_INDIRECT_SRC_V8:
3744   case AMDGPU::SI_INDIRECT_SRC_V16:
3745     return emitIndirectSrc(MI, *BB, *getSubtarget());
3746   case AMDGPU::SI_INDIRECT_DST_V1:
3747   case AMDGPU::SI_INDIRECT_DST_V2:
3748   case AMDGPU::SI_INDIRECT_DST_V4:
3749   case AMDGPU::SI_INDIRECT_DST_V8:
3750   case AMDGPU::SI_INDIRECT_DST_V16:
3751     return emitIndirectDst(MI, *BB, *getSubtarget());
3752   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3753   case AMDGPU::SI_KILL_I1_PSEUDO:
3754     return splitKillBlock(MI, BB);
3755   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3756     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3757     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3758     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3759 
3760     Register Dst = MI.getOperand(0).getReg();
3761     Register Src0 = MI.getOperand(1).getReg();
3762     Register Src1 = MI.getOperand(2).getReg();
3763     const DebugLoc &DL = MI.getDebugLoc();
3764     Register SrcCond = MI.getOperand(3).getReg();
3765 
3766     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3767     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3768     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3769     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3770 
3771     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3772       .addReg(SrcCond);
3773     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3774       .addImm(0)
3775       .addReg(Src0, 0, AMDGPU::sub0)
3776       .addImm(0)
3777       .addReg(Src1, 0, AMDGPU::sub0)
3778       .addReg(SrcCondCopy);
3779     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3780       .addImm(0)
3781       .addReg(Src0, 0, AMDGPU::sub1)
3782       .addImm(0)
3783       .addReg(Src1, 0, AMDGPU::sub1)
3784       .addReg(SrcCondCopy);
3785 
3786     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3787       .addReg(DstLo)
3788       .addImm(AMDGPU::sub0)
3789       .addReg(DstHi)
3790       .addImm(AMDGPU::sub1);
3791     MI.eraseFromParent();
3792     return BB;
3793   }
3794   case AMDGPU::SI_BR_UNDEF: {
3795     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3796     const DebugLoc &DL = MI.getDebugLoc();
3797     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3798                            .add(MI.getOperand(0));
3799     Br->getOperand(1).setIsUndef(true); // read undef SCC
3800     MI.eraseFromParent();
3801     return BB;
3802   }
3803   case AMDGPU::ADJCALLSTACKUP:
3804   case AMDGPU::ADJCALLSTACKDOWN: {
3805     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3806     MachineInstrBuilder MIB(*MF, &MI);
3807 
3808     // Add an implicit use of the frame offset reg to prevent the restore copy
3809     // inserted after the call from being reorderd after stack operations in the
3810     // the caller's frame.
3811     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3812         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3813         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3814     return BB;
3815   }
3816   case AMDGPU::SI_CALL_ISEL: {
3817     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3818     const DebugLoc &DL = MI.getDebugLoc();
3819 
3820     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3821 
3822     MachineInstrBuilder MIB;
3823     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3824 
3825     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3826       MIB.add(MI.getOperand(I));
3827 
3828     MIB.cloneMemRefs(MI);
3829     MI.eraseFromParent();
3830     return BB;
3831   }
3832   case AMDGPU::V_ADD_I32_e32:
3833   case AMDGPU::V_SUB_I32_e32:
3834   case AMDGPU::V_SUBREV_I32_e32: {
3835     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3836     const DebugLoc &DL = MI.getDebugLoc();
3837     unsigned Opc = MI.getOpcode();
3838 
3839     bool NeedClampOperand = false;
3840     if (TII->pseudoToMCOpcode(Opc) == -1) {
3841       Opc = AMDGPU::getVOPe64(Opc);
3842       NeedClampOperand = true;
3843     }
3844 
3845     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3846     if (TII->isVOP3(*I)) {
3847       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3848       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3849       I.addReg(TRI->getVCC(), RegState::Define);
3850     }
3851     I.add(MI.getOperand(1))
3852      .add(MI.getOperand(2));
3853     if (NeedClampOperand)
3854       I.addImm(0); // clamp bit for e64 encoding
3855 
3856     TII->legalizeOperands(*I);
3857 
3858     MI.eraseFromParent();
3859     return BB;
3860   }
3861   case AMDGPU::DS_GWS_INIT:
3862   case AMDGPU::DS_GWS_SEMA_V:
3863   case AMDGPU::DS_GWS_SEMA_BR:
3864   case AMDGPU::DS_GWS_SEMA_P:
3865   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3866   case AMDGPU::DS_GWS_BARRIER:
3867     // A s_waitcnt 0 is required to be the instruction immediately following.
3868     if (getSubtarget()->hasGWSAutoReplay()) {
3869       bundleInstWithWaitcnt(MI);
3870       return BB;
3871     }
3872 
3873     return emitGWSMemViolTestLoop(MI, BB);
3874   default:
3875     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3876   }
3877 }
3878 
3879 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3880   return isTypeLegal(VT.getScalarType());
3881 }
3882 
3883 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3884   // This currently forces unfolding various combinations of fsub into fma with
3885   // free fneg'd operands. As long as we have fast FMA (controlled by
3886   // isFMAFasterThanFMulAndFAdd), we should perform these.
3887 
3888   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3889   // most of these combines appear to be cycle neutral but save on instruction
3890   // count / code size.
3891   return true;
3892 }
3893 
3894 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3895                                          EVT VT) const {
3896   if (!VT.isVector()) {
3897     return MVT::i1;
3898   }
3899   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3900 }
3901 
3902 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3903   // TODO: Should i16 be used always if legal? For now it would force VALU
3904   // shifts.
3905   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3906 }
3907 
3908 // Answering this is somewhat tricky and depends on the specific device which
3909 // have different rates for fma or all f64 operations.
3910 //
3911 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3912 // regardless of which device (although the number of cycles differs between
3913 // devices), so it is always profitable for f64.
3914 //
3915 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3916 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3917 // which we can always do even without fused FP ops since it returns the same
3918 // result as the separate operations and since it is always full
3919 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3920 // however does not support denormals, so we do report fma as faster if we have
3921 // a fast fma device and require denormals.
3922 //
3923 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
3924                                                   EVT VT) const {
3925   VT = VT.getScalarType();
3926 
3927   switch (VT.getSimpleVT().SimpleTy) {
3928   case MVT::f32: {
3929     // This is as fast on some subtargets. However, we always have full rate f32
3930     // mad available which returns the same result as the separate operations
3931     // which we should prefer over fma. We can't use this if we want to support
3932     // denormals, so only report this in these cases.
3933     if (hasFP32Denormals(MF))
3934       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3935 
3936     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3937     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3938   }
3939   case MVT::f64:
3940     return true;
3941   case MVT::f16:
3942     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
3943   default:
3944     break;
3945   }
3946 
3947   return false;
3948 }
3949 
3950 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
3951                                    const SDNode *N) const {
3952   // TODO: Check future ftz flag
3953   // v_mad_f32/v_mac_f32 do not support denormals.
3954   EVT VT = N->getValueType(0);
3955   if (VT == MVT::f32)
3956     return !hasFP32Denormals(DAG.getMachineFunction());
3957   if (VT == MVT::f16) {
3958     return Subtarget->hasMadF16() &&
3959            !hasFP64FP16Denormals(DAG.getMachineFunction());
3960   }
3961 
3962   return false;
3963 }
3964 
3965 //===----------------------------------------------------------------------===//
3966 // Custom DAG Lowering Operations
3967 //===----------------------------------------------------------------------===//
3968 
3969 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3970 // wider vector type is legal.
3971 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3972                                              SelectionDAG &DAG) const {
3973   unsigned Opc = Op.getOpcode();
3974   EVT VT = Op.getValueType();
3975   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
3976 
3977   SDValue Lo, Hi;
3978   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3979 
3980   SDLoc SL(Op);
3981   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3982                              Op->getFlags());
3983   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3984                              Op->getFlags());
3985 
3986   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3987 }
3988 
3989 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3990 // wider vector type is legal.
3991 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3992                                               SelectionDAG &DAG) const {
3993   unsigned Opc = Op.getOpcode();
3994   EVT VT = Op.getValueType();
3995   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3996 
3997   SDValue Lo0, Hi0;
3998   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3999   SDValue Lo1, Hi1;
4000   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4001 
4002   SDLoc SL(Op);
4003 
4004   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4005                              Op->getFlags());
4006   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4007                              Op->getFlags());
4008 
4009   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4010 }
4011 
4012 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4013                                               SelectionDAG &DAG) const {
4014   unsigned Opc = Op.getOpcode();
4015   EVT VT = Op.getValueType();
4016   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4017 
4018   SDValue Lo0, Hi0;
4019   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4020   SDValue Lo1, Hi1;
4021   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4022   SDValue Lo2, Hi2;
4023   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4024 
4025   SDLoc SL(Op);
4026 
4027   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4028                              Op->getFlags());
4029   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4030                              Op->getFlags());
4031 
4032   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4033 }
4034 
4035 
4036 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4037   switch (Op.getOpcode()) {
4038   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4039   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4040   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4041   case ISD::LOAD: {
4042     SDValue Result = LowerLOAD(Op, DAG);
4043     assert((!Result.getNode() ||
4044             Result.getNode()->getNumValues() == 2) &&
4045            "Load should return a value and a chain");
4046     return Result;
4047   }
4048 
4049   case ISD::FSIN:
4050   case ISD::FCOS:
4051     return LowerTrig(Op, DAG);
4052   case ISD::SELECT: return LowerSELECT(Op, DAG);
4053   case ISD::FDIV: return LowerFDIV(Op, DAG);
4054   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4055   case ISD::STORE: return LowerSTORE(Op, DAG);
4056   case ISD::GlobalAddress: {
4057     MachineFunction &MF = DAG.getMachineFunction();
4058     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4059     return LowerGlobalAddress(MFI, Op, DAG);
4060   }
4061   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4062   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4063   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4064   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4065   case ISD::INSERT_SUBVECTOR:
4066     return lowerINSERT_SUBVECTOR(Op, DAG);
4067   case ISD::INSERT_VECTOR_ELT:
4068     return lowerINSERT_VECTOR_ELT(Op, DAG);
4069   case ISD::EXTRACT_VECTOR_ELT:
4070     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4071   case ISD::VECTOR_SHUFFLE:
4072     return lowerVECTOR_SHUFFLE(Op, DAG);
4073   case ISD::BUILD_VECTOR:
4074     return lowerBUILD_VECTOR(Op, DAG);
4075   case ISD::FP_ROUND:
4076     return lowerFP_ROUND(Op, DAG);
4077   case ISD::TRAP:
4078     return lowerTRAP(Op, DAG);
4079   case ISD::DEBUGTRAP:
4080     return lowerDEBUGTRAP(Op, DAG);
4081   case ISD::FABS:
4082   case ISD::FNEG:
4083   case ISD::FCANONICALIZE:
4084   case ISD::BSWAP:
4085     return splitUnaryVectorOp(Op, DAG);
4086   case ISD::FMINNUM:
4087   case ISD::FMAXNUM:
4088     return lowerFMINNUM_FMAXNUM(Op, DAG);
4089   case ISD::FMA:
4090     return splitTernaryVectorOp(Op, DAG);
4091   case ISD::SHL:
4092   case ISD::SRA:
4093   case ISD::SRL:
4094   case ISD::ADD:
4095   case ISD::SUB:
4096   case ISD::MUL:
4097   case ISD::SMIN:
4098   case ISD::SMAX:
4099   case ISD::UMIN:
4100   case ISD::UMAX:
4101   case ISD::FADD:
4102   case ISD::FMUL:
4103   case ISD::FMINNUM_IEEE:
4104   case ISD::FMAXNUM_IEEE:
4105     return splitBinaryVectorOp(Op, DAG);
4106   }
4107   return SDValue();
4108 }
4109 
4110 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4111                                        const SDLoc &DL,
4112                                        SelectionDAG &DAG, bool Unpacked) {
4113   if (!LoadVT.isVector())
4114     return Result;
4115 
4116   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4117     // Truncate to v2i16/v4i16.
4118     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4119 
4120     // Workaround legalizer not scalarizing truncate after vector op
4121     // legalization byt not creating intermediate vector trunc.
4122     SmallVector<SDValue, 4> Elts;
4123     DAG.ExtractVectorElements(Result, Elts);
4124     for (SDValue &Elt : Elts)
4125       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4126 
4127     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4128 
4129     // Bitcast to original type (v2f16/v4f16).
4130     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4131   }
4132 
4133   // Cast back to the original packed type.
4134   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4135 }
4136 
4137 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4138                                               MemSDNode *M,
4139                                               SelectionDAG &DAG,
4140                                               ArrayRef<SDValue> Ops,
4141                                               bool IsIntrinsic) const {
4142   SDLoc DL(M);
4143 
4144   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4145   EVT LoadVT = M->getValueType(0);
4146 
4147   EVT EquivLoadVT = LoadVT;
4148   if (Unpacked && LoadVT.isVector()) {
4149     EquivLoadVT = LoadVT.isVector() ?
4150       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4151                        LoadVT.getVectorNumElements()) : LoadVT;
4152   }
4153 
4154   // Change from v4f16/v2f16 to EquivLoadVT.
4155   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4156 
4157   SDValue Load
4158     = DAG.getMemIntrinsicNode(
4159       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4160       VTList, Ops, M->getMemoryVT(),
4161       M->getMemOperand());
4162   if (!Unpacked) // Just adjusted the opcode.
4163     return Load;
4164 
4165   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4166 
4167   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4168 }
4169 
4170 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4171                                              SelectionDAG &DAG,
4172                                              ArrayRef<SDValue> Ops) const {
4173   SDLoc DL(M);
4174   EVT LoadVT = M->getValueType(0);
4175   EVT EltType = LoadVT.getScalarType();
4176   EVT IntVT = LoadVT.changeTypeToInteger();
4177 
4178   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4179 
4180   unsigned Opc =
4181       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4182 
4183   if (IsD16) {
4184     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4185   }
4186 
4187   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4188   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4189     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4190 
4191   if (isTypeLegal(LoadVT)) {
4192     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4193                                M->getMemOperand(), DAG);
4194   }
4195 
4196   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4197   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4198   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4199                                         M->getMemOperand(), DAG);
4200   return DAG.getMergeValues(
4201       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4202       DL);
4203 }
4204 
4205 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4206                                   SDNode *N, SelectionDAG &DAG) {
4207   EVT VT = N->getValueType(0);
4208   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4209   int CondCode = CD->getSExtValue();
4210   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4211       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4212     return DAG.getUNDEF(VT);
4213 
4214   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4215 
4216   SDValue LHS = N->getOperand(1);
4217   SDValue RHS = N->getOperand(2);
4218 
4219   SDLoc DL(N);
4220 
4221   EVT CmpVT = LHS.getValueType();
4222   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4223     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4224       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4225     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4226     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4227   }
4228 
4229   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4230 
4231   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4232   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4233 
4234   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4235                               DAG.getCondCode(CCOpcode));
4236   if (VT.bitsEq(CCVT))
4237     return SetCC;
4238   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4239 }
4240 
4241 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4242                                   SDNode *N, SelectionDAG &DAG) {
4243   EVT VT = N->getValueType(0);
4244   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4245 
4246   int CondCode = CD->getSExtValue();
4247   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4248       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4249     return DAG.getUNDEF(VT);
4250   }
4251 
4252   SDValue Src0 = N->getOperand(1);
4253   SDValue Src1 = N->getOperand(2);
4254   EVT CmpVT = Src0.getValueType();
4255   SDLoc SL(N);
4256 
4257   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4258     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4259     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4260   }
4261 
4262   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4263   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4264   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4265   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4266   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4267                               Src1, DAG.getCondCode(CCOpcode));
4268   if (VT.bitsEq(CCVT))
4269     return SetCC;
4270   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4271 }
4272 
4273 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4274                                     SelectionDAG &DAG) {
4275   EVT VT = N->getValueType(0);
4276   SDValue Src = N->getOperand(1);
4277   SDLoc SL(N);
4278 
4279   if (Src.getOpcode() == ISD::SETCC) {
4280     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4281     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4282                        Src.getOperand(1), Src.getOperand(2));
4283   }
4284   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4285     // (ballot 0) -> 0
4286     if (Arg->isNullValue())
4287       return DAG.getConstant(0, SL, VT);
4288 
4289     // (ballot 1) -> EXEC/EXEC_LO
4290     if (Arg->isOne()) {
4291       Register Exec;
4292       if (VT.getScalarSizeInBits() == 32)
4293         Exec = AMDGPU::EXEC_LO;
4294       else if (VT.getScalarSizeInBits() == 64)
4295         Exec = AMDGPU::EXEC;
4296       else
4297         return SDValue();
4298 
4299       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4300     }
4301   }
4302 
4303   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4304   // ISD::SETNE)
4305   return DAG.getNode(
4306       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4307       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4308 }
4309 
4310 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4311                                           SmallVectorImpl<SDValue> &Results,
4312                                           SelectionDAG &DAG) const {
4313   switch (N->getOpcode()) {
4314   case ISD::INSERT_VECTOR_ELT: {
4315     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4316       Results.push_back(Res);
4317     return;
4318   }
4319   case ISD::EXTRACT_VECTOR_ELT: {
4320     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4321       Results.push_back(Res);
4322     return;
4323   }
4324   case ISD::INTRINSIC_WO_CHAIN: {
4325     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4326     switch (IID) {
4327     case Intrinsic::amdgcn_cvt_pkrtz: {
4328       SDValue Src0 = N->getOperand(1);
4329       SDValue Src1 = N->getOperand(2);
4330       SDLoc SL(N);
4331       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4332                                 Src0, Src1);
4333       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4334       return;
4335     }
4336     case Intrinsic::amdgcn_cvt_pknorm_i16:
4337     case Intrinsic::amdgcn_cvt_pknorm_u16:
4338     case Intrinsic::amdgcn_cvt_pk_i16:
4339     case Intrinsic::amdgcn_cvt_pk_u16: {
4340       SDValue Src0 = N->getOperand(1);
4341       SDValue Src1 = N->getOperand(2);
4342       SDLoc SL(N);
4343       unsigned Opcode;
4344 
4345       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4346         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4347       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4348         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4349       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4350         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4351       else
4352         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4353 
4354       EVT VT = N->getValueType(0);
4355       if (isTypeLegal(VT))
4356         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4357       else {
4358         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4359         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4360       }
4361       return;
4362     }
4363     }
4364     break;
4365   }
4366   case ISD::INTRINSIC_W_CHAIN: {
4367     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4368       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4369         // FIXME: Hacky
4370         Results.push_back(Res.getOperand(0));
4371         Results.push_back(Res.getOperand(1));
4372       } else {
4373         Results.push_back(Res);
4374         Results.push_back(Res.getValue(1));
4375       }
4376       return;
4377     }
4378 
4379     break;
4380   }
4381   case ISD::SELECT: {
4382     SDLoc SL(N);
4383     EVT VT = N->getValueType(0);
4384     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4385     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4386     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4387 
4388     EVT SelectVT = NewVT;
4389     if (NewVT.bitsLT(MVT::i32)) {
4390       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4391       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4392       SelectVT = MVT::i32;
4393     }
4394 
4395     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4396                                     N->getOperand(0), LHS, RHS);
4397 
4398     if (NewVT != SelectVT)
4399       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4400     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4401     return;
4402   }
4403   case ISD::FNEG: {
4404     if (N->getValueType(0) != MVT::v2f16)
4405       break;
4406 
4407     SDLoc SL(N);
4408     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4409 
4410     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4411                              BC,
4412                              DAG.getConstant(0x80008000, SL, MVT::i32));
4413     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4414     return;
4415   }
4416   case ISD::FABS: {
4417     if (N->getValueType(0) != MVT::v2f16)
4418       break;
4419 
4420     SDLoc SL(N);
4421     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4422 
4423     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4424                              BC,
4425                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4426     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4427     return;
4428   }
4429   default:
4430     break;
4431   }
4432 }
4433 
4434 /// Helper function for LowerBRCOND
4435 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4436 
4437   SDNode *Parent = Value.getNode();
4438   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4439        I != E; ++I) {
4440 
4441     if (I.getUse().get() != Value)
4442       continue;
4443 
4444     if (I->getOpcode() == Opcode)
4445       return *I;
4446   }
4447   return nullptr;
4448 }
4449 
4450 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4451   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4452     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4453     case Intrinsic::amdgcn_if:
4454       return AMDGPUISD::IF;
4455     case Intrinsic::amdgcn_else:
4456       return AMDGPUISD::ELSE;
4457     case Intrinsic::amdgcn_loop:
4458       return AMDGPUISD::LOOP;
4459     case Intrinsic::amdgcn_end_cf:
4460       llvm_unreachable("should not occur");
4461     default:
4462       return 0;
4463     }
4464   }
4465 
4466   // break, if_break, else_break are all only used as inputs to loop, not
4467   // directly as branch conditions.
4468   return 0;
4469 }
4470 
4471 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4472   const Triple &TT = getTargetMachine().getTargetTriple();
4473   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4474           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4475          AMDGPU::shouldEmitConstantsToTextSection(TT);
4476 }
4477 
4478 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4479   // FIXME: Either avoid relying on address space here or change the default
4480   // address space for functions to avoid the explicit check.
4481   return (GV->getValueType()->isFunctionTy() ||
4482           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4483          !shouldEmitFixup(GV) &&
4484          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4485 }
4486 
4487 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4488   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4489 }
4490 
4491 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4492   if (!GV->hasExternalLinkage())
4493     return true;
4494 
4495   const auto OS = getTargetMachine().getTargetTriple().getOS();
4496   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4497 }
4498 
4499 /// This transforms the control flow intrinsics to get the branch destination as
4500 /// last parameter, also switches branch target with BR if the need arise
4501 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4502                                       SelectionDAG &DAG) const {
4503   SDLoc DL(BRCOND);
4504 
4505   SDNode *Intr = BRCOND.getOperand(1).getNode();
4506   SDValue Target = BRCOND.getOperand(2);
4507   SDNode *BR = nullptr;
4508   SDNode *SetCC = nullptr;
4509 
4510   if (Intr->getOpcode() == ISD::SETCC) {
4511     // As long as we negate the condition everything is fine
4512     SetCC = Intr;
4513     Intr = SetCC->getOperand(0).getNode();
4514 
4515   } else {
4516     // Get the target from BR if we don't negate the condition
4517     BR = findUser(BRCOND, ISD::BR);
4518     Target = BR->getOperand(1);
4519   }
4520 
4521   // FIXME: This changes the types of the intrinsics instead of introducing new
4522   // nodes with the correct types.
4523   // e.g. llvm.amdgcn.loop
4524 
4525   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4526   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4527 
4528   unsigned CFNode = isCFIntrinsic(Intr);
4529   if (CFNode == 0) {
4530     // This is a uniform branch so we don't need to legalize.
4531     return BRCOND;
4532   }
4533 
4534   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4535                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4536 
4537   assert(!SetCC ||
4538         (SetCC->getConstantOperandVal(1) == 1 &&
4539          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4540                                                              ISD::SETNE));
4541 
4542   // operands of the new intrinsic call
4543   SmallVector<SDValue, 4> Ops;
4544   if (HaveChain)
4545     Ops.push_back(BRCOND.getOperand(0));
4546 
4547   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4548   Ops.push_back(Target);
4549 
4550   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4551 
4552   // build the new intrinsic call
4553   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4554 
4555   if (!HaveChain) {
4556     SDValue Ops[] =  {
4557       SDValue(Result, 0),
4558       BRCOND.getOperand(0)
4559     };
4560 
4561     Result = DAG.getMergeValues(Ops, DL).getNode();
4562   }
4563 
4564   if (BR) {
4565     // Give the branch instruction our target
4566     SDValue Ops[] = {
4567       BR->getOperand(0),
4568       BRCOND.getOperand(2)
4569     };
4570     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4571     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4572   }
4573 
4574   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4575 
4576   // Copy the intrinsic results to registers
4577   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4578     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4579     if (!CopyToReg)
4580       continue;
4581 
4582     Chain = DAG.getCopyToReg(
4583       Chain, DL,
4584       CopyToReg->getOperand(1),
4585       SDValue(Result, i - 1),
4586       SDValue());
4587 
4588     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4589   }
4590 
4591   // Remove the old intrinsic from the chain
4592   DAG.ReplaceAllUsesOfValueWith(
4593     SDValue(Intr, Intr->getNumValues() - 1),
4594     Intr->getOperand(0));
4595 
4596   return Chain;
4597 }
4598 
4599 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4600                                           SelectionDAG &DAG) const {
4601   MVT VT = Op.getSimpleValueType();
4602   SDLoc DL(Op);
4603   // Checking the depth
4604   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4605     return DAG.getConstant(0, DL, VT);
4606 
4607   MachineFunction &MF = DAG.getMachineFunction();
4608   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4609   // Check for kernel and shader functions
4610   if (Info->isEntryFunction())
4611     return DAG.getConstant(0, DL, VT);
4612 
4613   MachineFrameInfo &MFI = MF.getFrameInfo();
4614   // There is a call to @llvm.returnaddress in this function
4615   MFI.setReturnAddressIsTaken(true);
4616 
4617   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4618   // Get the return address reg and mark it as an implicit live-in
4619   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4620 
4621   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4622 }
4623 
4624 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4625                                             SDValue Op,
4626                                             const SDLoc &DL,
4627                                             EVT VT) const {
4628   return Op.getValueType().bitsLE(VT) ?
4629       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4630     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4631                 DAG.getTargetConstant(0, DL, MVT::i32));
4632 }
4633 
4634 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4635   assert(Op.getValueType() == MVT::f16 &&
4636          "Do not know how to custom lower FP_ROUND for non-f16 type");
4637 
4638   SDValue Src = Op.getOperand(0);
4639   EVT SrcVT = Src.getValueType();
4640   if (SrcVT != MVT::f64)
4641     return Op;
4642 
4643   SDLoc DL(Op);
4644 
4645   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4646   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4647   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4648 }
4649 
4650 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4651                                                SelectionDAG &DAG) const {
4652   EVT VT = Op.getValueType();
4653   const MachineFunction &MF = DAG.getMachineFunction();
4654   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4655   bool IsIEEEMode = Info->getMode().IEEE;
4656 
4657   // FIXME: Assert during selection that this is only selected for
4658   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4659   // mode functions, but this happens to be OK since it's only done in cases
4660   // where there is known no sNaN.
4661   if (IsIEEEMode)
4662     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4663 
4664   if (VT == MVT::v4f16)
4665     return splitBinaryVectorOp(Op, DAG);
4666   return Op;
4667 }
4668 
4669 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4670   SDLoc SL(Op);
4671   SDValue Chain = Op.getOperand(0);
4672 
4673   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4674       !Subtarget->isTrapHandlerEnabled())
4675     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4676 
4677   MachineFunction &MF = DAG.getMachineFunction();
4678   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4679   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4680   assert(UserSGPR != AMDGPU::NoRegister);
4681   SDValue QueuePtr = CreateLiveInRegister(
4682     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4683   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4684   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4685                                    QueuePtr, SDValue());
4686   SDValue Ops[] = {
4687     ToReg,
4688     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4689     SGPR01,
4690     ToReg.getValue(1)
4691   };
4692   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4693 }
4694 
4695 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4696   SDLoc SL(Op);
4697   SDValue Chain = Op.getOperand(0);
4698   MachineFunction &MF = DAG.getMachineFunction();
4699 
4700   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4701       !Subtarget->isTrapHandlerEnabled()) {
4702     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4703                                      "debugtrap handler not supported",
4704                                      Op.getDebugLoc(),
4705                                      DS_Warning);
4706     LLVMContext &Ctx = MF.getFunction().getContext();
4707     Ctx.diagnose(NoTrap);
4708     return Chain;
4709   }
4710 
4711   SDValue Ops[] = {
4712     Chain,
4713     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4714   };
4715   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4716 }
4717 
4718 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4719                                              SelectionDAG &DAG) const {
4720   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4721   if (Subtarget->hasApertureRegs()) {
4722     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4723         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4724         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4725     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4726         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4727         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4728     unsigned Encoding =
4729         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4730         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4731         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4732 
4733     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4734     SDValue ApertureReg = SDValue(
4735         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4736     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4737     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4738   }
4739 
4740   MachineFunction &MF = DAG.getMachineFunction();
4741   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4742   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4743   assert(UserSGPR != AMDGPU::NoRegister);
4744 
4745   SDValue QueuePtr = CreateLiveInRegister(
4746     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4747 
4748   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4749   // private_segment_aperture_base_hi.
4750   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4751 
4752   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4753 
4754   // TODO: Use custom target PseudoSourceValue.
4755   // TODO: We should use the value from the IR intrinsic call, but it might not
4756   // be available and how do we get it?
4757   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4758   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4759                      MinAlign(64, StructOffset),
4760                      MachineMemOperand::MODereferenceable |
4761                          MachineMemOperand::MOInvariant);
4762 }
4763 
4764 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4765                                              SelectionDAG &DAG) const {
4766   SDLoc SL(Op);
4767   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4768 
4769   SDValue Src = ASC->getOperand(0);
4770   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4771 
4772   const AMDGPUTargetMachine &TM =
4773     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4774 
4775   // flat -> local/private
4776   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4777     unsigned DestAS = ASC->getDestAddressSpace();
4778 
4779     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4780         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4781       unsigned NullVal = TM.getNullPointerValue(DestAS);
4782       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4783       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4784       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4785 
4786       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4787                          NonNull, Ptr, SegmentNullPtr);
4788     }
4789   }
4790 
4791   // local/private -> flat
4792   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4793     unsigned SrcAS = ASC->getSrcAddressSpace();
4794 
4795     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4796         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4797       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4798       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4799 
4800       SDValue NonNull
4801         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4802 
4803       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4804       SDValue CvtPtr
4805         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4806 
4807       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4808                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4809                          FlatNullPtr);
4810     }
4811   }
4812 
4813   // global <-> flat are no-ops and never emitted.
4814 
4815   const MachineFunction &MF = DAG.getMachineFunction();
4816   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4817     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4818   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4819 
4820   return DAG.getUNDEF(ASC->getValueType(0));
4821 }
4822 
4823 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4824 // the small vector and inserting them into the big vector. That is better than
4825 // the default expansion of doing it via a stack slot. Even though the use of
4826 // the stack slot would be optimized away afterwards, the stack slot itself
4827 // remains.
4828 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4829                                                 SelectionDAG &DAG) const {
4830   SDValue Vec = Op.getOperand(0);
4831   SDValue Ins = Op.getOperand(1);
4832   SDValue Idx = Op.getOperand(2);
4833   EVT VecVT = Vec.getValueType();
4834   EVT InsVT = Ins.getValueType();
4835   EVT EltVT = VecVT.getVectorElementType();
4836   unsigned InsNumElts = InsVT.getVectorNumElements();
4837   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4838   SDLoc SL(Op);
4839 
4840   for (unsigned I = 0; I != InsNumElts; ++I) {
4841     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4842                               DAG.getConstant(I, SL, MVT::i32));
4843     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4844                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4845   }
4846   return Vec;
4847 }
4848 
4849 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4850                                                  SelectionDAG &DAG) const {
4851   SDValue Vec = Op.getOperand(0);
4852   SDValue InsVal = Op.getOperand(1);
4853   SDValue Idx = Op.getOperand(2);
4854   EVT VecVT = Vec.getValueType();
4855   EVT EltVT = VecVT.getVectorElementType();
4856   unsigned VecSize = VecVT.getSizeInBits();
4857   unsigned EltSize = EltVT.getSizeInBits();
4858 
4859 
4860   assert(VecSize <= 64);
4861 
4862   unsigned NumElts = VecVT.getVectorNumElements();
4863   SDLoc SL(Op);
4864   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4865 
4866   if (NumElts == 4 && EltSize == 16 && KIdx) {
4867     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4868 
4869     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4870                                  DAG.getConstant(0, SL, MVT::i32));
4871     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4872                                  DAG.getConstant(1, SL, MVT::i32));
4873 
4874     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4875     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4876 
4877     unsigned Idx = KIdx->getZExtValue();
4878     bool InsertLo = Idx < 2;
4879     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4880       InsertLo ? LoVec : HiVec,
4881       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4882       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4883 
4884     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4885 
4886     SDValue Concat = InsertLo ?
4887       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4888       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4889 
4890     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4891   }
4892 
4893   if (isa<ConstantSDNode>(Idx))
4894     return SDValue();
4895 
4896   MVT IntVT = MVT::getIntegerVT(VecSize);
4897 
4898   // Avoid stack access for dynamic indexing.
4899   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4900 
4901   // Create a congruent vector with the target value in each element so that
4902   // the required element can be masked and ORed into the target vector.
4903   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4904                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4905 
4906   assert(isPowerOf2_32(EltSize));
4907   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4908 
4909   // Convert vector index to bit-index.
4910   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4911 
4912   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4913   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4914                             DAG.getConstant(0xffff, SL, IntVT),
4915                             ScaledIdx);
4916 
4917   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4918   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4919                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4920 
4921   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4922   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4923 }
4924 
4925 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4926                                                   SelectionDAG &DAG) const {
4927   SDLoc SL(Op);
4928 
4929   EVT ResultVT = Op.getValueType();
4930   SDValue Vec = Op.getOperand(0);
4931   SDValue Idx = Op.getOperand(1);
4932   EVT VecVT = Vec.getValueType();
4933   unsigned VecSize = VecVT.getSizeInBits();
4934   EVT EltVT = VecVT.getVectorElementType();
4935   assert(VecSize <= 64);
4936 
4937   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4938 
4939   // Make sure we do any optimizations that will make it easier to fold
4940   // source modifiers before obscuring it with bit operations.
4941 
4942   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4943   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4944     return Combined;
4945 
4946   unsigned EltSize = EltVT.getSizeInBits();
4947   assert(isPowerOf2_32(EltSize));
4948 
4949   MVT IntVT = MVT::getIntegerVT(VecSize);
4950   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4951 
4952   // Convert vector index to bit-index (* EltSize)
4953   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4954 
4955   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4956   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4957 
4958   if (ResultVT == MVT::f16) {
4959     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4960     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4961   }
4962 
4963   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4964 }
4965 
4966 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4967   assert(Elt % 2 == 0);
4968   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4969 }
4970 
4971 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4972                                               SelectionDAG &DAG) const {
4973   SDLoc SL(Op);
4974   EVT ResultVT = Op.getValueType();
4975   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4976 
4977   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4978   EVT EltVT = PackVT.getVectorElementType();
4979   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4980 
4981   // vector_shuffle <0,1,6,7> lhs, rhs
4982   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4983   //
4984   // vector_shuffle <6,7,2,3> lhs, rhs
4985   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4986   //
4987   // vector_shuffle <6,7,0,1> lhs, rhs
4988   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4989 
4990   // Avoid scalarizing when both halves are reading from consecutive elements.
4991   SmallVector<SDValue, 4> Pieces;
4992   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4993     if (elementPairIsContiguous(SVN->getMask(), I)) {
4994       const int Idx = SVN->getMaskElt(I);
4995       int VecIdx = Idx < SrcNumElts ? 0 : 1;
4996       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4997       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4998                                     PackVT, SVN->getOperand(VecIdx),
4999                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5000       Pieces.push_back(SubVec);
5001     } else {
5002       const int Idx0 = SVN->getMaskElt(I);
5003       const int Idx1 = SVN->getMaskElt(I + 1);
5004       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5005       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5006       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5007       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5008 
5009       SDValue Vec0 = SVN->getOperand(VecIdx0);
5010       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5011                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5012 
5013       SDValue Vec1 = SVN->getOperand(VecIdx1);
5014       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5015                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5016       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5017     }
5018   }
5019 
5020   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5021 }
5022 
5023 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5024                                             SelectionDAG &DAG) const {
5025   SDLoc SL(Op);
5026   EVT VT = Op.getValueType();
5027 
5028   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5029     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5030 
5031     // Turn into pair of packed build_vectors.
5032     // TODO: Special case for constants that can be materialized with s_mov_b64.
5033     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5034                                     { Op.getOperand(0), Op.getOperand(1) });
5035     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5036                                     { Op.getOperand(2), Op.getOperand(3) });
5037 
5038     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5039     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5040 
5041     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5042     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5043   }
5044 
5045   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5046   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5047 
5048   SDValue Lo = Op.getOperand(0);
5049   SDValue Hi = Op.getOperand(1);
5050 
5051   // Avoid adding defined bits with the zero_extend.
5052   if (Hi.isUndef()) {
5053     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5054     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5055     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5056   }
5057 
5058   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5059   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5060 
5061   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5062                               DAG.getConstant(16, SL, MVT::i32));
5063   if (Lo.isUndef())
5064     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5065 
5066   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5067   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5068 
5069   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5070   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5071 }
5072 
5073 bool
5074 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5075   // We can fold offsets for anything that doesn't require a GOT relocation.
5076   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5077           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5078           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5079          !shouldEmitGOTReloc(GA->getGlobal());
5080 }
5081 
5082 static SDValue
5083 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5084                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5085                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5086   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5087   // lowered to the following code sequence:
5088   //
5089   // For constant address space:
5090   //   s_getpc_b64 s[0:1]
5091   //   s_add_u32 s0, s0, $symbol
5092   //   s_addc_u32 s1, s1, 0
5093   //
5094   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5095   //   a fixup or relocation is emitted to replace $symbol with a literal
5096   //   constant, which is a pc-relative offset from the encoding of the $symbol
5097   //   operand to the global variable.
5098   //
5099   // For global address space:
5100   //   s_getpc_b64 s[0:1]
5101   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5102   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5103   //
5104   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5105   //   fixups or relocations are emitted to replace $symbol@*@lo and
5106   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5107   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5108   //   operand to the global variable.
5109   //
5110   // What we want here is an offset from the value returned by s_getpc
5111   // (which is the address of the s_add_u32 instruction) to the global
5112   // variable, but since the encoding of $symbol starts 4 bytes after the start
5113   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5114   // small. This requires us to add 4 to the global variable offset in order to
5115   // compute the correct address.
5116   SDValue PtrLo =
5117       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5118   SDValue PtrHi;
5119   if (GAFlags == SIInstrInfo::MO_NONE) {
5120     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5121   } else {
5122     PtrHi =
5123         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5124   }
5125   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5126 }
5127 
5128 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5129                                              SDValue Op,
5130                                              SelectionDAG &DAG) const {
5131   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5132   const GlobalValue *GV = GSD->getGlobal();
5133   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5134        shouldUseLDSConstAddress(GV)) ||
5135       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5136       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5137     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5138 
5139   SDLoc DL(GSD);
5140   EVT PtrVT = Op.getValueType();
5141 
5142   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5143     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5144                                             SIInstrInfo::MO_ABS32_LO);
5145     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5146   }
5147 
5148   if (shouldEmitFixup(GV))
5149     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5150   else if (shouldEmitPCReloc(GV))
5151     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5152                                    SIInstrInfo::MO_REL32);
5153 
5154   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5155                                             SIInstrInfo::MO_GOTPCREL32);
5156 
5157   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5158   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5159   const DataLayout &DataLayout = DAG.getDataLayout();
5160   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5161   MachinePointerInfo PtrInfo
5162     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5163 
5164   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5165                      MachineMemOperand::MODereferenceable |
5166                          MachineMemOperand::MOInvariant);
5167 }
5168 
5169 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5170                                    const SDLoc &DL, SDValue V) const {
5171   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5172   // the destination register.
5173   //
5174   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5175   // so we will end up with redundant moves to m0.
5176   //
5177   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5178 
5179   // A Null SDValue creates a glue result.
5180   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5181                                   V, Chain);
5182   return SDValue(M0, 0);
5183 }
5184 
5185 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5186                                                  SDValue Op,
5187                                                  MVT VT,
5188                                                  unsigned Offset) const {
5189   SDLoc SL(Op);
5190   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5191                                            DAG.getEntryNode(), Offset, 4, false);
5192   // The local size values will have the hi 16-bits as zero.
5193   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5194                      DAG.getValueType(VT));
5195 }
5196 
5197 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5198                                         EVT VT) {
5199   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5200                                       "non-hsa intrinsic with hsa target",
5201                                       DL.getDebugLoc());
5202   DAG.getContext()->diagnose(BadIntrin);
5203   return DAG.getUNDEF(VT);
5204 }
5205 
5206 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5207                                          EVT VT) {
5208   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5209                                       "intrinsic not supported on subtarget",
5210                                       DL.getDebugLoc());
5211   DAG.getContext()->diagnose(BadIntrin);
5212   return DAG.getUNDEF(VT);
5213 }
5214 
5215 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5216                                     ArrayRef<SDValue> Elts) {
5217   assert(!Elts.empty());
5218   MVT Type;
5219   unsigned NumElts;
5220 
5221   if (Elts.size() == 1) {
5222     Type = MVT::f32;
5223     NumElts = 1;
5224   } else if (Elts.size() == 2) {
5225     Type = MVT::v2f32;
5226     NumElts = 2;
5227   } else if (Elts.size() == 3) {
5228     Type = MVT::v3f32;
5229     NumElts = 3;
5230   } else if (Elts.size() <= 4) {
5231     Type = MVT::v4f32;
5232     NumElts = 4;
5233   } else if (Elts.size() <= 8) {
5234     Type = MVT::v8f32;
5235     NumElts = 8;
5236   } else {
5237     assert(Elts.size() <= 16);
5238     Type = MVT::v16f32;
5239     NumElts = 16;
5240   }
5241 
5242   SmallVector<SDValue, 16> VecElts(NumElts);
5243   for (unsigned i = 0; i < Elts.size(); ++i) {
5244     SDValue Elt = Elts[i];
5245     if (Elt.getValueType() != MVT::f32)
5246       Elt = DAG.getBitcast(MVT::f32, Elt);
5247     VecElts[i] = Elt;
5248   }
5249   for (unsigned i = Elts.size(); i < NumElts; ++i)
5250     VecElts[i] = DAG.getUNDEF(MVT::f32);
5251 
5252   if (NumElts == 1)
5253     return VecElts[0];
5254   return DAG.getBuildVector(Type, DL, VecElts);
5255 }
5256 
5257 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5258                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5259   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5260 
5261   uint64_t Value = CachePolicyConst->getZExtValue();
5262   SDLoc DL(CachePolicy);
5263   if (GLC) {
5264     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5265     Value &= ~(uint64_t)0x1;
5266   }
5267   if (SLC) {
5268     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5269     Value &= ~(uint64_t)0x2;
5270   }
5271   if (DLC) {
5272     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5273     Value &= ~(uint64_t)0x4;
5274   }
5275 
5276   return Value == 0;
5277 }
5278 
5279 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5280                               SDValue Src, int ExtraElts) {
5281   EVT SrcVT = Src.getValueType();
5282 
5283   SmallVector<SDValue, 8> Elts;
5284 
5285   if (SrcVT.isVector())
5286     DAG.ExtractVectorElements(Src, Elts);
5287   else
5288     Elts.push_back(Src);
5289 
5290   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5291   while (ExtraElts--)
5292     Elts.push_back(Undef);
5293 
5294   return DAG.getBuildVector(CastVT, DL, Elts);
5295 }
5296 
5297 // Re-construct the required return value for a image load intrinsic.
5298 // This is more complicated due to the optional use TexFailCtrl which means the required
5299 // return type is an aggregate
5300 static SDValue constructRetValue(SelectionDAG &DAG,
5301                                  MachineSDNode *Result,
5302                                  ArrayRef<EVT> ResultTypes,
5303                                  bool IsTexFail, bool Unpacked, bool IsD16,
5304                                  int DMaskPop, int NumVDataDwords,
5305                                  const SDLoc &DL, LLVMContext &Context) {
5306   // Determine the required return type. This is the same regardless of IsTexFail flag
5307   EVT ReqRetVT = ResultTypes[0];
5308   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5309   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5310     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5311 
5312   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5313     DMaskPop : (DMaskPop + 1) / 2;
5314 
5315   MVT DataDwordVT = NumDataDwords == 1 ?
5316     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5317 
5318   MVT MaskPopVT = MaskPopDwords == 1 ?
5319     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5320 
5321   SDValue Data(Result, 0);
5322   SDValue TexFail;
5323 
5324   if (IsTexFail) {
5325     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5326     if (MaskPopVT.isVector()) {
5327       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5328                          SDValue(Result, 0), ZeroIdx);
5329     } else {
5330       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5331                          SDValue(Result, 0), ZeroIdx);
5332     }
5333 
5334     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5335                           SDValue(Result, 0),
5336                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5337   }
5338 
5339   if (DataDwordVT.isVector())
5340     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5341                           NumDataDwords - MaskPopDwords);
5342 
5343   if (IsD16)
5344     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5345 
5346   if (!ReqRetVT.isVector())
5347     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5348 
5349   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5350 
5351   if (TexFail)
5352     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5353 
5354   if (Result->getNumValues() == 1)
5355     return Data;
5356 
5357   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5358 }
5359 
5360 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5361                          SDValue *LWE, bool &IsTexFail) {
5362   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5363 
5364   uint64_t Value = TexFailCtrlConst->getZExtValue();
5365   if (Value) {
5366     IsTexFail = true;
5367   }
5368 
5369   SDLoc DL(TexFailCtrlConst);
5370   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5371   Value &= ~(uint64_t)0x1;
5372   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5373   Value &= ~(uint64_t)0x2;
5374 
5375   return Value == 0;
5376 }
5377 
5378 SDValue SITargetLowering::lowerImage(SDValue Op,
5379                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5380                                      SelectionDAG &DAG) const {
5381   SDLoc DL(Op);
5382   MachineFunction &MF = DAG.getMachineFunction();
5383   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5384   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5385       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5386   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5387   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5388       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5389   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5390       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5391   unsigned IntrOpcode = Intr->BaseOpcode;
5392   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5393 
5394   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5395   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5396   bool IsD16 = false;
5397   bool IsA16 = false;
5398   SDValue VData;
5399   int NumVDataDwords;
5400   bool AdjustRetType = false;
5401 
5402   unsigned AddrIdx; // Index of first address argument
5403   unsigned DMask;
5404   unsigned DMaskLanes = 0;
5405 
5406   if (BaseOpcode->Atomic) {
5407     VData = Op.getOperand(2);
5408 
5409     bool Is64Bit = VData.getValueType() == MVT::i64;
5410     if (BaseOpcode->AtomicX2) {
5411       SDValue VData2 = Op.getOperand(3);
5412       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5413                                  {VData, VData2});
5414       if (Is64Bit)
5415         VData = DAG.getBitcast(MVT::v4i32, VData);
5416 
5417       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5418       DMask = Is64Bit ? 0xf : 0x3;
5419       NumVDataDwords = Is64Bit ? 4 : 2;
5420       AddrIdx = 4;
5421     } else {
5422       DMask = Is64Bit ? 0x3 : 0x1;
5423       NumVDataDwords = Is64Bit ? 2 : 1;
5424       AddrIdx = 3;
5425     }
5426   } else {
5427     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5428     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5429     DMask = DMaskConst->getZExtValue();
5430     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5431 
5432     if (BaseOpcode->Store) {
5433       VData = Op.getOperand(2);
5434 
5435       MVT StoreVT = VData.getSimpleValueType();
5436       if (StoreVT.getScalarType() == MVT::f16) {
5437         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5438           return Op; // D16 is unsupported for this instruction
5439 
5440         IsD16 = true;
5441         VData = handleD16VData(VData, DAG);
5442       }
5443 
5444       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5445     } else {
5446       // Work out the num dwords based on the dmask popcount and underlying type
5447       // and whether packing is supported.
5448       MVT LoadVT = ResultTypes[0].getSimpleVT();
5449       if (LoadVT.getScalarType() == MVT::f16) {
5450         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5451           return Op; // D16 is unsupported for this instruction
5452 
5453         IsD16 = true;
5454       }
5455 
5456       // Confirm that the return type is large enough for the dmask specified
5457       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5458           (!LoadVT.isVector() && DMaskLanes > 1))
5459           return Op;
5460 
5461       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5462         NumVDataDwords = (DMaskLanes + 1) / 2;
5463       else
5464         NumVDataDwords = DMaskLanes;
5465 
5466       AdjustRetType = true;
5467     }
5468 
5469     AddrIdx = DMaskIdx + 1;
5470   }
5471 
5472   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5473   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5474   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5475   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5476                        NumCoords + NumLCM;
5477   unsigned NumMIVAddrs = NumVAddrs;
5478 
5479   SmallVector<SDValue, 4> VAddrs;
5480 
5481   // Optimize _L to _LZ when _L is zero
5482   if (LZMappingInfo) {
5483     if (auto ConstantLod =
5484          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5485       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5486         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5487         NumMIVAddrs--;               // remove 'lod'
5488       }
5489     }
5490   }
5491 
5492   // Optimize _mip away, when 'lod' is zero
5493   if (MIPMappingInfo) {
5494     if (auto ConstantLod =
5495          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5496       if (ConstantLod->isNullValue()) {
5497         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5498         NumMIVAddrs--;               // remove 'lod'
5499       }
5500     }
5501   }
5502 
5503   // Check for 16 bit addresses and pack if true.
5504   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5505   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5506   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5507   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5508     // Illegal to use a16 images
5509     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5510       return Op;
5511 
5512     IsA16 = true;
5513     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5514     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5515       SDValue AddrLo;
5516       // Push back extra arguments.
5517       if (i < DimIdx) {
5518         AddrLo = Op.getOperand(i);
5519       } else {
5520         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5521         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5522         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5523             ((NumGradients / 2) % 2 == 1 &&
5524             (i == DimIdx + (NumGradients / 2) - 1 ||
5525              i == DimIdx + NumGradients - 1))) {
5526           AddrLo = Op.getOperand(i);
5527           if (AddrLo.getValueType() != MVT::i16)
5528             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5529           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5530         } else {
5531           AddrLo = DAG.getBuildVector(VectorVT, DL,
5532                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5533           i++;
5534         }
5535         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5536       }
5537       VAddrs.push_back(AddrLo);
5538     }
5539   } else {
5540     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5541       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5542   }
5543 
5544   // If the register allocator cannot place the address registers contiguously
5545   // without introducing moves, then using the non-sequential address encoding
5546   // is always preferable, since it saves VALU instructions and is usually a
5547   // wash in terms of code size or even better.
5548   //
5549   // However, we currently have no way of hinting to the register allocator that
5550   // MIMG addresses should be placed contiguously when it is possible to do so,
5551   // so force non-NSA for the common 2-address case as a heuristic.
5552   //
5553   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5554   // allocation when possible.
5555   bool UseNSA =
5556       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5557   SDValue VAddr;
5558   if (!UseNSA)
5559     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5560 
5561   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5562   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5563   unsigned CtrlIdx; // Index of texfailctrl argument
5564   SDValue Unorm;
5565   if (!BaseOpcode->Sampler) {
5566     Unorm = True;
5567     CtrlIdx = AddrIdx + NumVAddrs + 1;
5568   } else {
5569     auto UnormConst =
5570         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5571 
5572     Unorm = UnormConst->getZExtValue() ? True : False;
5573     CtrlIdx = AddrIdx + NumVAddrs + 3;
5574   }
5575 
5576   SDValue TFE;
5577   SDValue LWE;
5578   SDValue TexFail = Op.getOperand(CtrlIdx);
5579   bool IsTexFail = false;
5580   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5581     return Op;
5582 
5583   if (IsTexFail) {
5584     if (!DMaskLanes) {
5585       // Expecting to get an error flag since TFC is on - and dmask is 0
5586       // Force dmask to be at least 1 otherwise the instruction will fail
5587       DMask = 0x1;
5588       DMaskLanes = 1;
5589       NumVDataDwords = 1;
5590     }
5591     NumVDataDwords += 1;
5592     AdjustRetType = true;
5593   }
5594 
5595   // Has something earlier tagged that the return type needs adjusting
5596   // This happens if the instruction is a load or has set TexFailCtrl flags
5597   if (AdjustRetType) {
5598     // NumVDataDwords reflects the true number of dwords required in the return type
5599     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5600       // This is a no-op load. This can be eliminated
5601       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5602       if (isa<MemSDNode>(Op))
5603         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5604       return Undef;
5605     }
5606 
5607     EVT NewVT = NumVDataDwords > 1 ?
5608                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5609                 : MVT::i32;
5610 
5611     ResultTypes[0] = NewVT;
5612     if (ResultTypes.size() == 3) {
5613       // Original result was aggregate type used for TexFailCtrl results
5614       // The actual instruction returns as a vector type which has now been
5615       // created. Remove the aggregate result.
5616       ResultTypes.erase(&ResultTypes[1]);
5617     }
5618   }
5619 
5620   SDValue GLC;
5621   SDValue SLC;
5622   SDValue DLC;
5623   if (BaseOpcode->Atomic) {
5624     GLC = True; // TODO no-return optimization
5625     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5626                           IsGFX10 ? &DLC : nullptr))
5627       return Op;
5628   } else {
5629     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5630                           IsGFX10 ? &DLC : nullptr))
5631       return Op;
5632   }
5633 
5634   SmallVector<SDValue, 26> Ops;
5635   if (BaseOpcode->Store || BaseOpcode->Atomic)
5636     Ops.push_back(VData); // vdata
5637   if (UseNSA) {
5638     for (const SDValue &Addr : VAddrs)
5639       Ops.push_back(Addr);
5640   } else {
5641     Ops.push_back(VAddr);
5642   }
5643   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5644   if (BaseOpcode->Sampler)
5645     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5646   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5647   if (IsGFX10)
5648     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5649   Ops.push_back(Unorm);
5650   if (IsGFX10)
5651     Ops.push_back(DLC);
5652   Ops.push_back(GLC);
5653   Ops.push_back(SLC);
5654   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5655                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5656   if (IsGFX10)
5657     Ops.push_back(IsA16 ? True : False);
5658   Ops.push_back(TFE);
5659   Ops.push_back(LWE);
5660   if (!IsGFX10)
5661     Ops.push_back(DimInfo->DA ? True : False);
5662   if (BaseOpcode->HasD16)
5663     Ops.push_back(IsD16 ? True : False);
5664   if (isa<MemSDNode>(Op))
5665     Ops.push_back(Op.getOperand(0)); // chain
5666 
5667   int NumVAddrDwords =
5668       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5669   int Opcode = -1;
5670 
5671   if (IsGFX10) {
5672     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5673                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5674                                           : AMDGPU::MIMGEncGfx10Default,
5675                                    NumVDataDwords, NumVAddrDwords);
5676   } else {
5677     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5678       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5679                                      NumVDataDwords, NumVAddrDwords);
5680     if (Opcode == -1)
5681       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5682                                      NumVDataDwords, NumVAddrDwords);
5683   }
5684   assert(Opcode != -1);
5685 
5686   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5687   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5688     MachineMemOperand *MemRef = MemOp->getMemOperand();
5689     DAG.setNodeMemRefs(NewNode, {MemRef});
5690   }
5691 
5692   if (BaseOpcode->AtomicX2) {
5693     SmallVector<SDValue, 1> Elt;
5694     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5695     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5696   } else if (!BaseOpcode->Store) {
5697     return constructRetValue(DAG, NewNode,
5698                              OrigResultTypes, IsTexFail,
5699                              Subtarget->hasUnpackedD16VMem(), IsD16,
5700                              DMaskLanes, NumVDataDwords, DL,
5701                              *DAG.getContext());
5702   }
5703 
5704   return SDValue(NewNode, 0);
5705 }
5706 
5707 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5708                                        SDValue Offset, SDValue CachePolicy,
5709                                        SelectionDAG &DAG) const {
5710   MachineFunction &MF = DAG.getMachineFunction();
5711 
5712   const DataLayout &DataLayout = DAG.getDataLayout();
5713   Align Alignment =
5714       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
5715 
5716   MachineMemOperand *MMO = MF.getMachineMemOperand(
5717       MachinePointerInfo(),
5718       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5719           MachineMemOperand::MOInvariant,
5720       VT.getStoreSize(), Alignment);
5721 
5722   if (!Offset->isDivergent()) {
5723     SDValue Ops[] = {
5724         Rsrc,
5725         Offset, // Offset
5726         CachePolicy
5727     };
5728 
5729     // Widen vec3 load to vec4.
5730     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5731       EVT WidenedVT =
5732           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5733       auto WidenedOp = DAG.getMemIntrinsicNode(
5734           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5735           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5736       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5737                                    DAG.getVectorIdxConstant(0, DL));
5738       return Subvector;
5739     }
5740 
5741     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5742                                    DAG.getVTList(VT), Ops, VT, MMO);
5743   }
5744 
5745   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5746   // assume that the buffer is unswizzled.
5747   SmallVector<SDValue, 4> Loads;
5748   unsigned NumLoads = 1;
5749   MVT LoadVT = VT.getSimpleVT();
5750   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5751   assert((LoadVT.getScalarType() == MVT::i32 ||
5752           LoadVT.getScalarType() == MVT::f32));
5753 
5754   if (NumElts == 8 || NumElts == 16) {
5755     NumLoads = NumElts / 4;
5756     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5757   }
5758 
5759   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5760   SDValue Ops[] = {
5761       DAG.getEntryNode(),                               // Chain
5762       Rsrc,                                             // rsrc
5763       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5764       {},                                               // voffset
5765       {},                                               // soffset
5766       {},                                               // offset
5767       CachePolicy,                                      // cachepolicy
5768       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5769   };
5770 
5771   // Use the alignment to ensure that the required offsets will fit into the
5772   // immediate offsets.
5773   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5774 
5775   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5776   for (unsigned i = 0; i < NumLoads; ++i) {
5777     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5778     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5779                                         LoadVT, MMO, DAG));
5780   }
5781 
5782   if (NumElts == 8 || NumElts == 16)
5783     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5784 
5785   return Loads[0];
5786 }
5787 
5788 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5789                                                   SelectionDAG &DAG) const {
5790   MachineFunction &MF = DAG.getMachineFunction();
5791   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5792 
5793   EVT VT = Op.getValueType();
5794   SDLoc DL(Op);
5795   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5796 
5797   // TODO: Should this propagate fast-math-flags?
5798 
5799   switch (IntrinsicID) {
5800   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5801     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5802       return emitNonHSAIntrinsicError(DAG, DL, VT);
5803     return getPreloadedValue(DAG, *MFI, VT,
5804                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5805   }
5806   case Intrinsic::amdgcn_dispatch_ptr:
5807   case Intrinsic::amdgcn_queue_ptr: {
5808     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5809       DiagnosticInfoUnsupported BadIntrin(
5810           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5811           DL.getDebugLoc());
5812       DAG.getContext()->diagnose(BadIntrin);
5813       return DAG.getUNDEF(VT);
5814     }
5815 
5816     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5817       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5818     return getPreloadedValue(DAG, *MFI, VT, RegID);
5819   }
5820   case Intrinsic::amdgcn_implicitarg_ptr: {
5821     if (MFI->isEntryFunction())
5822       return getImplicitArgPtr(DAG, DL);
5823     return getPreloadedValue(DAG, *MFI, VT,
5824                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5825   }
5826   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5827     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
5828       // This only makes sense to call in a kernel, so just lower to null.
5829       return DAG.getConstant(0, DL, VT);
5830     }
5831 
5832     return getPreloadedValue(DAG, *MFI, VT,
5833                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5834   }
5835   case Intrinsic::amdgcn_dispatch_id: {
5836     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5837   }
5838   case Intrinsic::amdgcn_rcp:
5839     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5840   case Intrinsic::amdgcn_rsq:
5841     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5842   case Intrinsic::amdgcn_rsq_legacy:
5843     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5844       return emitRemovedIntrinsicError(DAG, DL, VT);
5845     return SDValue();
5846   case Intrinsic::amdgcn_rcp_legacy:
5847     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5848       return emitRemovedIntrinsicError(DAG, DL, VT);
5849     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5850   case Intrinsic::amdgcn_rsq_clamp: {
5851     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5852       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5853 
5854     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5855     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5856     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5857 
5858     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5859     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5860                               DAG.getConstantFP(Max, DL, VT));
5861     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5862                        DAG.getConstantFP(Min, DL, VT));
5863   }
5864   case Intrinsic::r600_read_ngroups_x:
5865     if (Subtarget->isAmdHsaOS())
5866       return emitNonHSAIntrinsicError(DAG, DL, VT);
5867 
5868     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5869                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5870   case Intrinsic::r600_read_ngroups_y:
5871     if (Subtarget->isAmdHsaOS())
5872       return emitNonHSAIntrinsicError(DAG, DL, VT);
5873 
5874     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5875                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5876   case Intrinsic::r600_read_ngroups_z:
5877     if (Subtarget->isAmdHsaOS())
5878       return emitNonHSAIntrinsicError(DAG, DL, VT);
5879 
5880     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5881                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5882   case Intrinsic::r600_read_global_size_x:
5883     if (Subtarget->isAmdHsaOS())
5884       return emitNonHSAIntrinsicError(DAG, DL, VT);
5885 
5886     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5887                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5888   case Intrinsic::r600_read_global_size_y:
5889     if (Subtarget->isAmdHsaOS())
5890       return emitNonHSAIntrinsicError(DAG, DL, VT);
5891 
5892     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5893                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5894   case Intrinsic::r600_read_global_size_z:
5895     if (Subtarget->isAmdHsaOS())
5896       return emitNonHSAIntrinsicError(DAG, DL, VT);
5897 
5898     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5899                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5900   case Intrinsic::r600_read_local_size_x:
5901     if (Subtarget->isAmdHsaOS())
5902       return emitNonHSAIntrinsicError(DAG, DL, VT);
5903 
5904     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5905                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5906   case Intrinsic::r600_read_local_size_y:
5907     if (Subtarget->isAmdHsaOS())
5908       return emitNonHSAIntrinsicError(DAG, DL, VT);
5909 
5910     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5911                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5912   case Intrinsic::r600_read_local_size_z:
5913     if (Subtarget->isAmdHsaOS())
5914       return emitNonHSAIntrinsicError(DAG, DL, VT);
5915 
5916     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5917                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5918   case Intrinsic::amdgcn_workgroup_id_x:
5919     return getPreloadedValue(DAG, *MFI, VT,
5920                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5921   case Intrinsic::amdgcn_workgroup_id_y:
5922     return getPreloadedValue(DAG, *MFI, VT,
5923                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5924   case Intrinsic::amdgcn_workgroup_id_z:
5925     return getPreloadedValue(DAG, *MFI, VT,
5926                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5927   case Intrinsic::amdgcn_workitem_id_x:
5928     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5929                           SDLoc(DAG.getEntryNode()),
5930                           MFI->getArgInfo().WorkItemIDX);
5931   case Intrinsic::amdgcn_workitem_id_y:
5932     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5933                           SDLoc(DAG.getEntryNode()),
5934                           MFI->getArgInfo().WorkItemIDY);
5935   case Intrinsic::amdgcn_workitem_id_z:
5936     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5937                           SDLoc(DAG.getEntryNode()),
5938                           MFI->getArgInfo().WorkItemIDZ);
5939   case Intrinsic::amdgcn_wavefrontsize:
5940     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5941                            SDLoc(Op), MVT::i32);
5942   case Intrinsic::amdgcn_s_buffer_load: {
5943     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5944     SDValue GLC;
5945     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5946     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5947                           IsGFX10 ? &DLC : nullptr))
5948       return Op;
5949     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5950                         DAG);
5951   }
5952   case Intrinsic::amdgcn_fdiv_fast:
5953     return lowerFDIV_FAST(Op, DAG);
5954   case Intrinsic::amdgcn_sin:
5955     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5956 
5957   case Intrinsic::amdgcn_cos:
5958     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5959 
5960   case Intrinsic::amdgcn_mul_u24:
5961     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5962   case Intrinsic::amdgcn_mul_i24:
5963     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5964 
5965   case Intrinsic::amdgcn_log_clamp: {
5966     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5967       return SDValue();
5968 
5969     DiagnosticInfoUnsupported BadIntrin(
5970       MF.getFunction(), "intrinsic not supported on subtarget",
5971       DL.getDebugLoc());
5972       DAG.getContext()->diagnose(BadIntrin);
5973       return DAG.getUNDEF(VT);
5974   }
5975   case Intrinsic::amdgcn_ldexp:
5976     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5977                        Op.getOperand(1), Op.getOperand(2));
5978 
5979   case Intrinsic::amdgcn_fract:
5980     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5981 
5982   case Intrinsic::amdgcn_class:
5983     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5984                        Op.getOperand(1), Op.getOperand(2));
5985   case Intrinsic::amdgcn_div_fmas:
5986     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5987                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5988                        Op.getOperand(4));
5989 
5990   case Intrinsic::amdgcn_div_fixup:
5991     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5992                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5993 
5994   case Intrinsic::amdgcn_trig_preop:
5995     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5996                        Op.getOperand(1), Op.getOperand(2));
5997   case Intrinsic::amdgcn_div_scale: {
5998     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5999 
6000     // Translate to the operands expected by the machine instruction. The
6001     // first parameter must be the same as the first instruction.
6002     SDValue Numerator = Op.getOperand(1);
6003     SDValue Denominator = Op.getOperand(2);
6004 
6005     // Note this order is opposite of the machine instruction's operations,
6006     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6007     // intrinsic has the numerator as the first operand to match a normal
6008     // division operation.
6009 
6010     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6011 
6012     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6013                        Denominator, Numerator);
6014   }
6015   case Intrinsic::amdgcn_icmp: {
6016     // There is a Pat that handles this variant, so return it as-is.
6017     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6018         Op.getConstantOperandVal(2) == 0 &&
6019         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6020       return Op;
6021     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6022   }
6023   case Intrinsic::amdgcn_fcmp: {
6024     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6025   }
6026   case Intrinsic::amdgcn_ballot:
6027     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6028   case Intrinsic::amdgcn_fmed3:
6029     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6030                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6031   case Intrinsic::amdgcn_fdot2:
6032     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6033                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6034                        Op.getOperand(4));
6035   case Intrinsic::amdgcn_fmul_legacy:
6036     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6037                        Op.getOperand(1), Op.getOperand(2));
6038   case Intrinsic::amdgcn_sffbh:
6039     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6040   case Intrinsic::amdgcn_sbfe:
6041     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6042                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6043   case Intrinsic::amdgcn_ubfe:
6044     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6045                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6046   case Intrinsic::amdgcn_cvt_pkrtz:
6047   case Intrinsic::amdgcn_cvt_pknorm_i16:
6048   case Intrinsic::amdgcn_cvt_pknorm_u16:
6049   case Intrinsic::amdgcn_cvt_pk_i16:
6050   case Intrinsic::amdgcn_cvt_pk_u16: {
6051     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6052     EVT VT = Op.getValueType();
6053     unsigned Opcode;
6054 
6055     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6056       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6057     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6058       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6059     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6060       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6061     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6062       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6063     else
6064       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6065 
6066     if (isTypeLegal(VT))
6067       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6068 
6069     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6070                                Op.getOperand(1), Op.getOperand(2));
6071     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6072   }
6073   case Intrinsic::amdgcn_fmad_ftz:
6074     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6075                        Op.getOperand(2), Op.getOperand(3));
6076 
6077   case Intrinsic::amdgcn_if_break:
6078     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6079                                       Op->getOperand(1), Op->getOperand(2)), 0);
6080 
6081   case Intrinsic::amdgcn_groupstaticsize: {
6082     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6083     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6084       return Op;
6085 
6086     const Module *M = MF.getFunction().getParent();
6087     const GlobalValue *GV =
6088         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6089     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6090                                             SIInstrInfo::MO_ABS32_LO);
6091     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6092   }
6093   case Intrinsic::amdgcn_is_shared:
6094   case Intrinsic::amdgcn_is_private: {
6095     SDLoc SL(Op);
6096     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6097       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6098     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6099     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6100                                  Op.getOperand(1));
6101 
6102     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6103                                 DAG.getConstant(1, SL, MVT::i32));
6104     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6105   }
6106   case Intrinsic::amdgcn_alignbit:
6107     return DAG.getNode(ISD::FSHR, DL, VT,
6108                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6109   case Intrinsic::amdgcn_reloc_constant: {
6110     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6111     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6112     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6113     auto RelocSymbol = cast<GlobalVariable>(
6114         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6115     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6116                                             SIInstrInfo::MO_ABS32_LO);
6117     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6118   }
6119   default:
6120     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6121             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6122       return lowerImage(Op, ImageDimIntr, DAG);
6123 
6124     return Op;
6125   }
6126 }
6127 
6128 // This function computes an appropriate offset to pass to
6129 // MachineMemOperand::setOffset() based on the offset inputs to
6130 // an intrinsic.  If any of the offsets are non-contstant or
6131 // if VIndex is non-zero then this function returns 0.  Otherwise,
6132 // it returns the sum of VOffset, SOffset, and Offset.
6133 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6134                                       SDValue SOffset,
6135                                       SDValue Offset,
6136                                       SDValue VIndex = SDValue()) {
6137 
6138   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6139       !isa<ConstantSDNode>(Offset))
6140     return 0;
6141 
6142   if (VIndex) {
6143     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6144       return 0;
6145   }
6146 
6147   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6148          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6149          cast<ConstantSDNode>(Offset)->getSExtValue();
6150 }
6151 
6152 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6153   switch (MF.getFunction().getCallingConv()) {
6154   case CallingConv::AMDGPU_PS:
6155     return 1;
6156   case CallingConv::AMDGPU_VS:
6157     return 2;
6158   case CallingConv::AMDGPU_GS:
6159     return 3;
6160   case CallingConv::AMDGPU_HS:
6161   case CallingConv::AMDGPU_LS:
6162   case CallingConv::AMDGPU_ES:
6163     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6164   case CallingConv::AMDGPU_CS:
6165   case CallingConv::AMDGPU_KERNEL:
6166   case CallingConv::C:
6167   case CallingConv::Fast:
6168   default:
6169     // Assume other calling conventions are various compute callable functions
6170     return 0;
6171   }
6172 }
6173 
6174 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6175                                                  SelectionDAG &DAG) const {
6176   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6177   SDLoc DL(Op);
6178 
6179   switch (IntrID) {
6180   case Intrinsic::amdgcn_ds_ordered_add:
6181   case Intrinsic::amdgcn_ds_ordered_swap: {
6182     MemSDNode *M = cast<MemSDNode>(Op);
6183     SDValue Chain = M->getOperand(0);
6184     SDValue M0 = M->getOperand(2);
6185     SDValue Value = M->getOperand(3);
6186     unsigned IndexOperand = M->getConstantOperandVal(7);
6187     unsigned WaveRelease = M->getConstantOperandVal(8);
6188     unsigned WaveDone = M->getConstantOperandVal(9);
6189 
6190     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6191     IndexOperand &= ~0x3f;
6192     unsigned CountDw = 0;
6193 
6194     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6195       CountDw = (IndexOperand >> 24) & 0xf;
6196       IndexOperand &= ~(0xf << 24);
6197 
6198       if (CountDw < 1 || CountDw > 4) {
6199         report_fatal_error(
6200             "ds_ordered_count: dword count must be between 1 and 4");
6201       }
6202     }
6203 
6204     if (IndexOperand)
6205       report_fatal_error("ds_ordered_count: bad index operand");
6206 
6207     if (WaveDone && !WaveRelease)
6208       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6209 
6210     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6211     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6212     unsigned Offset0 = OrderedCountIndex << 2;
6213     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6214                        (Instruction << 4);
6215 
6216     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6217       Offset1 |= (CountDw - 1) << 6;
6218 
6219     unsigned Offset = Offset0 | (Offset1 << 8);
6220 
6221     SDValue Ops[] = {
6222       Chain,
6223       Value,
6224       DAG.getTargetConstant(Offset, DL, MVT::i16),
6225       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6226     };
6227     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6228                                    M->getVTList(), Ops, M->getMemoryVT(),
6229                                    M->getMemOperand());
6230   }
6231   case Intrinsic::amdgcn_ds_fadd: {
6232     MemSDNode *M = cast<MemSDNode>(Op);
6233     unsigned Opc;
6234     switch (IntrID) {
6235     case Intrinsic::amdgcn_ds_fadd:
6236       Opc = ISD::ATOMIC_LOAD_FADD;
6237       break;
6238     }
6239 
6240     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6241                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6242                          M->getMemOperand());
6243   }
6244   case Intrinsic::amdgcn_atomic_inc:
6245   case Intrinsic::amdgcn_atomic_dec:
6246   case Intrinsic::amdgcn_ds_fmin:
6247   case Intrinsic::amdgcn_ds_fmax: {
6248     MemSDNode *M = cast<MemSDNode>(Op);
6249     unsigned Opc;
6250     switch (IntrID) {
6251     case Intrinsic::amdgcn_atomic_inc:
6252       Opc = AMDGPUISD::ATOMIC_INC;
6253       break;
6254     case Intrinsic::amdgcn_atomic_dec:
6255       Opc = AMDGPUISD::ATOMIC_DEC;
6256       break;
6257     case Intrinsic::amdgcn_ds_fmin:
6258       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6259       break;
6260     case Intrinsic::amdgcn_ds_fmax:
6261       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6262       break;
6263     default:
6264       llvm_unreachable("Unknown intrinsic!");
6265     }
6266     SDValue Ops[] = {
6267       M->getOperand(0), // Chain
6268       M->getOperand(2), // Ptr
6269       M->getOperand(3)  // Value
6270     };
6271 
6272     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6273                                    M->getMemoryVT(), M->getMemOperand());
6274   }
6275   case Intrinsic::amdgcn_buffer_load:
6276   case Intrinsic::amdgcn_buffer_load_format: {
6277     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6278     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6279     unsigned IdxEn = 1;
6280     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6281       IdxEn = Idx->getZExtValue() != 0;
6282     SDValue Ops[] = {
6283       Op.getOperand(0), // Chain
6284       Op.getOperand(2), // rsrc
6285       Op.getOperand(3), // vindex
6286       SDValue(),        // voffset -- will be set by setBufferOffsets
6287       SDValue(),        // soffset -- will be set by setBufferOffsets
6288       SDValue(),        // offset -- will be set by setBufferOffsets
6289       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6290       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6291     };
6292 
6293     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6294     // We don't know the offset if vindex is non-zero, so clear it.
6295     if (IdxEn)
6296       Offset = 0;
6297 
6298     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6299         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6300 
6301     EVT VT = Op.getValueType();
6302     EVT IntVT = VT.changeTypeToInteger();
6303     auto *M = cast<MemSDNode>(Op);
6304     M->getMemOperand()->setOffset(Offset);
6305     EVT LoadVT = Op.getValueType();
6306 
6307     if (LoadVT.getScalarType() == MVT::f16)
6308       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6309                                  M, DAG, Ops);
6310 
6311     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6312     if (LoadVT.getScalarType() == MVT::i8 ||
6313         LoadVT.getScalarType() == MVT::i16)
6314       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6315 
6316     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6317                                M->getMemOperand(), DAG);
6318   }
6319   case Intrinsic::amdgcn_raw_buffer_load:
6320   case Intrinsic::amdgcn_raw_buffer_load_format: {
6321     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6322 
6323     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6324     SDValue Ops[] = {
6325       Op.getOperand(0), // Chain
6326       Op.getOperand(2), // rsrc
6327       DAG.getConstant(0, DL, MVT::i32), // vindex
6328       Offsets.first,    // voffset
6329       Op.getOperand(4), // soffset
6330       Offsets.second,   // offset
6331       Op.getOperand(5), // cachepolicy, swizzled buffer
6332       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6333     };
6334 
6335     auto *M = cast<MemSDNode>(Op);
6336     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6337     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6338   }
6339   case Intrinsic::amdgcn_struct_buffer_load:
6340   case Intrinsic::amdgcn_struct_buffer_load_format: {
6341     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6342 
6343     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6344     SDValue Ops[] = {
6345       Op.getOperand(0), // Chain
6346       Op.getOperand(2), // rsrc
6347       Op.getOperand(3), // vindex
6348       Offsets.first,    // voffset
6349       Op.getOperand(5), // soffset
6350       Offsets.second,   // offset
6351       Op.getOperand(6), // cachepolicy, swizzled buffer
6352       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6353     };
6354 
6355     auto *M = cast<MemSDNode>(Op);
6356     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6357                                                         Ops[2]));
6358     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6359   }
6360   case Intrinsic::amdgcn_tbuffer_load: {
6361     MemSDNode *M = cast<MemSDNode>(Op);
6362     EVT LoadVT = Op.getValueType();
6363 
6364     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6365     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6366     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6367     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6368     unsigned IdxEn = 1;
6369     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6370       IdxEn = Idx->getZExtValue() != 0;
6371     SDValue Ops[] = {
6372       Op.getOperand(0),  // Chain
6373       Op.getOperand(2),  // rsrc
6374       Op.getOperand(3),  // vindex
6375       Op.getOperand(4),  // voffset
6376       Op.getOperand(5),  // soffset
6377       Op.getOperand(6),  // offset
6378       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6379       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6380       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6381     };
6382 
6383     if (LoadVT.getScalarType() == MVT::f16)
6384       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6385                                  M, DAG, Ops);
6386     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6387                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6388                                DAG);
6389   }
6390   case Intrinsic::amdgcn_raw_tbuffer_load: {
6391     MemSDNode *M = cast<MemSDNode>(Op);
6392     EVT LoadVT = Op.getValueType();
6393     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6394 
6395     SDValue Ops[] = {
6396       Op.getOperand(0),  // Chain
6397       Op.getOperand(2),  // rsrc
6398       DAG.getConstant(0, DL, MVT::i32), // vindex
6399       Offsets.first,     // voffset
6400       Op.getOperand(4),  // soffset
6401       Offsets.second,    // offset
6402       Op.getOperand(5),  // format
6403       Op.getOperand(6),  // cachepolicy, swizzled buffer
6404       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6405     };
6406 
6407     if (LoadVT.getScalarType() == MVT::f16)
6408       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6409                                  M, DAG, Ops);
6410     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6411                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6412                                DAG);
6413   }
6414   case Intrinsic::amdgcn_struct_tbuffer_load: {
6415     MemSDNode *M = cast<MemSDNode>(Op);
6416     EVT LoadVT = Op.getValueType();
6417     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6418 
6419     SDValue Ops[] = {
6420       Op.getOperand(0),  // Chain
6421       Op.getOperand(2),  // rsrc
6422       Op.getOperand(3),  // vindex
6423       Offsets.first,     // voffset
6424       Op.getOperand(5),  // soffset
6425       Offsets.second,    // offset
6426       Op.getOperand(6),  // format
6427       Op.getOperand(7),  // cachepolicy, swizzled buffer
6428       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6429     };
6430 
6431     if (LoadVT.getScalarType() == MVT::f16)
6432       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6433                                  M, DAG, Ops);
6434     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6435                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6436                                DAG);
6437   }
6438   case Intrinsic::amdgcn_buffer_atomic_swap:
6439   case Intrinsic::amdgcn_buffer_atomic_add:
6440   case Intrinsic::amdgcn_buffer_atomic_sub:
6441   case Intrinsic::amdgcn_buffer_atomic_smin:
6442   case Intrinsic::amdgcn_buffer_atomic_umin:
6443   case Intrinsic::amdgcn_buffer_atomic_smax:
6444   case Intrinsic::amdgcn_buffer_atomic_umax:
6445   case Intrinsic::amdgcn_buffer_atomic_and:
6446   case Intrinsic::amdgcn_buffer_atomic_or:
6447   case Intrinsic::amdgcn_buffer_atomic_xor: {
6448     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6449     unsigned IdxEn = 1;
6450     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6451       IdxEn = Idx->getZExtValue() != 0;
6452     SDValue Ops[] = {
6453       Op.getOperand(0), // Chain
6454       Op.getOperand(2), // vdata
6455       Op.getOperand(3), // rsrc
6456       Op.getOperand(4), // vindex
6457       SDValue(),        // voffset -- will be set by setBufferOffsets
6458       SDValue(),        // soffset -- will be set by setBufferOffsets
6459       SDValue(),        // offset -- will be set by setBufferOffsets
6460       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6461       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6462     };
6463     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6464     // We don't know the offset if vindex is non-zero, so clear it.
6465     if (IdxEn)
6466       Offset = 0;
6467     EVT VT = Op.getValueType();
6468 
6469     auto *M = cast<MemSDNode>(Op);
6470     M->getMemOperand()->setOffset(Offset);
6471     unsigned Opcode = 0;
6472 
6473     switch (IntrID) {
6474     case Intrinsic::amdgcn_buffer_atomic_swap:
6475       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6476       break;
6477     case Intrinsic::amdgcn_buffer_atomic_add:
6478       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6479       break;
6480     case Intrinsic::amdgcn_buffer_atomic_sub:
6481       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6482       break;
6483     case Intrinsic::amdgcn_buffer_atomic_smin:
6484       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6485       break;
6486     case Intrinsic::amdgcn_buffer_atomic_umin:
6487       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6488       break;
6489     case Intrinsic::amdgcn_buffer_atomic_smax:
6490       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6491       break;
6492     case Intrinsic::amdgcn_buffer_atomic_umax:
6493       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6494       break;
6495     case Intrinsic::amdgcn_buffer_atomic_and:
6496       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6497       break;
6498     case Intrinsic::amdgcn_buffer_atomic_or:
6499       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6500       break;
6501     case Intrinsic::amdgcn_buffer_atomic_xor:
6502       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6503       break;
6504     default:
6505       llvm_unreachable("unhandled atomic opcode");
6506     }
6507 
6508     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6509                                    M->getMemOperand());
6510   }
6511   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6512   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6513   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6514   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6515   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6516   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6517   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6518   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6519   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6520   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6521   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6522   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6523     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6524     SDValue Ops[] = {
6525       Op.getOperand(0), // Chain
6526       Op.getOperand(2), // vdata
6527       Op.getOperand(3), // rsrc
6528       DAG.getConstant(0, DL, MVT::i32), // vindex
6529       Offsets.first,    // voffset
6530       Op.getOperand(5), // soffset
6531       Offsets.second,   // offset
6532       Op.getOperand(6), // cachepolicy
6533       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6534     };
6535     EVT VT = Op.getValueType();
6536 
6537     auto *M = cast<MemSDNode>(Op);
6538     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6539     unsigned Opcode = 0;
6540 
6541     switch (IntrID) {
6542     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6543       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6544       break;
6545     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6546       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6547       break;
6548     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6549       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6550       break;
6551     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6552       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6553       break;
6554     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6555       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6556       break;
6557     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6558       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6559       break;
6560     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6561       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6562       break;
6563     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6564       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6565       break;
6566     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6567       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6568       break;
6569     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6570       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6571       break;
6572     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6573       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6574       break;
6575     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6576       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6577       break;
6578     default:
6579       llvm_unreachable("unhandled atomic opcode");
6580     }
6581 
6582     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6583                                    M->getMemOperand());
6584   }
6585   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6586   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6587   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6588   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6589   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6590   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6591   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6592   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6593   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6594   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6595   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6596   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6597     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6598     SDValue Ops[] = {
6599       Op.getOperand(0), // Chain
6600       Op.getOperand(2), // vdata
6601       Op.getOperand(3), // rsrc
6602       Op.getOperand(4), // vindex
6603       Offsets.first,    // voffset
6604       Op.getOperand(6), // soffset
6605       Offsets.second,   // offset
6606       Op.getOperand(7), // cachepolicy
6607       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6608     };
6609     EVT VT = Op.getValueType();
6610 
6611     auto *M = cast<MemSDNode>(Op);
6612     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6613                                                         Ops[3]));
6614     unsigned Opcode = 0;
6615 
6616     switch (IntrID) {
6617     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6618       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6619       break;
6620     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6621       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6622       break;
6623     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6624       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6625       break;
6626     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6627       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6628       break;
6629     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6630       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6631       break;
6632     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6633       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6634       break;
6635     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6636       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6637       break;
6638     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6639       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6640       break;
6641     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6642       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6643       break;
6644     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6645       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6646       break;
6647     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6648       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6649       break;
6650     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6651       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6652       break;
6653     default:
6654       llvm_unreachable("unhandled atomic opcode");
6655     }
6656 
6657     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6658                                    M->getMemOperand());
6659   }
6660   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6661     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6662     unsigned IdxEn = 1;
6663     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6664       IdxEn = Idx->getZExtValue() != 0;
6665     SDValue Ops[] = {
6666       Op.getOperand(0), // Chain
6667       Op.getOperand(2), // src
6668       Op.getOperand(3), // cmp
6669       Op.getOperand(4), // rsrc
6670       Op.getOperand(5), // vindex
6671       SDValue(),        // voffset -- will be set by setBufferOffsets
6672       SDValue(),        // soffset -- will be set by setBufferOffsets
6673       SDValue(),        // offset -- will be set by setBufferOffsets
6674       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6675       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6676     };
6677     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6678     // We don't know the offset if vindex is non-zero, so clear it.
6679     if (IdxEn)
6680       Offset = 0;
6681     EVT VT = Op.getValueType();
6682     auto *M = cast<MemSDNode>(Op);
6683     M->getMemOperand()->setOffset(Offset);
6684 
6685     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6686                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6687   }
6688   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6689     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6690     SDValue Ops[] = {
6691       Op.getOperand(0), // Chain
6692       Op.getOperand(2), // src
6693       Op.getOperand(3), // cmp
6694       Op.getOperand(4), // rsrc
6695       DAG.getConstant(0, DL, MVT::i32), // vindex
6696       Offsets.first,    // voffset
6697       Op.getOperand(6), // soffset
6698       Offsets.second,   // offset
6699       Op.getOperand(7), // cachepolicy
6700       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6701     };
6702     EVT VT = Op.getValueType();
6703     auto *M = cast<MemSDNode>(Op);
6704     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6705 
6706     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6707                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6708   }
6709   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6710     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6711     SDValue Ops[] = {
6712       Op.getOperand(0), // Chain
6713       Op.getOperand(2), // src
6714       Op.getOperand(3), // cmp
6715       Op.getOperand(4), // rsrc
6716       Op.getOperand(5), // vindex
6717       Offsets.first,    // voffset
6718       Op.getOperand(7), // soffset
6719       Offsets.second,   // offset
6720       Op.getOperand(8), // cachepolicy
6721       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6722     };
6723     EVT VT = Op.getValueType();
6724     auto *M = cast<MemSDNode>(Op);
6725     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6726                                                         Ops[4]));
6727 
6728     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6729                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6730   }
6731 
6732   default:
6733     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6734             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6735       return lowerImage(Op, ImageDimIntr, DAG);
6736 
6737     return SDValue();
6738   }
6739 }
6740 
6741 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6742 // dwordx4 if on SI.
6743 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6744                                               SDVTList VTList,
6745                                               ArrayRef<SDValue> Ops, EVT MemVT,
6746                                               MachineMemOperand *MMO,
6747                                               SelectionDAG &DAG) const {
6748   EVT VT = VTList.VTs[0];
6749   EVT WidenedVT = VT;
6750   EVT WidenedMemVT = MemVT;
6751   if (!Subtarget->hasDwordx3LoadStores() &&
6752       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6753     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6754                                  WidenedVT.getVectorElementType(), 4);
6755     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6756                                     WidenedMemVT.getVectorElementType(), 4);
6757     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6758   }
6759 
6760   assert(VTList.NumVTs == 2);
6761   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6762 
6763   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6764                                        WidenedMemVT, MMO);
6765   if (WidenedVT != VT) {
6766     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6767                                DAG.getVectorIdxConstant(0, DL));
6768     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6769   }
6770   return NewOp;
6771 }
6772 
6773 SDValue SITargetLowering::handleD16VData(SDValue VData,
6774                                          SelectionDAG &DAG) const {
6775   EVT StoreVT = VData.getValueType();
6776 
6777   // No change for f16 and legal vector D16 types.
6778   if (!StoreVT.isVector())
6779     return VData;
6780 
6781   SDLoc DL(VData);
6782   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6783 
6784   if (Subtarget->hasUnpackedD16VMem()) {
6785     // We need to unpack the packed data to store.
6786     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6787     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6788 
6789     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6790                                         StoreVT.getVectorNumElements());
6791     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6792     return DAG.UnrollVectorOp(ZExt.getNode());
6793   }
6794 
6795   assert(isTypeLegal(StoreVT));
6796   return VData;
6797 }
6798 
6799 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6800                                               SelectionDAG &DAG) const {
6801   SDLoc DL(Op);
6802   SDValue Chain = Op.getOperand(0);
6803   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6804   MachineFunction &MF = DAG.getMachineFunction();
6805 
6806   switch (IntrinsicID) {
6807   case Intrinsic::amdgcn_exp_compr: {
6808     SDValue Src0 = Op.getOperand(4);
6809     SDValue Src1 = Op.getOperand(5);
6810     // Hack around illegal type on SI by directly selecting it.
6811     if (isTypeLegal(Src0.getValueType()))
6812       return SDValue();
6813 
6814     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6815     SDValue Undef = DAG.getUNDEF(MVT::f32);
6816     const SDValue Ops[] = {
6817       Op.getOperand(2), // tgt
6818       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
6819       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
6820       Undef, // src2
6821       Undef, // src3
6822       Op.getOperand(7), // vm
6823       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6824       Op.getOperand(3), // en
6825       Op.getOperand(0) // Chain
6826     };
6827 
6828     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
6829     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
6830   }
6831   case Intrinsic::amdgcn_s_barrier: {
6832     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6833       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6834       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6835       if (WGSize <= ST.getWavefrontSize())
6836         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6837                                           Op.getOperand(0)), 0);
6838     }
6839     return SDValue();
6840   };
6841   case Intrinsic::amdgcn_tbuffer_store: {
6842     SDValue VData = Op.getOperand(2);
6843     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6844     if (IsD16)
6845       VData = handleD16VData(VData, DAG);
6846     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6847     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6848     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6849     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6850     unsigned IdxEn = 1;
6851     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6852       IdxEn = Idx->getZExtValue() != 0;
6853     SDValue Ops[] = {
6854       Chain,
6855       VData,             // vdata
6856       Op.getOperand(3),  // rsrc
6857       Op.getOperand(4),  // vindex
6858       Op.getOperand(5),  // voffset
6859       Op.getOperand(6),  // soffset
6860       Op.getOperand(7),  // offset
6861       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6862       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6863       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
6864     };
6865     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6866                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6867     MemSDNode *M = cast<MemSDNode>(Op);
6868     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6869                                    M->getMemoryVT(), M->getMemOperand());
6870   }
6871 
6872   case Intrinsic::amdgcn_struct_tbuffer_store: {
6873     SDValue VData = Op.getOperand(2);
6874     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6875     if (IsD16)
6876       VData = handleD16VData(VData, DAG);
6877     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6878     SDValue Ops[] = {
6879       Chain,
6880       VData,             // vdata
6881       Op.getOperand(3),  // rsrc
6882       Op.getOperand(4),  // vindex
6883       Offsets.first,     // voffset
6884       Op.getOperand(6),  // soffset
6885       Offsets.second,    // offset
6886       Op.getOperand(7),  // format
6887       Op.getOperand(8),  // cachepolicy, swizzled buffer
6888       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
6889     };
6890     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6891                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6892     MemSDNode *M = cast<MemSDNode>(Op);
6893     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6894                                    M->getMemoryVT(), M->getMemOperand());
6895   }
6896 
6897   case Intrinsic::amdgcn_raw_tbuffer_store: {
6898     SDValue VData = Op.getOperand(2);
6899     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6900     if (IsD16)
6901       VData = handleD16VData(VData, DAG);
6902     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6903     SDValue Ops[] = {
6904       Chain,
6905       VData,             // vdata
6906       Op.getOperand(3),  // rsrc
6907       DAG.getConstant(0, DL, MVT::i32), // vindex
6908       Offsets.first,     // voffset
6909       Op.getOperand(5),  // soffset
6910       Offsets.second,    // offset
6911       Op.getOperand(6),  // format
6912       Op.getOperand(7),  // cachepolicy, swizzled buffer
6913       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
6914     };
6915     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6916                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6917     MemSDNode *M = cast<MemSDNode>(Op);
6918     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6919                                    M->getMemoryVT(), M->getMemOperand());
6920   }
6921 
6922   case Intrinsic::amdgcn_buffer_store:
6923   case Intrinsic::amdgcn_buffer_store_format: {
6924     SDValue VData = Op.getOperand(2);
6925     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6926     if (IsD16)
6927       VData = handleD16VData(VData, DAG);
6928     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6929     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6930     unsigned IdxEn = 1;
6931     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6932       IdxEn = Idx->getZExtValue() != 0;
6933     SDValue Ops[] = {
6934       Chain,
6935       VData,
6936       Op.getOperand(3), // rsrc
6937       Op.getOperand(4), // vindex
6938       SDValue(), // voffset -- will be set by setBufferOffsets
6939       SDValue(), // soffset -- will be set by setBufferOffsets
6940       SDValue(), // offset -- will be set by setBufferOffsets
6941       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6942       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6943     };
6944     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6945     // We don't know the offset if vindex is non-zero, so clear it.
6946     if (IdxEn)
6947       Offset = 0;
6948     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6949                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6950     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6951     MemSDNode *M = cast<MemSDNode>(Op);
6952     M->getMemOperand()->setOffset(Offset);
6953 
6954     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6955     EVT VDataType = VData.getValueType().getScalarType();
6956     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6957       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6958 
6959     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6960                                    M->getMemoryVT(), M->getMemOperand());
6961   }
6962 
6963   case Intrinsic::amdgcn_raw_buffer_store:
6964   case Intrinsic::amdgcn_raw_buffer_store_format: {
6965     const bool IsFormat =
6966         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
6967 
6968     SDValue VData = Op.getOperand(2);
6969     EVT VDataVT = VData.getValueType();
6970     EVT EltType = VDataVT.getScalarType();
6971     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6972     if (IsD16)
6973       VData = handleD16VData(VData, DAG);
6974 
6975     if (!isTypeLegal(VDataVT)) {
6976       VData =
6977           DAG.getNode(ISD::BITCAST, DL,
6978                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6979     }
6980 
6981     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6982     SDValue Ops[] = {
6983       Chain,
6984       VData,
6985       Op.getOperand(3), // rsrc
6986       DAG.getConstant(0, DL, MVT::i32), // vindex
6987       Offsets.first,    // voffset
6988       Op.getOperand(5), // soffset
6989       Offsets.second,   // offset
6990       Op.getOperand(6), // cachepolicy, swizzled buffer
6991       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6992     };
6993     unsigned Opc =
6994         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
6995     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6996     MemSDNode *M = cast<MemSDNode>(Op);
6997     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6998 
6999     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7000     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7001       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7002 
7003     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7004                                    M->getMemoryVT(), M->getMemOperand());
7005   }
7006 
7007   case Intrinsic::amdgcn_struct_buffer_store:
7008   case Intrinsic::amdgcn_struct_buffer_store_format: {
7009     const bool IsFormat =
7010         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7011 
7012     SDValue VData = Op.getOperand(2);
7013     EVT VDataVT = VData.getValueType();
7014     EVT EltType = VDataVT.getScalarType();
7015     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7016 
7017     if (IsD16)
7018       VData = handleD16VData(VData, DAG);
7019 
7020     if (!isTypeLegal(VDataVT)) {
7021       VData =
7022           DAG.getNode(ISD::BITCAST, DL,
7023                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7024     }
7025 
7026     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7027     SDValue Ops[] = {
7028       Chain,
7029       VData,
7030       Op.getOperand(3), // rsrc
7031       Op.getOperand(4), // vindex
7032       Offsets.first,    // voffset
7033       Op.getOperand(6), // soffset
7034       Offsets.second,   // offset
7035       Op.getOperand(7), // cachepolicy, swizzled buffer
7036       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7037     };
7038     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7039                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7040     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7041     MemSDNode *M = cast<MemSDNode>(Op);
7042     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7043                                                         Ops[3]));
7044 
7045     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7046     EVT VDataType = VData.getValueType().getScalarType();
7047     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7048       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7049 
7050     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7051                                    M->getMemoryVT(), M->getMemOperand());
7052   }
7053 
7054   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7055     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7056     unsigned IdxEn = 1;
7057     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7058       IdxEn = Idx->getZExtValue() != 0;
7059     SDValue Ops[] = {
7060       Chain,
7061       Op.getOperand(2), // vdata
7062       Op.getOperand(3), // rsrc
7063       Op.getOperand(4), // vindex
7064       SDValue(),        // voffset -- will be set by setBufferOffsets
7065       SDValue(),        // soffset -- will be set by setBufferOffsets
7066       SDValue(),        // offset -- will be set by setBufferOffsets
7067       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7068       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7069     };
7070     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7071     // We don't know the offset if vindex is non-zero, so clear it.
7072     if (IdxEn)
7073       Offset = 0;
7074     EVT VT = Op.getOperand(2).getValueType();
7075 
7076     auto *M = cast<MemSDNode>(Op);
7077     M->getMemOperand()->setOffset(Offset);
7078     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7079                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7080 
7081     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7082                                    M->getMemOperand());
7083   }
7084 
7085   case Intrinsic::amdgcn_global_atomic_fadd: {
7086     SDValue Ops[] = {
7087       Chain,
7088       Op.getOperand(2), // ptr
7089       Op.getOperand(3)  // vdata
7090     };
7091     EVT VT = Op.getOperand(3).getValueType();
7092 
7093     auto *M = cast<MemSDNode>(Op);
7094     if (VT.isVector()) {
7095       return DAG.getMemIntrinsicNode(
7096         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7097         M->getMemOperand());
7098     }
7099 
7100     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7101                          DAG.getVTList(VT, MVT::Other), Ops,
7102                          M->getMemOperand()).getValue(1);
7103   }
7104   case Intrinsic::amdgcn_end_cf:
7105     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7106                                       Op->getOperand(2), Chain), 0);
7107 
7108   default: {
7109     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7110             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7111       return lowerImage(Op, ImageDimIntr, DAG);
7112 
7113     return Op;
7114   }
7115   }
7116 }
7117 
7118 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7119 // offset (the offset that is included in bounds checking and swizzling, to be
7120 // split between the instruction's voffset and immoffset fields) and soffset
7121 // (the offset that is excluded from bounds checking and swizzling, to go in
7122 // the instruction's soffset field).  This function takes the first kind of
7123 // offset and figures out how to split it between voffset and immoffset.
7124 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7125     SDValue Offset, SelectionDAG &DAG) const {
7126   SDLoc DL(Offset);
7127   const unsigned MaxImm = 4095;
7128   SDValue N0 = Offset;
7129   ConstantSDNode *C1 = nullptr;
7130 
7131   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7132     N0 = SDValue();
7133   else if (DAG.isBaseWithConstantOffset(N0)) {
7134     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7135     N0 = N0.getOperand(0);
7136   }
7137 
7138   if (C1) {
7139     unsigned ImmOffset = C1->getZExtValue();
7140     // If the immediate value is too big for the immoffset field, put the value
7141     // and -4096 into the immoffset field so that the value that is copied/added
7142     // for the voffset field is a multiple of 4096, and it stands more chance
7143     // of being CSEd with the copy/add for another similar load/store.
7144     // However, do not do that rounding down to a multiple of 4096 if that is a
7145     // negative number, as it appears to be illegal to have a negative offset
7146     // in the vgpr, even if adding the immediate offset makes it positive.
7147     unsigned Overflow = ImmOffset & ~MaxImm;
7148     ImmOffset -= Overflow;
7149     if ((int32_t)Overflow < 0) {
7150       Overflow += ImmOffset;
7151       ImmOffset = 0;
7152     }
7153     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7154     if (Overflow) {
7155       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7156       if (!N0)
7157         N0 = OverflowVal;
7158       else {
7159         SDValue Ops[] = { N0, OverflowVal };
7160         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7161       }
7162     }
7163   }
7164   if (!N0)
7165     N0 = DAG.getConstant(0, DL, MVT::i32);
7166   if (!C1)
7167     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7168   return {N0, SDValue(C1, 0)};
7169 }
7170 
7171 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7172 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7173 // pointed to by Offsets.
7174 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7175                                         SelectionDAG &DAG, SDValue *Offsets,
7176                                         unsigned Align) const {
7177   SDLoc DL(CombinedOffset);
7178   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7179     uint32_t Imm = C->getZExtValue();
7180     uint32_t SOffset, ImmOffset;
7181     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7182       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7183       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7184       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7185       return SOffset + ImmOffset;
7186     }
7187   }
7188   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7189     SDValue N0 = CombinedOffset.getOperand(0);
7190     SDValue N1 = CombinedOffset.getOperand(1);
7191     uint32_t SOffset, ImmOffset;
7192     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7193     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7194                                                 Subtarget, Align)) {
7195       Offsets[0] = N0;
7196       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7197       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7198       return 0;
7199     }
7200   }
7201   Offsets[0] = CombinedOffset;
7202   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7203   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7204   return 0;
7205 }
7206 
7207 // Handle 8 bit and 16 bit buffer loads
7208 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7209                                                      EVT LoadVT, SDLoc DL,
7210                                                      ArrayRef<SDValue> Ops,
7211                                                      MemSDNode *M) const {
7212   EVT IntVT = LoadVT.changeTypeToInteger();
7213   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7214          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7215 
7216   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7217   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7218                                                Ops, IntVT,
7219                                                M->getMemOperand());
7220   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7221   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7222 
7223   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7224 }
7225 
7226 // Handle 8 bit and 16 bit buffer stores
7227 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7228                                                       EVT VDataType, SDLoc DL,
7229                                                       SDValue Ops[],
7230                                                       MemSDNode *M) const {
7231   if (VDataType == MVT::f16)
7232     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7233 
7234   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7235   Ops[1] = BufferStoreExt;
7236   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7237                                  AMDGPUISD::BUFFER_STORE_SHORT;
7238   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7239   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7240                                      M->getMemOperand());
7241 }
7242 
7243 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7244                                  ISD::LoadExtType ExtType, SDValue Op,
7245                                  const SDLoc &SL, EVT VT) {
7246   if (VT.bitsLT(Op.getValueType()))
7247     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7248 
7249   switch (ExtType) {
7250   case ISD::SEXTLOAD:
7251     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7252   case ISD::ZEXTLOAD:
7253     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7254   case ISD::EXTLOAD:
7255     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7256   case ISD::NON_EXTLOAD:
7257     return Op;
7258   }
7259 
7260   llvm_unreachable("invalid ext type");
7261 }
7262 
7263 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7264   SelectionDAG &DAG = DCI.DAG;
7265   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7266     return SDValue();
7267 
7268   // FIXME: Constant loads should all be marked invariant.
7269   unsigned AS = Ld->getAddressSpace();
7270   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7271       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7272       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7273     return SDValue();
7274 
7275   // Don't do this early, since it may interfere with adjacent load merging for
7276   // illegal types. We can avoid losing alignment information for exotic types
7277   // pre-legalize.
7278   EVT MemVT = Ld->getMemoryVT();
7279   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7280       MemVT.getSizeInBits() >= 32)
7281     return SDValue();
7282 
7283   SDLoc SL(Ld);
7284 
7285   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7286          "unexpected vector extload");
7287 
7288   // TODO: Drop only high part of range.
7289   SDValue Ptr = Ld->getBasePtr();
7290   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7291                                 MVT::i32, SL, Ld->getChain(), Ptr,
7292                                 Ld->getOffset(),
7293                                 Ld->getPointerInfo(), MVT::i32,
7294                                 Ld->getAlignment(),
7295                                 Ld->getMemOperand()->getFlags(),
7296                                 Ld->getAAInfo(),
7297                                 nullptr); // Drop ranges
7298 
7299   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7300   if (MemVT.isFloatingPoint()) {
7301     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7302            "unexpected fp extload");
7303     TruncVT = MemVT.changeTypeToInteger();
7304   }
7305 
7306   SDValue Cvt = NewLoad;
7307   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7308     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7309                       DAG.getValueType(TruncVT));
7310   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7311              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7312     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7313   } else {
7314     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7315   }
7316 
7317   EVT VT = Ld->getValueType(0);
7318   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7319 
7320   DCI.AddToWorklist(Cvt.getNode());
7321 
7322   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7323   // the appropriate extension from the 32-bit load.
7324   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7325   DCI.AddToWorklist(Cvt.getNode());
7326 
7327   // Handle conversion back to floating point if necessary.
7328   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7329 
7330   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7331 }
7332 
7333 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7334   SDLoc DL(Op);
7335   LoadSDNode *Load = cast<LoadSDNode>(Op);
7336   ISD::LoadExtType ExtType = Load->getExtensionType();
7337   EVT MemVT = Load->getMemoryVT();
7338 
7339   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7340     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7341       return SDValue();
7342 
7343     // FIXME: Copied from PPC
7344     // First, load into 32 bits, then truncate to 1 bit.
7345 
7346     SDValue Chain = Load->getChain();
7347     SDValue BasePtr = Load->getBasePtr();
7348     MachineMemOperand *MMO = Load->getMemOperand();
7349 
7350     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7351 
7352     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7353                                    BasePtr, RealMemVT, MMO);
7354 
7355     if (!MemVT.isVector()) {
7356       SDValue Ops[] = {
7357         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7358         NewLD.getValue(1)
7359       };
7360 
7361       return DAG.getMergeValues(Ops, DL);
7362     }
7363 
7364     SmallVector<SDValue, 3> Elts;
7365     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7366       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7367                                 DAG.getConstant(I, DL, MVT::i32));
7368 
7369       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7370     }
7371 
7372     SDValue Ops[] = {
7373       DAG.getBuildVector(MemVT, DL, Elts),
7374       NewLD.getValue(1)
7375     };
7376 
7377     return DAG.getMergeValues(Ops, DL);
7378   }
7379 
7380   if (!MemVT.isVector())
7381     return SDValue();
7382 
7383   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7384          "Custom lowering for non-i32 vectors hasn't been implemented.");
7385 
7386   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7387                                       MemVT, *Load->getMemOperand())) {
7388     SDValue Ops[2];
7389     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7390     return DAG.getMergeValues(Ops, DL);
7391   }
7392 
7393   unsigned Alignment = Load->getAlignment();
7394   unsigned AS = Load->getAddressSpace();
7395   if (Subtarget->hasLDSMisalignedBug() &&
7396       AS == AMDGPUAS::FLAT_ADDRESS &&
7397       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7398     return SplitVectorLoad(Op, DAG);
7399   }
7400 
7401   MachineFunction &MF = DAG.getMachineFunction();
7402   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7403   // If there is a possibilty that flat instruction access scratch memory
7404   // then we need to use the same legalization rules we use for private.
7405   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7406       !Subtarget->hasMultiDwordFlatScratchAddressing())
7407     AS = MFI->hasFlatScratchInit() ?
7408          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7409 
7410   unsigned NumElements = MemVT.getVectorNumElements();
7411 
7412   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7413       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7414     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7415       if (MemVT.isPow2VectorType())
7416         return SDValue();
7417       if (NumElements == 3)
7418         return WidenVectorLoad(Op, DAG);
7419       return SplitVectorLoad(Op, DAG);
7420     }
7421     // Non-uniform loads will be selected to MUBUF instructions, so they
7422     // have the same legalization requirements as global and private
7423     // loads.
7424     //
7425   }
7426 
7427   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7428       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7429       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7430     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7431         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7432         Alignment >= 4 && NumElements < 32) {
7433       if (MemVT.isPow2VectorType())
7434         return SDValue();
7435       if (NumElements == 3)
7436         return WidenVectorLoad(Op, DAG);
7437       return SplitVectorLoad(Op, DAG);
7438     }
7439     // Non-uniform loads will be selected to MUBUF instructions, so they
7440     // have the same legalization requirements as global and private
7441     // loads.
7442     //
7443   }
7444   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7445       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7446       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7447       AS == AMDGPUAS::FLAT_ADDRESS) {
7448     if (NumElements > 4)
7449       return SplitVectorLoad(Op, DAG);
7450     // v3 loads not supported on SI.
7451     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7452       return WidenVectorLoad(Op, DAG);
7453     // v3 and v4 loads are supported for private and global memory.
7454     return SDValue();
7455   }
7456   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7457     // Depending on the setting of the private_element_size field in the
7458     // resource descriptor, we can only make private accesses up to a certain
7459     // size.
7460     switch (Subtarget->getMaxPrivateElementSize()) {
7461     case 4: {
7462       SDValue Ops[2];
7463       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7464       return DAG.getMergeValues(Ops, DL);
7465     }
7466     case 8:
7467       if (NumElements > 2)
7468         return SplitVectorLoad(Op, DAG);
7469       return SDValue();
7470     case 16:
7471       // Same as global/flat
7472       if (NumElements > 4)
7473         return SplitVectorLoad(Op, DAG);
7474       // v3 loads not supported on SI.
7475       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7476         return WidenVectorLoad(Op, DAG);
7477       return SDValue();
7478     default:
7479       llvm_unreachable("unsupported private_element_size");
7480     }
7481   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7482     // Use ds_read_b128 if possible.
7483     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7484         MemVT.getStoreSize() == 16)
7485       return SDValue();
7486 
7487     if (NumElements > 2)
7488       return SplitVectorLoad(Op, DAG);
7489 
7490     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7491     // address is negative, then the instruction is incorrectly treated as
7492     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7493     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7494     // load later in the SILoadStoreOptimizer.
7495     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7496         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7497         Load->getAlignment() < 8) {
7498       return SplitVectorLoad(Op, DAG);
7499     }
7500   }
7501   return SDValue();
7502 }
7503 
7504 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7505   EVT VT = Op.getValueType();
7506   assert(VT.getSizeInBits() == 64);
7507 
7508   SDLoc DL(Op);
7509   SDValue Cond = Op.getOperand(0);
7510 
7511   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7512   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7513 
7514   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7515   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7516 
7517   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7518   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7519 
7520   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7521 
7522   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7523   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7524 
7525   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7526 
7527   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7528   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7529 }
7530 
7531 // Catch division cases where we can use shortcuts with rcp and rsq
7532 // instructions.
7533 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7534                                               SelectionDAG &DAG) const {
7535   SDLoc SL(Op);
7536   SDValue LHS = Op.getOperand(0);
7537   SDValue RHS = Op.getOperand(1);
7538   EVT VT = Op.getValueType();
7539   const SDNodeFlags Flags = Op->getFlags();
7540 
7541   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7542                             Flags.hasApproximateFuncs();
7543 
7544   // Without !fpmath accuracy information, we can't do more because we don't
7545   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7546   if (!AllowInaccurateRcp)
7547     return SDValue();
7548 
7549   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7550     if (CLHS->isExactlyValue(1.0)) {
7551       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7552       // the CI documentation has a worst case error of 1 ulp.
7553       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7554       // use it as long as we aren't trying to use denormals.
7555       //
7556       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7557 
7558       // 1.0 / sqrt(x) -> rsq(x)
7559 
7560       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7561       // error seems really high at 2^29 ULP.
7562       if (RHS.getOpcode() == ISD::FSQRT)
7563         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7564 
7565       // 1.0 / x -> rcp(x)
7566       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7567     }
7568 
7569     // Same as for 1.0, but expand the sign out of the constant.
7570     if (CLHS->isExactlyValue(-1.0)) {
7571       // -1.0 / x -> rcp (fneg x)
7572       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7573       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7574     }
7575   }
7576 
7577   // Turn into multiply by the reciprocal.
7578   // x / y -> x * (1.0 / y)
7579   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7580   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7581 }
7582 
7583 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7584                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7585   if (GlueChain->getNumValues() <= 1) {
7586     return DAG.getNode(Opcode, SL, VT, A, B);
7587   }
7588 
7589   assert(GlueChain->getNumValues() == 3);
7590 
7591   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7592   switch (Opcode) {
7593   default: llvm_unreachable("no chain equivalent for opcode");
7594   case ISD::FMUL:
7595     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7596     break;
7597   }
7598 
7599   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7600                      GlueChain.getValue(2));
7601 }
7602 
7603 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7604                            EVT VT, SDValue A, SDValue B, SDValue C,
7605                            SDValue GlueChain) {
7606   if (GlueChain->getNumValues() <= 1) {
7607     return DAG.getNode(Opcode, SL, VT, A, B, C);
7608   }
7609 
7610   assert(GlueChain->getNumValues() == 3);
7611 
7612   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7613   switch (Opcode) {
7614   default: llvm_unreachable("no chain equivalent for opcode");
7615   case ISD::FMA:
7616     Opcode = AMDGPUISD::FMA_W_CHAIN;
7617     break;
7618   }
7619 
7620   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7621                      GlueChain.getValue(2));
7622 }
7623 
7624 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7625   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7626     return FastLowered;
7627 
7628   SDLoc SL(Op);
7629   SDValue Src0 = Op.getOperand(0);
7630   SDValue Src1 = Op.getOperand(1);
7631 
7632   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7633   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7634 
7635   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7636   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7637 
7638   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7639   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7640 
7641   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7642 }
7643 
7644 // Faster 2.5 ULP division that does not support denormals.
7645 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7646   SDLoc SL(Op);
7647   SDValue LHS = Op.getOperand(1);
7648   SDValue RHS = Op.getOperand(2);
7649 
7650   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7651 
7652   const APFloat K0Val(BitsToFloat(0x6f800000));
7653   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7654 
7655   const APFloat K1Val(BitsToFloat(0x2f800000));
7656   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7657 
7658   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7659 
7660   EVT SetCCVT =
7661     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7662 
7663   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7664 
7665   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7666 
7667   // TODO: Should this propagate fast-math-flags?
7668   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7669 
7670   // rcp does not support denormals.
7671   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7672 
7673   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7674 
7675   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7676 }
7677 
7678 // Returns immediate value for setting the F32 denorm mode when using the
7679 // S_DENORM_MODE instruction.
7680 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7681                                           const SDLoc &SL, const GCNSubtarget *ST) {
7682   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7683   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7684                                 ? FP_DENORM_FLUSH_NONE
7685                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7686 
7687   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7688   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7689 }
7690 
7691 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7692   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7693     return FastLowered;
7694 
7695   SDLoc SL(Op);
7696   SDValue LHS = Op.getOperand(0);
7697   SDValue RHS = Op.getOperand(1);
7698 
7699   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7700 
7701   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7702 
7703   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7704                                           RHS, RHS, LHS);
7705   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7706                                         LHS, RHS, LHS);
7707 
7708   // Denominator is scaled to not be denormal, so using rcp is ok.
7709   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7710                                   DenominatorScaled);
7711   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7712                                      DenominatorScaled);
7713 
7714   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7715                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7716                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7717   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7718 
7719   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7720 
7721   if (!HasFP32Denormals) {
7722     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7723 
7724     SDValue EnableDenorm;
7725     if (Subtarget->hasDenormModeInst()) {
7726       const SDValue EnableDenormValue =
7727           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7728 
7729       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7730                                  DAG.getEntryNode(), EnableDenormValue);
7731     } else {
7732       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7733                                                         SL, MVT::i32);
7734       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7735                                  DAG.getEntryNode(), EnableDenormValue,
7736                                  BitField);
7737     }
7738 
7739     SDValue Ops[3] = {
7740       NegDivScale0,
7741       EnableDenorm.getValue(0),
7742       EnableDenorm.getValue(1)
7743     };
7744 
7745     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7746   }
7747 
7748   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7749                              ApproxRcp, One, NegDivScale0);
7750 
7751   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7752                              ApproxRcp, Fma0);
7753 
7754   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7755                            Fma1, Fma1);
7756 
7757   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7758                              NumeratorScaled, Mul);
7759 
7760   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7761 
7762   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7763                              NumeratorScaled, Fma3);
7764 
7765   if (!HasFP32Denormals) {
7766     SDValue DisableDenorm;
7767     if (Subtarget->hasDenormModeInst()) {
7768       const SDValue DisableDenormValue =
7769           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7770 
7771       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7772                                   Fma4.getValue(1), DisableDenormValue,
7773                                   Fma4.getValue(2));
7774     } else {
7775       const SDValue DisableDenormValue =
7776           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7777 
7778       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7779                                   Fma4.getValue(1), DisableDenormValue,
7780                                   BitField, Fma4.getValue(2));
7781     }
7782 
7783     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7784                                       DisableDenorm, DAG.getRoot());
7785     DAG.setRoot(OutputChain);
7786   }
7787 
7788   SDValue Scale = NumeratorScaled.getValue(1);
7789   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7790                              Fma4, Fma1, Fma3, Scale);
7791 
7792   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7793 }
7794 
7795 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7796   if (DAG.getTarget().Options.UnsafeFPMath)
7797     return lowerFastUnsafeFDIV(Op, DAG);
7798 
7799   SDLoc SL(Op);
7800   SDValue X = Op.getOperand(0);
7801   SDValue Y = Op.getOperand(1);
7802 
7803   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7804 
7805   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7806 
7807   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7808 
7809   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7810 
7811   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7812 
7813   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7814 
7815   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7816 
7817   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7818 
7819   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7820 
7821   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7822   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7823 
7824   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7825                              NegDivScale0, Mul, DivScale1);
7826 
7827   SDValue Scale;
7828 
7829   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7830     // Workaround a hardware bug on SI where the condition output from div_scale
7831     // is not usable.
7832 
7833     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7834 
7835     // Figure out if the scale to use for div_fmas.
7836     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7837     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7838     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7839     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7840 
7841     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7842     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7843 
7844     SDValue Scale0Hi
7845       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7846     SDValue Scale1Hi
7847       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7848 
7849     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7850     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7851     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7852   } else {
7853     Scale = DivScale1.getValue(1);
7854   }
7855 
7856   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7857                              Fma4, Fma3, Mul, Scale);
7858 
7859   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7860 }
7861 
7862 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7863   EVT VT = Op.getValueType();
7864 
7865   if (VT == MVT::f32)
7866     return LowerFDIV32(Op, DAG);
7867 
7868   if (VT == MVT::f64)
7869     return LowerFDIV64(Op, DAG);
7870 
7871   if (VT == MVT::f16)
7872     return LowerFDIV16(Op, DAG);
7873 
7874   llvm_unreachable("Unexpected type for fdiv");
7875 }
7876 
7877 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7878   SDLoc DL(Op);
7879   StoreSDNode *Store = cast<StoreSDNode>(Op);
7880   EVT VT = Store->getMemoryVT();
7881 
7882   if (VT == MVT::i1) {
7883     return DAG.getTruncStore(Store->getChain(), DL,
7884        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7885        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7886   }
7887 
7888   assert(VT.isVector() &&
7889          Store->getValue().getValueType().getScalarType() == MVT::i32);
7890 
7891   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7892                                       VT, *Store->getMemOperand())) {
7893     return expandUnalignedStore(Store, DAG);
7894   }
7895 
7896   unsigned AS = Store->getAddressSpace();
7897   if (Subtarget->hasLDSMisalignedBug() &&
7898       AS == AMDGPUAS::FLAT_ADDRESS &&
7899       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7900     return SplitVectorStore(Op, DAG);
7901   }
7902 
7903   MachineFunction &MF = DAG.getMachineFunction();
7904   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7905   // If there is a possibilty that flat instruction access scratch memory
7906   // then we need to use the same legalization rules we use for private.
7907   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7908       !Subtarget->hasMultiDwordFlatScratchAddressing())
7909     AS = MFI->hasFlatScratchInit() ?
7910          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7911 
7912   unsigned NumElements = VT.getVectorNumElements();
7913   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7914       AS == AMDGPUAS::FLAT_ADDRESS) {
7915     if (NumElements > 4)
7916       return SplitVectorStore(Op, DAG);
7917     // v3 stores not supported on SI.
7918     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7919       return SplitVectorStore(Op, DAG);
7920     return SDValue();
7921   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7922     switch (Subtarget->getMaxPrivateElementSize()) {
7923     case 4:
7924       return scalarizeVectorStore(Store, DAG);
7925     case 8:
7926       if (NumElements > 2)
7927         return SplitVectorStore(Op, DAG);
7928       return SDValue();
7929     case 16:
7930       if (NumElements > 4 || NumElements == 3)
7931         return SplitVectorStore(Op, DAG);
7932       return SDValue();
7933     default:
7934       llvm_unreachable("unsupported private_element_size");
7935     }
7936   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7937     // Use ds_write_b128 if possible.
7938     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7939         VT.getStoreSize() == 16 && NumElements != 3)
7940       return SDValue();
7941 
7942     if (NumElements > 2)
7943       return SplitVectorStore(Op, DAG);
7944 
7945     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7946     // address is negative, then the instruction is incorrectly treated as
7947     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7948     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7949     // store later in the SILoadStoreOptimizer.
7950     if (!Subtarget->hasUsableDSOffset() &&
7951         NumElements == 2 && VT.getStoreSize() == 8 &&
7952         Store->getAlignment() < 8) {
7953       return SplitVectorStore(Op, DAG);
7954     }
7955 
7956     return SDValue();
7957   } else {
7958     llvm_unreachable("unhandled address space");
7959   }
7960 }
7961 
7962 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7963   SDLoc DL(Op);
7964   EVT VT = Op.getValueType();
7965   SDValue Arg = Op.getOperand(0);
7966   SDValue TrigVal;
7967 
7968   // TODO: Should this propagate fast-math-flags?
7969 
7970   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7971 
7972   if (Subtarget->hasTrigReducedRange()) {
7973     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7974     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7975   } else {
7976     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7977   }
7978 
7979   switch (Op.getOpcode()) {
7980   case ISD::FCOS:
7981     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7982   case ISD::FSIN:
7983     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7984   default:
7985     llvm_unreachable("Wrong trig opcode");
7986   }
7987 }
7988 
7989 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7990   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7991   assert(AtomicNode->isCompareAndSwap());
7992   unsigned AS = AtomicNode->getAddressSpace();
7993 
7994   // No custom lowering required for local address space
7995   if (!isFlatGlobalAddrSpace(AS))
7996     return Op;
7997 
7998   // Non-local address space requires custom lowering for atomic compare
7999   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8000   SDLoc DL(Op);
8001   SDValue ChainIn = Op.getOperand(0);
8002   SDValue Addr = Op.getOperand(1);
8003   SDValue Old = Op.getOperand(2);
8004   SDValue New = Op.getOperand(3);
8005   EVT VT = Op.getValueType();
8006   MVT SimpleVT = VT.getSimpleVT();
8007   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8008 
8009   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8010   SDValue Ops[] = { ChainIn, Addr, NewOld };
8011 
8012   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8013                                  Ops, VT, AtomicNode->getMemOperand());
8014 }
8015 
8016 //===----------------------------------------------------------------------===//
8017 // Custom DAG optimizations
8018 //===----------------------------------------------------------------------===//
8019 
8020 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8021                                                      DAGCombinerInfo &DCI) const {
8022   EVT VT = N->getValueType(0);
8023   EVT ScalarVT = VT.getScalarType();
8024   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8025     return SDValue();
8026 
8027   SelectionDAG &DAG = DCI.DAG;
8028   SDLoc DL(N);
8029 
8030   SDValue Src = N->getOperand(0);
8031   EVT SrcVT = Src.getValueType();
8032 
8033   // TODO: We could try to match extracting the higher bytes, which would be
8034   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8035   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8036   // about in practice.
8037   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8038     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8039       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8040       DCI.AddToWorklist(Cvt.getNode());
8041 
8042       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8043       if (ScalarVT != MVT::f32) {
8044         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8045                           DAG.getTargetConstant(0, DL, MVT::i32));
8046       }
8047       return Cvt;
8048     }
8049   }
8050 
8051   return SDValue();
8052 }
8053 
8054 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8055 
8056 // This is a variant of
8057 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8058 //
8059 // The normal DAG combiner will do this, but only if the add has one use since
8060 // that would increase the number of instructions.
8061 //
8062 // This prevents us from seeing a constant offset that can be folded into a
8063 // memory instruction's addressing mode. If we know the resulting add offset of
8064 // a pointer can be folded into an addressing offset, we can replace the pointer
8065 // operand with the add of new constant offset. This eliminates one of the uses,
8066 // and may allow the remaining use to also be simplified.
8067 //
8068 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8069                                                unsigned AddrSpace,
8070                                                EVT MemVT,
8071                                                DAGCombinerInfo &DCI) const {
8072   SDValue N0 = N->getOperand(0);
8073   SDValue N1 = N->getOperand(1);
8074 
8075   // We only do this to handle cases where it's profitable when there are
8076   // multiple uses of the add, so defer to the standard combine.
8077   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8078       N0->hasOneUse())
8079     return SDValue();
8080 
8081   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8082   if (!CN1)
8083     return SDValue();
8084 
8085   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8086   if (!CAdd)
8087     return SDValue();
8088 
8089   // If the resulting offset is too large, we can't fold it into the addressing
8090   // mode offset.
8091   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8092   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8093 
8094   AddrMode AM;
8095   AM.HasBaseReg = true;
8096   AM.BaseOffs = Offset.getSExtValue();
8097   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8098     return SDValue();
8099 
8100   SelectionDAG &DAG = DCI.DAG;
8101   SDLoc SL(N);
8102   EVT VT = N->getValueType(0);
8103 
8104   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8105   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8106 
8107   SDNodeFlags Flags;
8108   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8109                           (N0.getOpcode() == ISD::OR ||
8110                            N0->getFlags().hasNoUnsignedWrap()));
8111 
8112   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8113 }
8114 
8115 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8116                                                   DAGCombinerInfo &DCI) const {
8117   SDValue Ptr = N->getBasePtr();
8118   SelectionDAG &DAG = DCI.DAG;
8119   SDLoc SL(N);
8120 
8121   // TODO: We could also do this for multiplies.
8122   if (Ptr.getOpcode() == ISD::SHL) {
8123     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8124                                           N->getMemoryVT(), DCI);
8125     if (NewPtr) {
8126       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8127 
8128       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8129       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8130     }
8131   }
8132 
8133   return SDValue();
8134 }
8135 
8136 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8137   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8138          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8139          (Opc == ISD::XOR && Val == 0);
8140 }
8141 
8142 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8143 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8144 // integer combine opportunities since most 64-bit operations are decomposed
8145 // this way.  TODO: We won't want this for SALU especially if it is an inline
8146 // immediate.
8147 SDValue SITargetLowering::splitBinaryBitConstantOp(
8148   DAGCombinerInfo &DCI,
8149   const SDLoc &SL,
8150   unsigned Opc, SDValue LHS,
8151   const ConstantSDNode *CRHS) const {
8152   uint64_t Val = CRHS->getZExtValue();
8153   uint32_t ValLo = Lo_32(Val);
8154   uint32_t ValHi = Hi_32(Val);
8155   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8156 
8157     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8158          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8159         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8160     // If we need to materialize a 64-bit immediate, it will be split up later
8161     // anyway. Avoid creating the harder to understand 64-bit immediate
8162     // materialization.
8163     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8164   }
8165 
8166   return SDValue();
8167 }
8168 
8169 // Returns true if argument is a boolean value which is not serialized into
8170 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8171 static bool isBoolSGPR(SDValue V) {
8172   if (V.getValueType() != MVT::i1)
8173     return false;
8174   switch (V.getOpcode()) {
8175   default: break;
8176   case ISD::SETCC:
8177   case ISD::AND:
8178   case ISD::OR:
8179   case ISD::XOR:
8180   case AMDGPUISD::FP_CLASS:
8181     return true;
8182   }
8183   return false;
8184 }
8185 
8186 // If a constant has all zeroes or all ones within each byte return it.
8187 // Otherwise return 0.
8188 static uint32_t getConstantPermuteMask(uint32_t C) {
8189   // 0xff for any zero byte in the mask
8190   uint32_t ZeroByteMask = 0;
8191   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8192   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8193   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8194   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8195   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8196   if ((NonZeroByteMask & C) != NonZeroByteMask)
8197     return 0; // Partial bytes selected.
8198   return C;
8199 }
8200 
8201 // Check if a node selects whole bytes from its operand 0 starting at a byte
8202 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8203 // or -1 if not succeeded.
8204 // Note byte select encoding:
8205 // value 0-3 selects corresponding source byte;
8206 // value 0xc selects zero;
8207 // value 0xff selects 0xff.
8208 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8209   assert(V.getValueSizeInBits() == 32);
8210 
8211   if (V.getNumOperands() != 2)
8212     return ~0;
8213 
8214   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8215   if (!N1)
8216     return ~0;
8217 
8218   uint32_t C = N1->getZExtValue();
8219 
8220   switch (V.getOpcode()) {
8221   default:
8222     break;
8223   case ISD::AND:
8224     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8225       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8226     }
8227     break;
8228 
8229   case ISD::OR:
8230     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8231       return (0x03020100 & ~ConstMask) | ConstMask;
8232     }
8233     break;
8234 
8235   case ISD::SHL:
8236     if (C % 8)
8237       return ~0;
8238 
8239     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8240 
8241   case ISD::SRL:
8242     if (C % 8)
8243       return ~0;
8244 
8245     return uint32_t(0x0c0c0c0c03020100ull >> C);
8246   }
8247 
8248   return ~0;
8249 }
8250 
8251 SDValue SITargetLowering::performAndCombine(SDNode *N,
8252                                             DAGCombinerInfo &DCI) const {
8253   if (DCI.isBeforeLegalize())
8254     return SDValue();
8255 
8256   SelectionDAG &DAG = DCI.DAG;
8257   EVT VT = N->getValueType(0);
8258   SDValue LHS = N->getOperand(0);
8259   SDValue RHS = N->getOperand(1);
8260 
8261 
8262   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8263   if (VT == MVT::i64 && CRHS) {
8264     if (SDValue Split
8265         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8266       return Split;
8267   }
8268 
8269   if (CRHS && VT == MVT::i32) {
8270     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8271     // nb = number of trailing zeroes in mask
8272     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8273     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8274     uint64_t Mask = CRHS->getZExtValue();
8275     unsigned Bits = countPopulation(Mask);
8276     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8277         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8278       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8279         unsigned Shift = CShift->getZExtValue();
8280         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8281         unsigned Offset = NB + Shift;
8282         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8283           SDLoc SL(N);
8284           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8285                                     LHS->getOperand(0),
8286                                     DAG.getConstant(Offset, SL, MVT::i32),
8287                                     DAG.getConstant(Bits, SL, MVT::i32));
8288           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8289           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8290                                     DAG.getValueType(NarrowVT));
8291           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8292                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8293           return Shl;
8294         }
8295       }
8296     }
8297 
8298     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8299     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8300         isa<ConstantSDNode>(LHS.getOperand(2))) {
8301       uint32_t Sel = getConstantPermuteMask(Mask);
8302       if (!Sel)
8303         return SDValue();
8304 
8305       // Select 0xc for all zero bytes
8306       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8307       SDLoc DL(N);
8308       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8309                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8310     }
8311   }
8312 
8313   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8314   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8315   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8316     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8317     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8318 
8319     SDValue X = LHS.getOperand(0);
8320     SDValue Y = RHS.getOperand(0);
8321     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8322       return SDValue();
8323 
8324     if (LCC == ISD::SETO) {
8325       if (X != LHS.getOperand(1))
8326         return SDValue();
8327 
8328       if (RCC == ISD::SETUNE) {
8329         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8330         if (!C1 || !C1->isInfinity() || C1->isNegative())
8331           return SDValue();
8332 
8333         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8334                               SIInstrFlags::N_SUBNORMAL |
8335                               SIInstrFlags::N_ZERO |
8336                               SIInstrFlags::P_ZERO |
8337                               SIInstrFlags::P_SUBNORMAL |
8338                               SIInstrFlags::P_NORMAL;
8339 
8340         static_assert(((~(SIInstrFlags::S_NAN |
8341                           SIInstrFlags::Q_NAN |
8342                           SIInstrFlags::N_INFINITY |
8343                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8344                       "mask not equal");
8345 
8346         SDLoc DL(N);
8347         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8348                            X, DAG.getConstant(Mask, DL, MVT::i32));
8349       }
8350     }
8351   }
8352 
8353   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8354     std::swap(LHS, RHS);
8355 
8356   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8357       RHS.hasOneUse()) {
8358     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8359     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8360     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8361     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8362     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8363         (RHS.getOperand(0) == LHS.getOperand(0) &&
8364          LHS.getOperand(0) == LHS.getOperand(1))) {
8365       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8366       unsigned NewMask = LCC == ISD::SETO ?
8367         Mask->getZExtValue() & ~OrdMask :
8368         Mask->getZExtValue() & OrdMask;
8369 
8370       SDLoc DL(N);
8371       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8372                          DAG.getConstant(NewMask, DL, MVT::i32));
8373     }
8374   }
8375 
8376   if (VT == MVT::i32 &&
8377       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8378     // and x, (sext cc from i1) => select cc, x, 0
8379     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8380       std::swap(LHS, RHS);
8381     if (isBoolSGPR(RHS.getOperand(0)))
8382       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8383                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8384   }
8385 
8386   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8387   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8388   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8389       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8390     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8391     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8392     if (LHSMask != ~0u && RHSMask != ~0u) {
8393       // Canonicalize the expression in an attempt to have fewer unique masks
8394       // and therefore fewer registers used to hold the masks.
8395       if (LHSMask > RHSMask) {
8396         std::swap(LHSMask, RHSMask);
8397         std::swap(LHS, RHS);
8398       }
8399 
8400       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8401       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8402       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8403       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8404 
8405       // Check of we need to combine values from two sources within a byte.
8406       if (!(LHSUsedLanes & RHSUsedLanes) &&
8407           // If we select high and lower word keep it for SDWA.
8408           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8409           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8410         // Each byte in each mask is either selector mask 0-3, or has higher
8411         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8412         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8413         // mask which is not 0xff wins. By anding both masks we have a correct
8414         // result except that 0x0c shall be corrected to give 0x0c only.
8415         uint32_t Mask = LHSMask & RHSMask;
8416         for (unsigned I = 0; I < 32; I += 8) {
8417           uint32_t ByteSel = 0xff << I;
8418           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8419             Mask &= (0x0c << I) & 0xffffffff;
8420         }
8421 
8422         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8423         // or 0x0c.
8424         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8425         SDLoc DL(N);
8426 
8427         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8428                            LHS.getOperand(0), RHS.getOperand(0),
8429                            DAG.getConstant(Sel, DL, MVT::i32));
8430       }
8431     }
8432   }
8433 
8434   return SDValue();
8435 }
8436 
8437 SDValue SITargetLowering::performOrCombine(SDNode *N,
8438                                            DAGCombinerInfo &DCI) const {
8439   SelectionDAG &DAG = DCI.DAG;
8440   SDValue LHS = N->getOperand(0);
8441   SDValue RHS = N->getOperand(1);
8442 
8443   EVT VT = N->getValueType(0);
8444   if (VT == MVT::i1) {
8445     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8446     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8447         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8448       SDValue Src = LHS.getOperand(0);
8449       if (Src != RHS.getOperand(0))
8450         return SDValue();
8451 
8452       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8453       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8454       if (!CLHS || !CRHS)
8455         return SDValue();
8456 
8457       // Only 10 bits are used.
8458       static const uint32_t MaxMask = 0x3ff;
8459 
8460       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8461       SDLoc DL(N);
8462       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8463                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8464     }
8465 
8466     return SDValue();
8467   }
8468 
8469   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8470   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8471       LHS.getOpcode() == AMDGPUISD::PERM &&
8472       isa<ConstantSDNode>(LHS.getOperand(2))) {
8473     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8474     if (!Sel)
8475       return SDValue();
8476 
8477     Sel |= LHS.getConstantOperandVal(2);
8478     SDLoc DL(N);
8479     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8480                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8481   }
8482 
8483   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8484   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8485   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8486       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8487     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8488     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8489     if (LHSMask != ~0u && RHSMask != ~0u) {
8490       // Canonicalize the expression in an attempt to have fewer unique masks
8491       // and therefore fewer registers used to hold the masks.
8492       if (LHSMask > RHSMask) {
8493         std::swap(LHSMask, RHSMask);
8494         std::swap(LHS, RHS);
8495       }
8496 
8497       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8498       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8499       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8500       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8501 
8502       // Check of we need to combine values from two sources within a byte.
8503       if (!(LHSUsedLanes & RHSUsedLanes) &&
8504           // If we select high and lower word keep it for SDWA.
8505           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8506           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8507         // Kill zero bytes selected by other mask. Zero value is 0xc.
8508         LHSMask &= ~RHSUsedLanes;
8509         RHSMask &= ~LHSUsedLanes;
8510         // Add 4 to each active LHS lane
8511         LHSMask |= LHSUsedLanes & 0x04040404;
8512         // Combine masks
8513         uint32_t Sel = LHSMask | RHSMask;
8514         SDLoc DL(N);
8515 
8516         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8517                            LHS.getOperand(0), RHS.getOperand(0),
8518                            DAG.getConstant(Sel, DL, MVT::i32));
8519       }
8520     }
8521   }
8522 
8523   if (VT != MVT::i64)
8524     return SDValue();
8525 
8526   // TODO: This could be a generic combine with a predicate for extracting the
8527   // high half of an integer being free.
8528 
8529   // (or i64:x, (zero_extend i32:y)) ->
8530   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8531   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8532       RHS.getOpcode() != ISD::ZERO_EXTEND)
8533     std::swap(LHS, RHS);
8534 
8535   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8536     SDValue ExtSrc = RHS.getOperand(0);
8537     EVT SrcVT = ExtSrc.getValueType();
8538     if (SrcVT == MVT::i32) {
8539       SDLoc SL(N);
8540       SDValue LowLHS, HiBits;
8541       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8542       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8543 
8544       DCI.AddToWorklist(LowOr.getNode());
8545       DCI.AddToWorklist(HiBits.getNode());
8546 
8547       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8548                                 LowOr, HiBits);
8549       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8550     }
8551   }
8552 
8553   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8554   if (CRHS) {
8555     if (SDValue Split
8556           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8557       return Split;
8558   }
8559 
8560   return SDValue();
8561 }
8562 
8563 SDValue SITargetLowering::performXorCombine(SDNode *N,
8564                                             DAGCombinerInfo &DCI) const {
8565   EVT VT = N->getValueType(0);
8566   if (VT != MVT::i64)
8567     return SDValue();
8568 
8569   SDValue LHS = N->getOperand(0);
8570   SDValue RHS = N->getOperand(1);
8571 
8572   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8573   if (CRHS) {
8574     if (SDValue Split
8575           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8576       return Split;
8577   }
8578 
8579   return SDValue();
8580 }
8581 
8582 // Instructions that will be lowered with a final instruction that zeros the
8583 // high result bits.
8584 // XXX - probably only need to list legal operations.
8585 static bool fp16SrcZerosHighBits(unsigned Opc) {
8586   switch (Opc) {
8587   case ISD::FADD:
8588   case ISD::FSUB:
8589   case ISD::FMUL:
8590   case ISD::FDIV:
8591   case ISD::FREM:
8592   case ISD::FMA:
8593   case ISD::FMAD:
8594   case ISD::FCANONICALIZE:
8595   case ISD::FP_ROUND:
8596   case ISD::UINT_TO_FP:
8597   case ISD::SINT_TO_FP:
8598   case ISD::FABS:
8599     // Fabs is lowered to a bit operation, but it's an and which will clear the
8600     // high bits anyway.
8601   case ISD::FSQRT:
8602   case ISD::FSIN:
8603   case ISD::FCOS:
8604   case ISD::FPOWI:
8605   case ISD::FPOW:
8606   case ISD::FLOG:
8607   case ISD::FLOG2:
8608   case ISD::FLOG10:
8609   case ISD::FEXP:
8610   case ISD::FEXP2:
8611   case ISD::FCEIL:
8612   case ISD::FTRUNC:
8613   case ISD::FRINT:
8614   case ISD::FNEARBYINT:
8615   case ISD::FROUND:
8616   case ISD::FFLOOR:
8617   case ISD::FMINNUM:
8618   case ISD::FMAXNUM:
8619   case AMDGPUISD::FRACT:
8620   case AMDGPUISD::CLAMP:
8621   case AMDGPUISD::COS_HW:
8622   case AMDGPUISD::SIN_HW:
8623   case AMDGPUISD::FMIN3:
8624   case AMDGPUISD::FMAX3:
8625   case AMDGPUISD::FMED3:
8626   case AMDGPUISD::FMAD_FTZ:
8627   case AMDGPUISD::RCP:
8628   case AMDGPUISD::RSQ:
8629   case AMDGPUISD::RCP_IFLAG:
8630   case AMDGPUISD::LDEXP:
8631     return true;
8632   default:
8633     // fcopysign, select and others may be lowered to 32-bit bit operations
8634     // which don't zero the high bits.
8635     return false;
8636   }
8637 }
8638 
8639 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8640                                                    DAGCombinerInfo &DCI) const {
8641   if (!Subtarget->has16BitInsts() ||
8642       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8643     return SDValue();
8644 
8645   EVT VT = N->getValueType(0);
8646   if (VT != MVT::i32)
8647     return SDValue();
8648 
8649   SDValue Src = N->getOperand(0);
8650   if (Src.getValueType() != MVT::i16)
8651     return SDValue();
8652 
8653   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8654   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8655   if (Src.getOpcode() == ISD::BITCAST) {
8656     SDValue BCSrc = Src.getOperand(0);
8657     if (BCSrc.getValueType() == MVT::f16 &&
8658         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8659       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8660   }
8661 
8662   return SDValue();
8663 }
8664 
8665 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8666                                                         DAGCombinerInfo &DCI)
8667                                                         const {
8668   SDValue Src = N->getOperand(0);
8669   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8670 
8671   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8672       VTSign->getVT() == MVT::i8) ||
8673       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8674       VTSign->getVT() == MVT::i16)) &&
8675       Src.hasOneUse()) {
8676     auto *M = cast<MemSDNode>(Src);
8677     SDValue Ops[] = {
8678       Src.getOperand(0), // Chain
8679       Src.getOperand(1), // rsrc
8680       Src.getOperand(2), // vindex
8681       Src.getOperand(3), // voffset
8682       Src.getOperand(4), // soffset
8683       Src.getOperand(5), // offset
8684       Src.getOperand(6),
8685       Src.getOperand(7)
8686     };
8687     // replace with BUFFER_LOAD_BYTE/SHORT
8688     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8689                                          Src.getOperand(0).getValueType());
8690     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8691                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8692     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8693                                                           ResList,
8694                                                           Ops, M->getMemoryVT(),
8695                                                           M->getMemOperand());
8696     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8697                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8698   }
8699   return SDValue();
8700 }
8701 
8702 SDValue SITargetLowering::performClassCombine(SDNode *N,
8703                                               DAGCombinerInfo &DCI) const {
8704   SelectionDAG &DAG = DCI.DAG;
8705   SDValue Mask = N->getOperand(1);
8706 
8707   // fp_class x, 0 -> false
8708   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8709     if (CMask->isNullValue())
8710       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8711   }
8712 
8713   if (N->getOperand(0).isUndef())
8714     return DAG.getUNDEF(MVT::i1);
8715 
8716   return SDValue();
8717 }
8718 
8719 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8720                                             DAGCombinerInfo &DCI) const {
8721   EVT VT = N->getValueType(0);
8722   SDValue N0 = N->getOperand(0);
8723 
8724   if (N0.isUndef())
8725     return N0;
8726 
8727   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8728                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8729     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8730                            N->getFlags());
8731   }
8732 
8733   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8734     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8735                            N0.getOperand(0), N->getFlags());
8736   }
8737 
8738   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8739 }
8740 
8741 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8742                                        unsigned MaxDepth) const {
8743   unsigned Opcode = Op.getOpcode();
8744   if (Opcode == ISD::FCANONICALIZE)
8745     return true;
8746 
8747   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8748     auto F = CFP->getValueAPF();
8749     if (F.isNaN() && F.isSignaling())
8750       return false;
8751     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8752   }
8753 
8754   // If source is a result of another standard FP operation it is already in
8755   // canonical form.
8756   if (MaxDepth == 0)
8757     return false;
8758 
8759   switch (Opcode) {
8760   // These will flush denorms if required.
8761   case ISD::FADD:
8762   case ISD::FSUB:
8763   case ISD::FMUL:
8764   case ISD::FCEIL:
8765   case ISD::FFLOOR:
8766   case ISD::FMA:
8767   case ISD::FMAD:
8768   case ISD::FSQRT:
8769   case ISD::FDIV:
8770   case ISD::FREM:
8771   case ISD::FP_ROUND:
8772   case ISD::FP_EXTEND:
8773   case AMDGPUISD::FMUL_LEGACY:
8774   case AMDGPUISD::FMAD_FTZ:
8775   case AMDGPUISD::RCP:
8776   case AMDGPUISD::RSQ:
8777   case AMDGPUISD::RSQ_CLAMP:
8778   case AMDGPUISD::RCP_LEGACY:
8779   case AMDGPUISD::RCP_IFLAG:
8780   case AMDGPUISD::TRIG_PREOP:
8781   case AMDGPUISD::DIV_SCALE:
8782   case AMDGPUISD::DIV_FMAS:
8783   case AMDGPUISD::DIV_FIXUP:
8784   case AMDGPUISD::FRACT:
8785   case AMDGPUISD::LDEXP:
8786   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8787   case AMDGPUISD::CVT_F32_UBYTE0:
8788   case AMDGPUISD::CVT_F32_UBYTE1:
8789   case AMDGPUISD::CVT_F32_UBYTE2:
8790   case AMDGPUISD::CVT_F32_UBYTE3:
8791     return true;
8792 
8793   // It can/will be lowered or combined as a bit operation.
8794   // Need to check their input recursively to handle.
8795   case ISD::FNEG:
8796   case ISD::FABS:
8797   case ISD::FCOPYSIGN:
8798     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8799 
8800   case ISD::FSIN:
8801   case ISD::FCOS:
8802   case ISD::FSINCOS:
8803     return Op.getValueType().getScalarType() != MVT::f16;
8804 
8805   case ISD::FMINNUM:
8806   case ISD::FMAXNUM:
8807   case ISD::FMINNUM_IEEE:
8808   case ISD::FMAXNUM_IEEE:
8809   case AMDGPUISD::CLAMP:
8810   case AMDGPUISD::FMED3:
8811   case AMDGPUISD::FMAX3:
8812   case AMDGPUISD::FMIN3: {
8813     // FIXME: Shouldn't treat the generic operations different based these.
8814     // However, we aren't really required to flush the result from
8815     // minnum/maxnum..
8816 
8817     // snans will be quieted, so we only need to worry about denormals.
8818     if (Subtarget->supportsMinMaxDenormModes() ||
8819         denormalsEnabledForType(DAG, Op.getValueType()))
8820       return true;
8821 
8822     // Flushing may be required.
8823     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8824     // targets need to check their input recursively.
8825 
8826     // FIXME: Does this apply with clamp? It's implemented with max.
8827     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8828       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8829         return false;
8830     }
8831 
8832     return true;
8833   }
8834   case ISD::SELECT: {
8835     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8836            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8837   }
8838   case ISD::BUILD_VECTOR: {
8839     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8840       SDValue SrcOp = Op.getOperand(i);
8841       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8842         return false;
8843     }
8844 
8845     return true;
8846   }
8847   case ISD::EXTRACT_VECTOR_ELT:
8848   case ISD::EXTRACT_SUBVECTOR: {
8849     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8850   }
8851   case ISD::INSERT_VECTOR_ELT: {
8852     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8853            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8854   }
8855   case ISD::UNDEF:
8856     // Could be anything.
8857     return false;
8858 
8859   case ISD::BITCAST: {
8860     // Hack round the mess we make when legalizing extract_vector_elt
8861     SDValue Src = Op.getOperand(0);
8862     if (Src.getValueType() == MVT::i16 &&
8863         Src.getOpcode() == ISD::TRUNCATE) {
8864       SDValue TruncSrc = Src.getOperand(0);
8865       if (TruncSrc.getValueType() == MVT::i32 &&
8866           TruncSrc.getOpcode() == ISD::BITCAST &&
8867           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8868         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8869       }
8870     }
8871 
8872     return false;
8873   }
8874   case ISD::INTRINSIC_WO_CHAIN: {
8875     unsigned IntrinsicID
8876       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8877     // TODO: Handle more intrinsics
8878     switch (IntrinsicID) {
8879     case Intrinsic::amdgcn_cvt_pkrtz:
8880     case Intrinsic::amdgcn_cubeid:
8881     case Intrinsic::amdgcn_frexp_mant:
8882     case Intrinsic::amdgcn_fdot2:
8883     case Intrinsic::amdgcn_rcp:
8884     case Intrinsic::amdgcn_rsq:
8885     case Intrinsic::amdgcn_rsq_clamp:
8886     case Intrinsic::amdgcn_rcp_legacy:
8887     case Intrinsic::amdgcn_rsq_legacy:
8888       return true;
8889     default:
8890       break;
8891     }
8892 
8893     LLVM_FALLTHROUGH;
8894   }
8895   default:
8896     return denormalsEnabledForType(DAG, Op.getValueType()) &&
8897            DAG.isKnownNeverSNaN(Op);
8898   }
8899 
8900   llvm_unreachable("invalid operation");
8901 }
8902 
8903 // Constant fold canonicalize.
8904 SDValue SITargetLowering::getCanonicalConstantFP(
8905   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8906   // Flush denormals to 0 if not enabled.
8907   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
8908     return DAG.getConstantFP(0.0, SL, VT);
8909 
8910   if (C.isNaN()) {
8911     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8912     if (C.isSignaling()) {
8913       // Quiet a signaling NaN.
8914       // FIXME: Is this supposed to preserve payload bits?
8915       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8916     }
8917 
8918     // Make sure it is the canonical NaN bitpattern.
8919     //
8920     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8921     // immediate?
8922     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8923       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8924   }
8925 
8926   // Already canonical.
8927   return DAG.getConstantFP(C, SL, VT);
8928 }
8929 
8930 static bool vectorEltWillFoldAway(SDValue Op) {
8931   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8932 }
8933 
8934 SDValue SITargetLowering::performFCanonicalizeCombine(
8935   SDNode *N,
8936   DAGCombinerInfo &DCI) const {
8937   SelectionDAG &DAG = DCI.DAG;
8938   SDValue N0 = N->getOperand(0);
8939   EVT VT = N->getValueType(0);
8940 
8941   // fcanonicalize undef -> qnan
8942   if (N0.isUndef()) {
8943     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8944     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8945   }
8946 
8947   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8948     EVT VT = N->getValueType(0);
8949     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8950   }
8951 
8952   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8953   //                                                   (fcanonicalize k)
8954   //
8955   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8956 
8957   // TODO: This could be better with wider vectors that will be split to v2f16,
8958   // and to consider uses since there aren't that many packed operations.
8959   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8960       isTypeLegal(MVT::v2f16)) {
8961     SDLoc SL(N);
8962     SDValue NewElts[2];
8963     SDValue Lo = N0.getOperand(0);
8964     SDValue Hi = N0.getOperand(1);
8965     EVT EltVT = Lo.getValueType();
8966 
8967     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8968       for (unsigned I = 0; I != 2; ++I) {
8969         SDValue Op = N0.getOperand(I);
8970         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8971           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8972                                               CFP->getValueAPF());
8973         } else if (Op.isUndef()) {
8974           // Handled below based on what the other operand is.
8975           NewElts[I] = Op;
8976         } else {
8977           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8978         }
8979       }
8980 
8981       // If one half is undef, and one is constant, perfer a splat vector rather
8982       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8983       // cheaper to use and may be free with a packed operation.
8984       if (NewElts[0].isUndef()) {
8985         if (isa<ConstantFPSDNode>(NewElts[1]))
8986           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8987             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8988       }
8989 
8990       if (NewElts[1].isUndef()) {
8991         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8992           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8993       }
8994 
8995       return DAG.getBuildVector(VT, SL, NewElts);
8996     }
8997   }
8998 
8999   unsigned SrcOpc = N0.getOpcode();
9000 
9001   // If it's free to do so, push canonicalizes further up the source, which may
9002   // find a canonical source.
9003   //
9004   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9005   // sNaNs.
9006   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9007     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9008     if (CRHS && N0.hasOneUse()) {
9009       SDLoc SL(N);
9010       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9011                                    N0.getOperand(0));
9012       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9013       DCI.AddToWorklist(Canon0.getNode());
9014 
9015       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9016     }
9017   }
9018 
9019   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9020 }
9021 
9022 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9023   switch (Opc) {
9024   case ISD::FMAXNUM:
9025   case ISD::FMAXNUM_IEEE:
9026     return AMDGPUISD::FMAX3;
9027   case ISD::SMAX:
9028     return AMDGPUISD::SMAX3;
9029   case ISD::UMAX:
9030     return AMDGPUISD::UMAX3;
9031   case ISD::FMINNUM:
9032   case ISD::FMINNUM_IEEE:
9033     return AMDGPUISD::FMIN3;
9034   case ISD::SMIN:
9035     return AMDGPUISD::SMIN3;
9036   case ISD::UMIN:
9037     return AMDGPUISD::UMIN3;
9038   default:
9039     llvm_unreachable("Not a min/max opcode");
9040   }
9041 }
9042 
9043 SDValue SITargetLowering::performIntMed3ImmCombine(
9044   SelectionDAG &DAG, const SDLoc &SL,
9045   SDValue Op0, SDValue Op1, bool Signed) const {
9046   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9047   if (!K1)
9048     return SDValue();
9049 
9050   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9051   if (!K0)
9052     return SDValue();
9053 
9054   if (Signed) {
9055     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9056       return SDValue();
9057   } else {
9058     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9059       return SDValue();
9060   }
9061 
9062   EVT VT = K0->getValueType(0);
9063   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9064   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9065     return DAG.getNode(Med3Opc, SL, VT,
9066                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9067   }
9068 
9069   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9070   MVT NVT = MVT::i32;
9071   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9072 
9073   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9074   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9075   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9076 
9077   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9078   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9079 }
9080 
9081 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9082   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9083     return C;
9084 
9085   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9086     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9087       return C;
9088   }
9089 
9090   return nullptr;
9091 }
9092 
9093 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9094                                                   const SDLoc &SL,
9095                                                   SDValue Op0,
9096                                                   SDValue Op1) const {
9097   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9098   if (!K1)
9099     return SDValue();
9100 
9101   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9102   if (!K0)
9103     return SDValue();
9104 
9105   // Ordered >= (although NaN inputs should have folded away by now).
9106   if (K0->getValueAPF() > K1->getValueAPF())
9107     return SDValue();
9108 
9109   const MachineFunction &MF = DAG.getMachineFunction();
9110   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9111 
9112   // TODO: Check IEEE bit enabled?
9113   EVT VT = Op0.getValueType();
9114   if (Info->getMode().DX10Clamp) {
9115     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9116     // hardware fmed3 behavior converting to a min.
9117     // FIXME: Should this be allowing -0.0?
9118     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9119       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9120   }
9121 
9122   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9123   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9124     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9125     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9126     // then give the other result, which is different from med3 with a NaN
9127     // input.
9128     SDValue Var = Op0.getOperand(0);
9129     if (!DAG.isKnownNeverSNaN(Var))
9130       return SDValue();
9131 
9132     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9133 
9134     if ((!K0->hasOneUse() ||
9135          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9136         (!K1->hasOneUse() ||
9137          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9138       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9139                          Var, SDValue(K0, 0), SDValue(K1, 0));
9140     }
9141   }
9142 
9143   return SDValue();
9144 }
9145 
9146 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9147                                                DAGCombinerInfo &DCI) const {
9148   SelectionDAG &DAG = DCI.DAG;
9149 
9150   EVT VT = N->getValueType(0);
9151   unsigned Opc = N->getOpcode();
9152   SDValue Op0 = N->getOperand(0);
9153   SDValue Op1 = N->getOperand(1);
9154 
9155   // Only do this if the inner op has one use since this will just increases
9156   // register pressure for no benefit.
9157 
9158   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9159       !VT.isVector() &&
9160       (VT == MVT::i32 || VT == MVT::f32 ||
9161        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9162     // max(max(a, b), c) -> max3(a, b, c)
9163     // min(min(a, b), c) -> min3(a, b, c)
9164     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9165       SDLoc DL(N);
9166       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9167                          DL,
9168                          N->getValueType(0),
9169                          Op0.getOperand(0),
9170                          Op0.getOperand(1),
9171                          Op1);
9172     }
9173 
9174     // Try commuted.
9175     // max(a, max(b, c)) -> max3(a, b, c)
9176     // min(a, min(b, c)) -> min3(a, b, c)
9177     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9178       SDLoc DL(N);
9179       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9180                          DL,
9181                          N->getValueType(0),
9182                          Op0,
9183                          Op1.getOperand(0),
9184                          Op1.getOperand(1));
9185     }
9186   }
9187 
9188   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9189   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9190     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9191       return Med3;
9192   }
9193 
9194   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9195     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9196       return Med3;
9197   }
9198 
9199   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9200   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9201        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9202        (Opc == AMDGPUISD::FMIN_LEGACY &&
9203         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9204       (VT == MVT::f32 || VT == MVT::f64 ||
9205        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9206        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9207       Op0.hasOneUse()) {
9208     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9209       return Res;
9210   }
9211 
9212   return SDValue();
9213 }
9214 
9215 static bool isClampZeroToOne(SDValue A, SDValue B) {
9216   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9217     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9218       // FIXME: Should this be allowing -0.0?
9219       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9220              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9221     }
9222   }
9223 
9224   return false;
9225 }
9226 
9227 // FIXME: Should only worry about snans for version with chain.
9228 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9229                                               DAGCombinerInfo &DCI) const {
9230   EVT VT = N->getValueType(0);
9231   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9232   // NaNs. With a NaN input, the order of the operands may change the result.
9233 
9234   SelectionDAG &DAG = DCI.DAG;
9235   SDLoc SL(N);
9236 
9237   SDValue Src0 = N->getOperand(0);
9238   SDValue Src1 = N->getOperand(1);
9239   SDValue Src2 = N->getOperand(2);
9240 
9241   if (isClampZeroToOne(Src0, Src1)) {
9242     // const_a, const_b, x -> clamp is safe in all cases including signaling
9243     // nans.
9244     // FIXME: Should this be allowing -0.0?
9245     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9246   }
9247 
9248   const MachineFunction &MF = DAG.getMachineFunction();
9249   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9250 
9251   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9252   // handling no dx10-clamp?
9253   if (Info->getMode().DX10Clamp) {
9254     // If NaNs is clamped to 0, we are free to reorder the inputs.
9255 
9256     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9257       std::swap(Src0, Src1);
9258 
9259     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9260       std::swap(Src1, Src2);
9261 
9262     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9263       std::swap(Src0, Src1);
9264 
9265     if (isClampZeroToOne(Src1, Src2))
9266       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9267   }
9268 
9269   return SDValue();
9270 }
9271 
9272 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9273                                                  DAGCombinerInfo &DCI) const {
9274   SDValue Src0 = N->getOperand(0);
9275   SDValue Src1 = N->getOperand(1);
9276   if (Src0.isUndef() && Src1.isUndef())
9277     return DCI.DAG.getUNDEF(N->getValueType(0));
9278   return SDValue();
9279 }
9280 
9281 SDValue SITargetLowering::performExtractVectorEltCombine(
9282   SDNode *N, DAGCombinerInfo &DCI) const {
9283   SDValue Vec = N->getOperand(0);
9284   SelectionDAG &DAG = DCI.DAG;
9285 
9286   EVT VecVT = Vec.getValueType();
9287   EVT EltVT = VecVT.getVectorElementType();
9288 
9289   if ((Vec.getOpcode() == ISD::FNEG ||
9290        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9291     SDLoc SL(N);
9292     EVT EltVT = N->getValueType(0);
9293     SDValue Idx = N->getOperand(1);
9294     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9295                               Vec.getOperand(0), Idx);
9296     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9297   }
9298 
9299   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9300   //    =>
9301   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9302   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9303   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9304   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9305     SDLoc SL(N);
9306     EVT EltVT = N->getValueType(0);
9307     SDValue Idx = N->getOperand(1);
9308     unsigned Opc = Vec.getOpcode();
9309 
9310     switch(Opc) {
9311     default:
9312       break;
9313       // TODO: Support other binary operations.
9314     case ISD::FADD:
9315     case ISD::FSUB:
9316     case ISD::FMUL:
9317     case ISD::ADD:
9318     case ISD::UMIN:
9319     case ISD::UMAX:
9320     case ISD::SMIN:
9321     case ISD::SMAX:
9322     case ISD::FMAXNUM:
9323     case ISD::FMINNUM:
9324     case ISD::FMAXNUM_IEEE:
9325     case ISD::FMINNUM_IEEE: {
9326       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9327                                  Vec.getOperand(0), Idx);
9328       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9329                                  Vec.getOperand(1), Idx);
9330 
9331       DCI.AddToWorklist(Elt0.getNode());
9332       DCI.AddToWorklist(Elt1.getNode());
9333       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9334     }
9335     }
9336   }
9337 
9338   unsigned VecSize = VecVT.getSizeInBits();
9339   unsigned EltSize = EltVT.getSizeInBits();
9340 
9341   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9342   // This elminates non-constant index and subsequent movrel or scratch access.
9343   // Sub-dword vectors of size 2 dword or less have better implementation.
9344   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9345   // instructions.
9346   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9347       !isa<ConstantSDNode>(N->getOperand(1))) {
9348     SDLoc SL(N);
9349     SDValue Idx = N->getOperand(1);
9350     SDValue V;
9351     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9352       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9353       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9354       if (I == 0)
9355         V = Elt;
9356       else
9357         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9358     }
9359     return V;
9360   }
9361 
9362   if (!DCI.isBeforeLegalize())
9363     return SDValue();
9364 
9365   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9366   // elements. This exposes more load reduction opportunities by replacing
9367   // multiple small extract_vector_elements with a single 32-bit extract.
9368   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9369   if (isa<MemSDNode>(Vec) &&
9370       EltSize <= 16 &&
9371       EltVT.isByteSized() &&
9372       VecSize > 32 &&
9373       VecSize % 32 == 0 &&
9374       Idx) {
9375     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9376 
9377     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9378     unsigned EltIdx = BitIndex / 32;
9379     unsigned LeftoverBitIdx = BitIndex % 32;
9380     SDLoc SL(N);
9381 
9382     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9383     DCI.AddToWorklist(Cast.getNode());
9384 
9385     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9386                               DAG.getConstant(EltIdx, SL, MVT::i32));
9387     DCI.AddToWorklist(Elt.getNode());
9388     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9389                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9390     DCI.AddToWorklist(Srl.getNode());
9391 
9392     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9393     DCI.AddToWorklist(Trunc.getNode());
9394     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9395   }
9396 
9397   return SDValue();
9398 }
9399 
9400 SDValue
9401 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9402                                                 DAGCombinerInfo &DCI) const {
9403   SDValue Vec = N->getOperand(0);
9404   SDValue Idx = N->getOperand(2);
9405   EVT VecVT = Vec.getValueType();
9406   EVT EltVT = VecVT.getVectorElementType();
9407   unsigned VecSize = VecVT.getSizeInBits();
9408   unsigned EltSize = EltVT.getSizeInBits();
9409 
9410   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9411   // => BUILD_VECTOR n x select (e, const-idx)
9412   // This elminates non-constant index and subsequent movrel or scratch access.
9413   // Sub-dword vectors of size 2 dword or less have better implementation.
9414   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9415   // instructions.
9416   if (isa<ConstantSDNode>(Idx) ||
9417       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9418     return SDValue();
9419 
9420   SelectionDAG &DAG = DCI.DAG;
9421   SDLoc SL(N);
9422   SDValue Ins = N->getOperand(1);
9423   EVT IdxVT = Idx.getValueType();
9424 
9425   SmallVector<SDValue, 16> Ops;
9426   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9427     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9428     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9429     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9430     Ops.push_back(V);
9431   }
9432 
9433   return DAG.getBuildVector(VecVT, SL, Ops);
9434 }
9435 
9436 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9437                                           const SDNode *N0,
9438                                           const SDNode *N1) const {
9439   EVT VT = N0->getValueType(0);
9440 
9441   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9442   // support denormals ever.
9443   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9444        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9445         getSubtarget()->hasMadF16())) &&
9446        isOperationLegal(ISD::FMAD, VT))
9447     return ISD::FMAD;
9448 
9449   const TargetOptions &Options = DAG.getTarget().Options;
9450   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9451        (N0->getFlags().hasAllowContract() &&
9452         N1->getFlags().hasAllowContract())) &&
9453       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9454     return ISD::FMA;
9455   }
9456 
9457   return 0;
9458 }
9459 
9460 // For a reassociatable opcode perform:
9461 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9462 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9463                                                SelectionDAG &DAG) const {
9464   EVT VT = N->getValueType(0);
9465   if (VT != MVT::i32 && VT != MVT::i64)
9466     return SDValue();
9467 
9468   unsigned Opc = N->getOpcode();
9469   SDValue Op0 = N->getOperand(0);
9470   SDValue Op1 = N->getOperand(1);
9471 
9472   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9473     return SDValue();
9474 
9475   if (Op0->isDivergent())
9476     std::swap(Op0, Op1);
9477 
9478   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9479     return SDValue();
9480 
9481   SDValue Op2 = Op1.getOperand(1);
9482   Op1 = Op1.getOperand(0);
9483   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9484     return SDValue();
9485 
9486   if (Op1->isDivergent())
9487     std::swap(Op1, Op2);
9488 
9489   // If either operand is constant this will conflict with
9490   // DAGCombiner::ReassociateOps().
9491   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9492       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9493     return SDValue();
9494 
9495   SDLoc SL(N);
9496   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9497   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9498 }
9499 
9500 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9501                            EVT VT,
9502                            SDValue N0, SDValue N1, SDValue N2,
9503                            bool Signed) {
9504   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9505   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9506   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9507   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9508 }
9509 
9510 SDValue SITargetLowering::performAddCombine(SDNode *N,
9511                                             DAGCombinerInfo &DCI) const {
9512   SelectionDAG &DAG = DCI.DAG;
9513   EVT VT = N->getValueType(0);
9514   SDLoc SL(N);
9515   SDValue LHS = N->getOperand(0);
9516   SDValue RHS = N->getOperand(1);
9517 
9518   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9519       && Subtarget->hasMad64_32() &&
9520       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9521       VT.getScalarSizeInBits() <= 64) {
9522     if (LHS.getOpcode() != ISD::MUL)
9523       std::swap(LHS, RHS);
9524 
9525     SDValue MulLHS = LHS.getOperand(0);
9526     SDValue MulRHS = LHS.getOperand(1);
9527     SDValue AddRHS = RHS;
9528 
9529     // TODO: Maybe restrict if SGPR inputs.
9530     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9531         numBitsUnsigned(MulRHS, DAG) <= 32) {
9532       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9533       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9534       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9535       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9536     }
9537 
9538     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9539       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9540       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9541       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9542       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9543     }
9544 
9545     return SDValue();
9546   }
9547 
9548   if (SDValue V = reassociateScalarOps(N, DAG)) {
9549     return V;
9550   }
9551 
9552   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9553     return SDValue();
9554 
9555   // add x, zext (setcc) => addcarry x, 0, setcc
9556   // add x, sext (setcc) => subcarry x, 0, setcc
9557   unsigned Opc = LHS.getOpcode();
9558   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9559       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9560     std::swap(RHS, LHS);
9561 
9562   Opc = RHS.getOpcode();
9563   switch (Opc) {
9564   default: break;
9565   case ISD::ZERO_EXTEND:
9566   case ISD::SIGN_EXTEND:
9567   case ISD::ANY_EXTEND: {
9568     auto Cond = RHS.getOperand(0);
9569     // If this won't be a real VOPC output, we would still need to insert an
9570     // extra instruction anyway.
9571     if (!isBoolSGPR(Cond))
9572       break;
9573     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9574     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9575     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9576     return DAG.getNode(Opc, SL, VTList, Args);
9577   }
9578   case ISD::ADDCARRY: {
9579     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9580     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9581     if (!C || C->getZExtValue() != 0) break;
9582     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9583     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9584   }
9585   }
9586   return SDValue();
9587 }
9588 
9589 SDValue SITargetLowering::performSubCombine(SDNode *N,
9590                                             DAGCombinerInfo &DCI) const {
9591   SelectionDAG &DAG = DCI.DAG;
9592   EVT VT = N->getValueType(0);
9593 
9594   if (VT != MVT::i32)
9595     return SDValue();
9596 
9597   SDLoc SL(N);
9598   SDValue LHS = N->getOperand(0);
9599   SDValue RHS = N->getOperand(1);
9600 
9601   // sub x, zext (setcc) => subcarry x, 0, setcc
9602   // sub x, sext (setcc) => addcarry x, 0, setcc
9603   unsigned Opc = RHS.getOpcode();
9604   switch (Opc) {
9605   default: break;
9606   case ISD::ZERO_EXTEND:
9607   case ISD::SIGN_EXTEND:
9608   case ISD::ANY_EXTEND: {
9609     auto Cond = RHS.getOperand(0);
9610     // If this won't be a real VOPC output, we would still need to insert an
9611     // extra instruction anyway.
9612     if (!isBoolSGPR(Cond))
9613       break;
9614     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9615     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9616     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9617     return DAG.getNode(Opc, SL, VTList, Args);
9618   }
9619   }
9620 
9621   if (LHS.getOpcode() == ISD::SUBCARRY) {
9622     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9623     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9624     if (!C || !C->isNullValue())
9625       return SDValue();
9626     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9627     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9628   }
9629   return SDValue();
9630 }
9631 
9632 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9633   DAGCombinerInfo &DCI) const {
9634 
9635   if (N->getValueType(0) != MVT::i32)
9636     return SDValue();
9637 
9638   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9639   if (!C || C->getZExtValue() != 0)
9640     return SDValue();
9641 
9642   SelectionDAG &DAG = DCI.DAG;
9643   SDValue LHS = N->getOperand(0);
9644 
9645   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9646   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9647   unsigned LHSOpc = LHS.getOpcode();
9648   unsigned Opc = N->getOpcode();
9649   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9650       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9651     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9652     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9653   }
9654   return SDValue();
9655 }
9656 
9657 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9658                                              DAGCombinerInfo &DCI) const {
9659   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9660     return SDValue();
9661 
9662   SelectionDAG &DAG = DCI.DAG;
9663   EVT VT = N->getValueType(0);
9664 
9665   SDLoc SL(N);
9666   SDValue LHS = N->getOperand(0);
9667   SDValue RHS = N->getOperand(1);
9668 
9669   // These should really be instruction patterns, but writing patterns with
9670   // source modiifiers is a pain.
9671 
9672   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9673   if (LHS.getOpcode() == ISD::FADD) {
9674     SDValue A = LHS.getOperand(0);
9675     if (A == LHS.getOperand(1)) {
9676       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9677       if (FusedOp != 0) {
9678         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9679         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9680       }
9681     }
9682   }
9683 
9684   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9685   if (RHS.getOpcode() == ISD::FADD) {
9686     SDValue A = RHS.getOperand(0);
9687     if (A == RHS.getOperand(1)) {
9688       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9689       if (FusedOp != 0) {
9690         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9691         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9692       }
9693     }
9694   }
9695 
9696   return SDValue();
9697 }
9698 
9699 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9700                                              DAGCombinerInfo &DCI) const {
9701   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9702     return SDValue();
9703 
9704   SelectionDAG &DAG = DCI.DAG;
9705   SDLoc SL(N);
9706   EVT VT = N->getValueType(0);
9707   assert(!VT.isVector());
9708 
9709   // Try to get the fneg to fold into the source modifier. This undoes generic
9710   // DAG combines and folds them into the mad.
9711   //
9712   // Only do this if we are not trying to support denormals. v_mad_f32 does
9713   // not support denormals ever.
9714   SDValue LHS = N->getOperand(0);
9715   SDValue RHS = N->getOperand(1);
9716   if (LHS.getOpcode() == ISD::FADD) {
9717     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9718     SDValue A = LHS.getOperand(0);
9719     if (A == LHS.getOperand(1)) {
9720       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9721       if (FusedOp != 0){
9722         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9723         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9724 
9725         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9726       }
9727     }
9728   }
9729 
9730   if (RHS.getOpcode() == ISD::FADD) {
9731     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9732 
9733     SDValue A = RHS.getOperand(0);
9734     if (A == RHS.getOperand(1)) {
9735       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9736       if (FusedOp != 0){
9737         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9738         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9739       }
9740     }
9741   }
9742 
9743   return SDValue();
9744 }
9745 
9746 SDValue SITargetLowering::performFMACombine(SDNode *N,
9747                                             DAGCombinerInfo &DCI) const {
9748   SelectionDAG &DAG = DCI.DAG;
9749   EVT VT = N->getValueType(0);
9750   SDLoc SL(N);
9751 
9752   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9753     return SDValue();
9754 
9755   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9756   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9757   SDValue Op1 = N->getOperand(0);
9758   SDValue Op2 = N->getOperand(1);
9759   SDValue FMA = N->getOperand(2);
9760 
9761   if (FMA.getOpcode() != ISD::FMA ||
9762       Op1.getOpcode() != ISD::FP_EXTEND ||
9763       Op2.getOpcode() != ISD::FP_EXTEND)
9764     return SDValue();
9765 
9766   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9767   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9768   // is sufficient to allow generaing fdot2.
9769   const TargetOptions &Options = DAG.getTarget().Options;
9770   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9771       (N->getFlags().hasAllowContract() &&
9772        FMA->getFlags().hasAllowContract())) {
9773     Op1 = Op1.getOperand(0);
9774     Op2 = Op2.getOperand(0);
9775     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9776         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9777       return SDValue();
9778 
9779     SDValue Vec1 = Op1.getOperand(0);
9780     SDValue Idx1 = Op1.getOperand(1);
9781     SDValue Vec2 = Op2.getOperand(0);
9782 
9783     SDValue FMAOp1 = FMA.getOperand(0);
9784     SDValue FMAOp2 = FMA.getOperand(1);
9785     SDValue FMAAcc = FMA.getOperand(2);
9786 
9787     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9788         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9789       return SDValue();
9790 
9791     FMAOp1 = FMAOp1.getOperand(0);
9792     FMAOp2 = FMAOp2.getOperand(0);
9793     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9794         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9795       return SDValue();
9796 
9797     SDValue Vec3 = FMAOp1.getOperand(0);
9798     SDValue Vec4 = FMAOp2.getOperand(0);
9799     SDValue Idx2 = FMAOp1.getOperand(1);
9800 
9801     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9802         // Idx1 and Idx2 cannot be the same.
9803         Idx1 == Idx2)
9804       return SDValue();
9805 
9806     if (Vec1 == Vec2 || Vec3 == Vec4)
9807       return SDValue();
9808 
9809     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9810       return SDValue();
9811 
9812     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9813         (Vec1 == Vec4 && Vec2 == Vec3)) {
9814       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9815                          DAG.getTargetConstant(0, SL, MVT::i1));
9816     }
9817   }
9818   return SDValue();
9819 }
9820 
9821 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9822                                               DAGCombinerInfo &DCI) const {
9823   SelectionDAG &DAG = DCI.DAG;
9824   SDLoc SL(N);
9825 
9826   SDValue LHS = N->getOperand(0);
9827   SDValue RHS = N->getOperand(1);
9828   EVT VT = LHS.getValueType();
9829   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9830 
9831   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9832   if (!CRHS) {
9833     CRHS = dyn_cast<ConstantSDNode>(LHS);
9834     if (CRHS) {
9835       std::swap(LHS, RHS);
9836       CC = getSetCCSwappedOperands(CC);
9837     }
9838   }
9839 
9840   if (CRHS) {
9841     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9842         isBoolSGPR(LHS.getOperand(0))) {
9843       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9844       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9845       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9846       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9847       if ((CRHS->isAllOnesValue() &&
9848            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9849           (CRHS->isNullValue() &&
9850            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9851         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9852                            DAG.getConstant(-1, SL, MVT::i1));
9853       if ((CRHS->isAllOnesValue() &&
9854            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9855           (CRHS->isNullValue() &&
9856            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9857         return LHS.getOperand(0);
9858     }
9859 
9860     uint64_t CRHSVal = CRHS->getZExtValue();
9861     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9862         LHS.getOpcode() == ISD::SELECT &&
9863         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9864         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9865         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9866         isBoolSGPR(LHS.getOperand(0))) {
9867       // Given CT != FT:
9868       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9869       // setcc (select cc, CT, CF), CF, ne => cc
9870       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9871       // setcc (select cc, CT, CF), CT, eq => cc
9872       uint64_t CT = LHS.getConstantOperandVal(1);
9873       uint64_t CF = LHS.getConstantOperandVal(2);
9874 
9875       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9876           (CT == CRHSVal && CC == ISD::SETNE))
9877         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9878                            DAG.getConstant(-1, SL, MVT::i1));
9879       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9880           (CT == CRHSVal && CC == ISD::SETEQ))
9881         return LHS.getOperand(0);
9882     }
9883   }
9884 
9885   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9886                                            VT != MVT::f16))
9887     return SDValue();
9888 
9889   // Match isinf/isfinite pattern
9890   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9891   // (fcmp one (fabs x), inf) -> (fp_class x,
9892   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9893   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9894     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9895     if (!CRHS)
9896       return SDValue();
9897 
9898     const APFloat &APF = CRHS->getValueAPF();
9899     if (APF.isInfinity() && !APF.isNegative()) {
9900       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9901                                  SIInstrFlags::N_INFINITY;
9902       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9903                                     SIInstrFlags::P_ZERO |
9904                                     SIInstrFlags::N_NORMAL |
9905                                     SIInstrFlags::P_NORMAL |
9906                                     SIInstrFlags::N_SUBNORMAL |
9907                                     SIInstrFlags::P_SUBNORMAL;
9908       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9909       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9910                          DAG.getConstant(Mask, SL, MVT::i32));
9911     }
9912   }
9913 
9914   return SDValue();
9915 }
9916 
9917 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9918                                                      DAGCombinerInfo &DCI) const {
9919   SelectionDAG &DAG = DCI.DAG;
9920   SDLoc SL(N);
9921   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9922 
9923   SDValue Src = N->getOperand(0);
9924   SDValue Shift = N->getOperand(0);
9925 
9926   // TODO: Extend type shouldn't matter (assuming legal types).
9927   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
9928     Shift = Shift.getOperand(0);
9929 
9930   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
9931     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
9932     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
9933     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9934     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9935     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
9936     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
9937       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
9938                                  SDLoc(Shift.getOperand(0)), MVT::i32);
9939 
9940       unsigned ShiftOffset = 8 * Offset;
9941       if (Shift.getOpcode() == ISD::SHL)
9942         ShiftOffset -= C->getZExtValue();
9943       else
9944         ShiftOffset += C->getZExtValue();
9945 
9946       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
9947         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
9948                            MVT::f32, Shift);
9949       }
9950     }
9951   }
9952 
9953   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9954   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9955   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
9956     // We simplified Src. If this node is not dead, visit it again so it is
9957     // folded properly.
9958     if (N->getOpcode() != ISD::DELETED_NODE)
9959       DCI.AddToWorklist(N);
9960     return SDValue(N, 0);
9961   }
9962 
9963   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
9964   if (SDValue DemandedSrc =
9965           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
9966     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
9967 
9968   return SDValue();
9969 }
9970 
9971 SDValue SITargetLowering::performClampCombine(SDNode *N,
9972                                               DAGCombinerInfo &DCI) const {
9973   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9974   if (!CSrc)
9975     return SDValue();
9976 
9977   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9978   const APFloat &F = CSrc->getValueAPF();
9979   APFloat Zero = APFloat::getZero(F.getSemantics());
9980   if (F < Zero ||
9981       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9982     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9983   }
9984 
9985   APFloat One(F.getSemantics(), "1.0");
9986   if (F > One)
9987     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9988 
9989   return SDValue(CSrc, 0);
9990 }
9991 
9992 
9993 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9994                                             DAGCombinerInfo &DCI) const {
9995   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9996     return SDValue();
9997   switch (N->getOpcode()) {
9998   default:
9999     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10000   case ISD::ADD:
10001     return performAddCombine(N, DCI);
10002   case ISD::SUB:
10003     return performSubCombine(N, DCI);
10004   case ISD::ADDCARRY:
10005   case ISD::SUBCARRY:
10006     return performAddCarrySubCarryCombine(N, DCI);
10007   case ISD::FADD:
10008     return performFAddCombine(N, DCI);
10009   case ISD::FSUB:
10010     return performFSubCombine(N, DCI);
10011   case ISD::SETCC:
10012     return performSetCCCombine(N, DCI);
10013   case ISD::FMAXNUM:
10014   case ISD::FMINNUM:
10015   case ISD::FMAXNUM_IEEE:
10016   case ISD::FMINNUM_IEEE:
10017   case ISD::SMAX:
10018   case ISD::SMIN:
10019   case ISD::UMAX:
10020   case ISD::UMIN:
10021   case AMDGPUISD::FMIN_LEGACY:
10022   case AMDGPUISD::FMAX_LEGACY:
10023     return performMinMaxCombine(N, DCI);
10024   case ISD::FMA:
10025     return performFMACombine(N, DCI);
10026   case ISD::LOAD: {
10027     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10028       return Widended;
10029     LLVM_FALLTHROUGH;
10030   }
10031   case ISD::STORE:
10032   case ISD::ATOMIC_LOAD:
10033   case ISD::ATOMIC_STORE:
10034   case ISD::ATOMIC_CMP_SWAP:
10035   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10036   case ISD::ATOMIC_SWAP:
10037   case ISD::ATOMIC_LOAD_ADD:
10038   case ISD::ATOMIC_LOAD_SUB:
10039   case ISD::ATOMIC_LOAD_AND:
10040   case ISD::ATOMIC_LOAD_OR:
10041   case ISD::ATOMIC_LOAD_XOR:
10042   case ISD::ATOMIC_LOAD_NAND:
10043   case ISD::ATOMIC_LOAD_MIN:
10044   case ISD::ATOMIC_LOAD_MAX:
10045   case ISD::ATOMIC_LOAD_UMIN:
10046   case ISD::ATOMIC_LOAD_UMAX:
10047   case ISD::ATOMIC_LOAD_FADD:
10048   case AMDGPUISD::ATOMIC_INC:
10049   case AMDGPUISD::ATOMIC_DEC:
10050   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10051   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10052     if (DCI.isBeforeLegalize())
10053       break;
10054     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10055   case ISD::AND:
10056     return performAndCombine(N, DCI);
10057   case ISD::OR:
10058     return performOrCombine(N, DCI);
10059   case ISD::XOR:
10060     return performXorCombine(N, DCI);
10061   case ISD::ZERO_EXTEND:
10062     return performZeroExtendCombine(N, DCI);
10063   case ISD::SIGN_EXTEND_INREG:
10064     return performSignExtendInRegCombine(N , DCI);
10065   case AMDGPUISD::FP_CLASS:
10066     return performClassCombine(N, DCI);
10067   case ISD::FCANONICALIZE:
10068     return performFCanonicalizeCombine(N, DCI);
10069   case AMDGPUISD::RCP:
10070     return performRcpCombine(N, DCI);
10071   case AMDGPUISD::FRACT:
10072   case AMDGPUISD::RSQ:
10073   case AMDGPUISD::RCP_LEGACY:
10074   case AMDGPUISD::RCP_IFLAG:
10075   case AMDGPUISD::RSQ_CLAMP:
10076   case AMDGPUISD::LDEXP: {
10077     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10078     SDValue Src = N->getOperand(0);
10079     if (Src.isUndef())
10080       return Src;
10081     break;
10082   }
10083   case ISD::SINT_TO_FP:
10084   case ISD::UINT_TO_FP:
10085     return performUCharToFloatCombine(N, DCI);
10086   case AMDGPUISD::CVT_F32_UBYTE0:
10087   case AMDGPUISD::CVT_F32_UBYTE1:
10088   case AMDGPUISD::CVT_F32_UBYTE2:
10089   case AMDGPUISD::CVT_F32_UBYTE3:
10090     return performCvtF32UByteNCombine(N, DCI);
10091   case AMDGPUISD::FMED3:
10092     return performFMed3Combine(N, DCI);
10093   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10094     return performCvtPkRTZCombine(N, DCI);
10095   case AMDGPUISD::CLAMP:
10096     return performClampCombine(N, DCI);
10097   case ISD::SCALAR_TO_VECTOR: {
10098     SelectionDAG &DAG = DCI.DAG;
10099     EVT VT = N->getValueType(0);
10100 
10101     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10102     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10103       SDLoc SL(N);
10104       SDValue Src = N->getOperand(0);
10105       EVT EltVT = Src.getValueType();
10106       if (EltVT == MVT::f16)
10107         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10108 
10109       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10110       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10111     }
10112 
10113     break;
10114   }
10115   case ISD::EXTRACT_VECTOR_ELT:
10116     return performExtractVectorEltCombine(N, DCI);
10117   case ISD::INSERT_VECTOR_ELT:
10118     return performInsertVectorEltCombine(N, DCI);
10119   }
10120   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10121 }
10122 
10123 /// Helper function for adjustWritemask
10124 static unsigned SubIdx2Lane(unsigned Idx) {
10125   switch (Idx) {
10126   default: return 0;
10127   case AMDGPU::sub0: return 0;
10128   case AMDGPU::sub1: return 1;
10129   case AMDGPU::sub2: return 2;
10130   case AMDGPU::sub3: return 3;
10131   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10132   }
10133 }
10134 
10135 /// Adjust the writemask of MIMG instructions
10136 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10137                                           SelectionDAG &DAG) const {
10138   unsigned Opcode = Node->getMachineOpcode();
10139 
10140   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10141   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10142   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10143     return Node; // not implemented for D16
10144 
10145   SDNode *Users[5] = { nullptr };
10146   unsigned Lane = 0;
10147   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10148   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10149   unsigned NewDmask = 0;
10150   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10151   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10152   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10153                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10154   unsigned TFCLane = 0;
10155   bool HasChain = Node->getNumValues() > 1;
10156 
10157   if (OldDmask == 0) {
10158     // These are folded out, but on the chance it happens don't assert.
10159     return Node;
10160   }
10161 
10162   unsigned OldBitsSet = countPopulation(OldDmask);
10163   // Work out which is the TFE/LWE lane if that is enabled.
10164   if (UsesTFC) {
10165     TFCLane = OldBitsSet;
10166   }
10167 
10168   // Try to figure out the used register components
10169   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10170        I != E; ++I) {
10171 
10172     // Don't look at users of the chain.
10173     if (I.getUse().getResNo() != 0)
10174       continue;
10175 
10176     // Abort if we can't understand the usage
10177     if (!I->isMachineOpcode() ||
10178         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10179       return Node;
10180 
10181     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10182     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10183     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10184     // set, etc.
10185     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10186 
10187     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10188     if (UsesTFC && Lane == TFCLane) {
10189       Users[Lane] = *I;
10190     } else {
10191       // Set which texture component corresponds to the lane.
10192       unsigned Comp;
10193       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10194         Comp = countTrailingZeros(Dmask);
10195         Dmask &= ~(1 << Comp);
10196       }
10197 
10198       // Abort if we have more than one user per component.
10199       if (Users[Lane])
10200         return Node;
10201 
10202       Users[Lane] = *I;
10203       NewDmask |= 1 << Comp;
10204     }
10205   }
10206 
10207   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10208   bool NoChannels = !NewDmask;
10209   if (NoChannels) {
10210     if (!UsesTFC) {
10211       // No uses of the result and not using TFC. Then do nothing.
10212       return Node;
10213     }
10214     // If the original dmask has one channel - then nothing to do
10215     if (OldBitsSet == 1)
10216       return Node;
10217     // Use an arbitrary dmask - required for the instruction to work
10218     NewDmask = 1;
10219   }
10220   // Abort if there's no change
10221   if (NewDmask == OldDmask)
10222     return Node;
10223 
10224   unsigned BitsSet = countPopulation(NewDmask);
10225 
10226   // Check for TFE or LWE - increase the number of channels by one to account
10227   // for the extra return value
10228   // This will need adjustment for D16 if this is also included in
10229   // adjustWriteMask (this function) but at present D16 are excluded.
10230   unsigned NewChannels = BitsSet + UsesTFC;
10231 
10232   int NewOpcode =
10233       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10234   assert(NewOpcode != -1 &&
10235          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10236          "failed to find equivalent MIMG op");
10237 
10238   // Adjust the writemask in the node
10239   SmallVector<SDValue, 12> Ops;
10240   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10241   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10242   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10243 
10244   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10245 
10246   MVT ResultVT = NewChannels == 1 ?
10247     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10248                            NewChannels == 5 ? 8 : NewChannels);
10249   SDVTList NewVTList = HasChain ?
10250     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10251 
10252 
10253   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10254                                               NewVTList, Ops);
10255 
10256   if (HasChain) {
10257     // Update chain.
10258     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10259     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10260   }
10261 
10262   if (NewChannels == 1) {
10263     assert(Node->hasNUsesOfValue(1, 0));
10264     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10265                                       SDLoc(Node), Users[Lane]->getValueType(0),
10266                                       SDValue(NewNode, 0));
10267     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10268     return nullptr;
10269   }
10270 
10271   // Update the users of the node with the new indices
10272   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10273     SDNode *User = Users[i];
10274     if (!User) {
10275       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10276       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10277       if (i || !NoChannels)
10278         continue;
10279     } else {
10280       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10281       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10282     }
10283 
10284     switch (Idx) {
10285     default: break;
10286     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10287     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10288     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10289     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10290     }
10291   }
10292 
10293   DAG.RemoveDeadNode(Node);
10294   return nullptr;
10295 }
10296 
10297 static bool isFrameIndexOp(SDValue Op) {
10298   if (Op.getOpcode() == ISD::AssertZext)
10299     Op = Op.getOperand(0);
10300 
10301   return isa<FrameIndexSDNode>(Op);
10302 }
10303 
10304 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10305 /// with frame index operands.
10306 /// LLVM assumes that inputs are to these instructions are registers.
10307 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10308                                                         SelectionDAG &DAG) const {
10309   if (Node->getOpcode() == ISD::CopyToReg) {
10310     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10311     SDValue SrcVal = Node->getOperand(2);
10312 
10313     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10314     // to try understanding copies to physical registers.
10315     if (SrcVal.getValueType() == MVT::i1 &&
10316         Register::isPhysicalRegister(DestReg->getReg())) {
10317       SDLoc SL(Node);
10318       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10319       SDValue VReg = DAG.getRegister(
10320         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10321 
10322       SDNode *Glued = Node->getGluedNode();
10323       SDValue ToVReg
10324         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10325                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10326       SDValue ToResultReg
10327         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10328                            VReg, ToVReg.getValue(1));
10329       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10330       DAG.RemoveDeadNode(Node);
10331       return ToResultReg.getNode();
10332     }
10333   }
10334 
10335   SmallVector<SDValue, 8> Ops;
10336   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10337     if (!isFrameIndexOp(Node->getOperand(i))) {
10338       Ops.push_back(Node->getOperand(i));
10339       continue;
10340     }
10341 
10342     SDLoc DL(Node);
10343     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10344                                      Node->getOperand(i).getValueType(),
10345                                      Node->getOperand(i)), 0));
10346   }
10347 
10348   return DAG.UpdateNodeOperands(Node, Ops);
10349 }
10350 
10351 /// Fold the instructions after selecting them.
10352 /// Returns null if users were already updated.
10353 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10354                                           SelectionDAG &DAG) const {
10355   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10356   unsigned Opcode = Node->getMachineOpcode();
10357 
10358   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10359       !TII->isGather4(Opcode)) {
10360     return adjustWritemask(Node, DAG);
10361   }
10362 
10363   if (Opcode == AMDGPU::INSERT_SUBREG ||
10364       Opcode == AMDGPU::REG_SEQUENCE) {
10365     legalizeTargetIndependentNode(Node, DAG);
10366     return Node;
10367   }
10368 
10369   switch (Opcode) {
10370   case AMDGPU::V_DIV_SCALE_F32:
10371   case AMDGPU::V_DIV_SCALE_F64: {
10372     // Satisfy the operand register constraint when one of the inputs is
10373     // undefined. Ordinarily each undef value will have its own implicit_def of
10374     // a vreg, so force these to use a single register.
10375     SDValue Src0 = Node->getOperand(0);
10376     SDValue Src1 = Node->getOperand(1);
10377     SDValue Src2 = Node->getOperand(2);
10378 
10379     if ((Src0.isMachineOpcode() &&
10380          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10381         (Src0 == Src1 || Src0 == Src2))
10382       break;
10383 
10384     MVT VT = Src0.getValueType().getSimpleVT();
10385     const TargetRegisterClass *RC =
10386         getRegClassFor(VT, Src0.getNode()->isDivergent());
10387 
10388     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10389     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10390 
10391     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10392                                       UndefReg, Src0, SDValue());
10393 
10394     // src0 must be the same register as src1 or src2, even if the value is
10395     // undefined, so make sure we don't violate this constraint.
10396     if (Src0.isMachineOpcode() &&
10397         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10398       if (Src1.isMachineOpcode() &&
10399           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10400         Src0 = Src1;
10401       else if (Src2.isMachineOpcode() &&
10402                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10403         Src0 = Src2;
10404       else {
10405         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10406         Src0 = UndefReg;
10407         Src1 = UndefReg;
10408       }
10409     } else
10410       break;
10411 
10412     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10413     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10414       Ops.push_back(Node->getOperand(I));
10415 
10416     Ops.push_back(ImpDef.getValue(1));
10417     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10418   }
10419   default:
10420     break;
10421   }
10422 
10423   return Node;
10424 }
10425 
10426 /// Assign the register class depending on the number of
10427 /// bits set in the writemask
10428 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10429                                                      SDNode *Node) const {
10430   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10431 
10432   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10433 
10434   if (TII->isVOP3(MI.getOpcode())) {
10435     // Make sure constant bus requirements are respected.
10436     TII->legalizeOperandsVOP3(MRI, MI);
10437 
10438     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10439     // This saves a chain-copy of registers and better ballance register
10440     // use between vgpr and agpr as agpr tuples tend to be big.
10441     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10442       unsigned Opc = MI.getOpcode();
10443       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10444       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10445                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10446         if (I == -1)
10447           break;
10448         MachineOperand &Op = MI.getOperand(I);
10449         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10450              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10451             !Register::isVirtualRegister(Op.getReg()) ||
10452             !TRI->isAGPR(MRI, Op.getReg()))
10453           continue;
10454         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10455         if (!Src || !Src->isCopy() ||
10456             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10457           continue;
10458         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10459         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10460         // All uses of agpr64 and agpr32 can also accept vgpr except for
10461         // v_accvgpr_read, but we do not produce agpr reads during selection,
10462         // so no use checks are needed.
10463         MRI.setRegClass(Op.getReg(), NewRC);
10464       }
10465     }
10466 
10467     return;
10468   }
10469 
10470   // Replace unused atomics with the no return version.
10471   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10472   if (NoRetAtomicOp != -1) {
10473     if (!Node->hasAnyUseOfValue(0)) {
10474       MI.setDesc(TII->get(NoRetAtomicOp));
10475       MI.RemoveOperand(0);
10476       return;
10477     }
10478 
10479     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10480     // instruction, because the return type of these instructions is a vec2 of
10481     // the memory type, so it can be tied to the input operand.
10482     // This means these instructions always have a use, so we need to add a
10483     // special case to check if the atomic has only one extract_subreg use,
10484     // which itself has no uses.
10485     if ((Node->hasNUsesOfValue(1, 0) &&
10486          Node->use_begin()->isMachineOpcode() &&
10487          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10488          !Node->use_begin()->hasAnyUseOfValue(0))) {
10489       Register Def = MI.getOperand(0).getReg();
10490 
10491       // Change this into a noret atomic.
10492       MI.setDesc(TII->get(NoRetAtomicOp));
10493       MI.RemoveOperand(0);
10494 
10495       // If we only remove the def operand from the atomic instruction, the
10496       // extract_subreg will be left with a use of a vreg without a def.
10497       // So we need to insert an implicit_def to avoid machine verifier
10498       // errors.
10499       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10500               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10501     }
10502     return;
10503   }
10504 }
10505 
10506 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10507                               uint64_t Val) {
10508   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10509   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10510 }
10511 
10512 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10513                                                 const SDLoc &DL,
10514                                                 SDValue Ptr) const {
10515   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10516 
10517   // Build the half of the subregister with the constants before building the
10518   // full 128-bit register. If we are building multiple resource descriptors,
10519   // this will allow CSEing of the 2-component register.
10520   const SDValue Ops0[] = {
10521     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10522     buildSMovImm32(DAG, DL, 0),
10523     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10524     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10525     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10526   };
10527 
10528   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10529                                                 MVT::v2i32, Ops0), 0);
10530 
10531   // Combine the constants and the pointer.
10532   const SDValue Ops1[] = {
10533     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10534     Ptr,
10535     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10536     SubRegHi,
10537     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10538   };
10539 
10540   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10541 }
10542 
10543 /// Return a resource descriptor with the 'Add TID' bit enabled
10544 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10545 ///        of the resource descriptor) to create an offset, which is added to
10546 ///        the resource pointer.
10547 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10548                                            SDValue Ptr, uint32_t RsrcDword1,
10549                                            uint64_t RsrcDword2And3) const {
10550   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10551   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10552   if (RsrcDword1) {
10553     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10554                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10555                     0);
10556   }
10557 
10558   SDValue DataLo = buildSMovImm32(DAG, DL,
10559                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10560   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10561 
10562   const SDValue Ops[] = {
10563     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10564     PtrLo,
10565     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10566     PtrHi,
10567     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10568     DataLo,
10569     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10570     DataHi,
10571     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10572   };
10573 
10574   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10575 }
10576 
10577 //===----------------------------------------------------------------------===//
10578 //                         SI Inline Assembly Support
10579 //===----------------------------------------------------------------------===//
10580 
10581 std::pair<unsigned, const TargetRegisterClass *>
10582 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10583                                                StringRef Constraint,
10584                                                MVT VT) const {
10585   const TargetRegisterClass *RC = nullptr;
10586   if (Constraint.size() == 1) {
10587     const unsigned BitWidth = VT.getSizeInBits();
10588     switch (Constraint[0]) {
10589     default:
10590       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10591     case 's':
10592     case 'r':
10593       switch (BitWidth) {
10594       case 16:
10595         RC = &AMDGPU::SReg_32RegClass;
10596         break;
10597       case 64:
10598         RC = &AMDGPU::SGPR_64RegClass;
10599         break;
10600       default:
10601         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
10602         if (!RC)
10603           return std::make_pair(0U, nullptr);
10604         break;
10605       }
10606       break;
10607     case 'v':
10608       switch (BitWidth) {
10609       case 16:
10610         RC = &AMDGPU::VGPR_32RegClass;
10611         break;
10612       default:
10613         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
10614         if (!RC)
10615           return std::make_pair(0U, nullptr);
10616         break;
10617       }
10618       break;
10619     case 'a':
10620       if (!Subtarget->hasMAIInsts())
10621         break;
10622       switch (BitWidth) {
10623       case 16:
10624         RC = &AMDGPU::AGPR_32RegClass;
10625         break;
10626       default:
10627         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
10628         if (!RC)
10629           return std::make_pair(0U, nullptr);
10630         break;
10631       }
10632       break;
10633     }
10634     // We actually support i128, i16 and f16 as inline parameters
10635     // even if they are not reported as legal
10636     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10637                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10638       return std::make_pair(0U, RC);
10639   }
10640 
10641   if (Constraint.size() > 1) {
10642     if (Constraint[1] == 'v') {
10643       RC = &AMDGPU::VGPR_32RegClass;
10644     } else if (Constraint[1] == 's') {
10645       RC = &AMDGPU::SGPR_32RegClass;
10646     } else if (Constraint[1] == 'a') {
10647       RC = &AMDGPU::AGPR_32RegClass;
10648     }
10649 
10650     if (RC) {
10651       uint32_t Idx;
10652       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10653       if (!Failed && Idx < RC->getNumRegs())
10654         return std::make_pair(RC->getRegister(Idx), RC);
10655     }
10656   }
10657 
10658   // FIXME: Returns VS_32 for physical SGPR constraints
10659   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10660 }
10661 
10662 SITargetLowering::ConstraintType
10663 SITargetLowering::getConstraintType(StringRef Constraint) const {
10664   if (Constraint.size() == 1) {
10665     switch (Constraint[0]) {
10666     default: break;
10667     case 's':
10668     case 'v':
10669     case 'a':
10670       return C_RegisterClass;
10671     }
10672   }
10673   return TargetLowering::getConstraintType(Constraint);
10674 }
10675 
10676 // Figure out which registers should be reserved for stack access. Only after
10677 // the function is legalized do we know all of the non-spill stack objects or if
10678 // calls are present.
10679 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10680   MachineRegisterInfo &MRI = MF.getRegInfo();
10681   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10682   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10683   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10684 
10685   if (Info->isEntryFunction()) {
10686     // Callable functions have fixed registers used for stack access.
10687     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10688   }
10689 
10690   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10691                              Info->getStackPtrOffsetReg()));
10692   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10693     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10694 
10695   // We need to worry about replacing the default register with itself in case
10696   // of MIR testcases missing the MFI.
10697   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10698     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10699 
10700   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10701     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10702 
10703   Info->limitOccupancy(MF);
10704 
10705   if (ST.isWave32() && !MF.empty()) {
10706     // Add VCC_HI def because many instructions marked as imp-use VCC where
10707     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10708     // having a use of undef.
10709 
10710     const SIInstrInfo *TII = ST.getInstrInfo();
10711     DebugLoc DL;
10712 
10713     MachineBasicBlock &MBB = MF.front();
10714     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10715     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10716 
10717     for (auto &MBB : MF) {
10718       for (auto &MI : MBB) {
10719         TII->fixImplicitOperands(MI);
10720       }
10721     }
10722   }
10723 
10724   TargetLoweringBase::finalizeLowering(MF);
10725 }
10726 
10727 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10728                                                      KnownBits &Known,
10729                                                      const APInt &DemandedElts,
10730                                                      const SelectionDAG &DAG,
10731                                                      unsigned Depth) const {
10732   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10733                                                 DAG, Depth);
10734 
10735   // Set the high bits to zero based on the maximum allowed scratch size per
10736   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10737   // calculation won't overflow, so assume the sign bit is never set.
10738   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10739 }
10740 
10741 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10742   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10743   const Align CacheLineAlign = Align(64);
10744 
10745   // Pre-GFX10 target did not benefit from loop alignment
10746   if (!ML || DisableLoopAlignment ||
10747       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10748       getSubtarget()->hasInstFwdPrefetchBug())
10749     return PrefAlign;
10750 
10751   // On GFX10 I$ is 4 x 64 bytes cache lines.
10752   // By default prefetcher keeps one cache line behind and reads two ahead.
10753   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10754   // behind and one ahead.
10755   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10756   // If loop fits 64 bytes it always spans no more than two cache lines and
10757   // does not need an alignment.
10758   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10759   // Else if loop is less or equal 192 bytes we need two lines behind.
10760 
10761   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10762   const MachineBasicBlock *Header = ML->getHeader();
10763   if (Header->getAlignment() != PrefAlign)
10764     return Header->getAlignment(); // Already processed.
10765 
10766   unsigned LoopSize = 0;
10767   for (const MachineBasicBlock *MBB : ML->blocks()) {
10768     // If inner loop block is aligned assume in average half of the alignment
10769     // size to be added as nops.
10770     if (MBB != Header)
10771       LoopSize += MBB->getAlignment().value() / 2;
10772 
10773     for (const MachineInstr &MI : *MBB) {
10774       LoopSize += TII->getInstSizeInBytes(MI);
10775       if (LoopSize > 192)
10776         return PrefAlign;
10777     }
10778   }
10779 
10780   if (LoopSize <= 64)
10781     return PrefAlign;
10782 
10783   if (LoopSize <= 128)
10784     return CacheLineAlign;
10785 
10786   // If any of parent loops is surrounded by prefetch instructions do not
10787   // insert new for inner loop, which would reset parent's settings.
10788   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10789     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10790       auto I = Exit->getFirstNonDebugInstr();
10791       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10792         return CacheLineAlign;
10793     }
10794   }
10795 
10796   MachineBasicBlock *Pre = ML->getLoopPreheader();
10797   MachineBasicBlock *Exit = ML->getExitBlock();
10798 
10799   if (Pre && Exit) {
10800     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10801             TII->get(AMDGPU::S_INST_PREFETCH))
10802       .addImm(1); // prefetch 2 lines behind PC
10803 
10804     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10805             TII->get(AMDGPU::S_INST_PREFETCH))
10806       .addImm(2); // prefetch 1 line behind PC
10807   }
10808 
10809   return CacheLineAlign;
10810 }
10811 
10812 LLVM_ATTRIBUTE_UNUSED
10813 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10814   assert(N->getOpcode() == ISD::CopyFromReg);
10815   do {
10816     // Follow the chain until we find an INLINEASM node.
10817     N = N->getOperand(0).getNode();
10818     if (N->getOpcode() == ISD::INLINEASM ||
10819         N->getOpcode() == ISD::INLINEASM_BR)
10820       return true;
10821   } while (N->getOpcode() == ISD::CopyFromReg);
10822   return false;
10823 }
10824 
10825 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10826   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10827 {
10828   switch (N->getOpcode()) {
10829     case ISD::CopyFromReg:
10830     {
10831       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10832       const MachineFunction * MF = FLI->MF;
10833       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10834       const MachineRegisterInfo &MRI = MF->getRegInfo();
10835       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10836       Register Reg = R->getReg();
10837       if (Reg.isPhysical())
10838         return !TRI.isSGPRReg(MRI, Reg);
10839 
10840       if (MRI.isLiveIn(Reg)) {
10841         // workitem.id.x workitem.id.y workitem.id.z
10842         // Any VGPR formal argument is also considered divergent
10843         if (!TRI.isSGPRReg(MRI, Reg))
10844           return true;
10845         // Formal arguments of non-entry functions
10846         // are conservatively considered divergent
10847         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10848           return true;
10849         return false;
10850       }
10851       const Value *V = FLI->getValueFromVirtualReg(Reg);
10852       if (V)
10853         return KDA->isDivergent(V);
10854       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10855       return !TRI.isSGPRReg(MRI, Reg);
10856     }
10857     break;
10858     case ISD::LOAD: {
10859       const LoadSDNode *L = cast<LoadSDNode>(N);
10860       unsigned AS = L->getAddressSpace();
10861       // A flat load may access private memory.
10862       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10863     } break;
10864     case ISD::CALLSEQ_END:
10865     return true;
10866     break;
10867     case ISD::INTRINSIC_WO_CHAIN:
10868     {
10869 
10870     }
10871       return AMDGPU::isIntrinsicSourceOfDivergence(
10872       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10873     case ISD::INTRINSIC_W_CHAIN:
10874       return AMDGPU::isIntrinsicSourceOfDivergence(
10875       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10876   }
10877   return false;
10878 }
10879 
10880 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
10881                                                EVT VT) const {
10882   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10883   case MVT::f32:
10884     return hasFP32Denormals(DAG.getMachineFunction());
10885   case MVT::f64:
10886   case MVT::f16:
10887     return hasFP64FP16Denormals(DAG.getMachineFunction());
10888   default:
10889     return false;
10890   }
10891 }
10892 
10893 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10894                                                     const SelectionDAG &DAG,
10895                                                     bool SNaN,
10896                                                     unsigned Depth) const {
10897   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10898     const MachineFunction &MF = DAG.getMachineFunction();
10899     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10900 
10901     if (Info->getMode().DX10Clamp)
10902       return true; // Clamped to 0.
10903     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10904   }
10905 
10906   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10907                                                             SNaN, Depth);
10908 }
10909 
10910 TargetLowering::AtomicExpansionKind
10911 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10912   switch (RMW->getOperation()) {
10913   case AtomicRMWInst::FAdd: {
10914     Type *Ty = RMW->getType();
10915 
10916     // We don't have a way to support 16-bit atomics now, so just leave them
10917     // as-is.
10918     if (Ty->isHalfTy())
10919       return AtomicExpansionKind::None;
10920 
10921     if (!Ty->isFloatTy())
10922       return AtomicExpansionKind::CmpXChg;
10923 
10924     // TODO: Do have these for flat. Older targets also had them for buffers.
10925     unsigned AS = RMW->getPointerAddressSpace();
10926 
10927     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
10928       return RMW->use_empty() ? AtomicExpansionKind::None :
10929                                 AtomicExpansionKind::CmpXChg;
10930     }
10931 
10932     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10933       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10934   }
10935   default:
10936     break;
10937   }
10938 
10939   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10940 }
10941 
10942 const TargetRegisterClass *
10943 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
10944   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
10945   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10946   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
10947     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
10948                                                : &AMDGPU::SReg_32RegClass;
10949   if (!TRI->isSGPRClass(RC) && !isDivergent)
10950     return TRI->getEquivalentSGPRClass(RC);
10951   else if (TRI->isSGPRClass(RC) && isDivergent)
10952     return TRI->getEquivalentVGPRClass(RC);
10953 
10954   return RC;
10955 }
10956 
10957 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
10958 // uniform values (as produced by the mask results of control flow intrinsics)
10959 // used outside of divergent blocks. The phi users need to also be treated as
10960 // always uniform.
10961 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
10962                       unsigned WaveSize) {
10963   // FIXME: We asssume we never cast the mask results of a control flow
10964   // intrinsic.
10965   // Early exit if the type won't be consistent as a compile time hack.
10966   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
10967   if (!IT || IT->getBitWidth() != WaveSize)
10968     return false;
10969 
10970   if (!isa<Instruction>(V))
10971     return false;
10972   if (!Visited.insert(V).second)
10973     return false;
10974   bool Result = false;
10975   for (auto U : V->users()) {
10976     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
10977       if (V == U->getOperand(1)) {
10978         switch (Intrinsic->getIntrinsicID()) {
10979         default:
10980           Result = false;
10981           break;
10982         case Intrinsic::amdgcn_if_break:
10983         case Intrinsic::amdgcn_if:
10984         case Intrinsic::amdgcn_else:
10985           Result = true;
10986           break;
10987         }
10988       }
10989       if (V == U->getOperand(0)) {
10990         switch (Intrinsic->getIntrinsicID()) {
10991         default:
10992           Result = false;
10993           break;
10994         case Intrinsic::amdgcn_end_cf:
10995         case Intrinsic::amdgcn_loop:
10996           Result = true;
10997           break;
10998         }
10999       }
11000     } else {
11001       Result = hasCFUser(U, Visited, WaveSize);
11002     }
11003     if (Result)
11004       break;
11005   }
11006   return Result;
11007 }
11008 
11009 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11010                                                const Value *V) const {
11011   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11012     if (isa<InlineAsm>(CI->getCalledValue())) {
11013       // FIXME: This cannot give a correct answer. This should only trigger in
11014       // the case where inline asm returns mixed SGPR and VGPR results, used
11015       // outside the defining block. We don't have a specific result to
11016       // consider, so this assumes if any value is SGPR, the overall register
11017       // also needs to be SGPR.
11018       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11019       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11020           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11021       for (auto &TC : TargetConstraints) {
11022         if (TC.Type == InlineAsm::isOutput) {
11023           ComputeConstraintToUse(TC, SDValue());
11024           unsigned AssignedReg;
11025           const TargetRegisterClass *RC;
11026           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11027               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11028           if (RC) {
11029             MachineRegisterInfo &MRI = MF.getRegInfo();
11030             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11031               return true;
11032             else if (SIRI->isSGPRClass(RC))
11033               return true;
11034           }
11035         }
11036       }
11037     }
11038   }
11039   SmallPtrSet<const Value *, 16> Visited;
11040   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11041 }
11042