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