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 "SIDefines.h"
24 #include "SIInstrInfo.h"
25 #include "SIMachineFunctionInfo.h"
26 #include "SIRegisterInfo.h"
27 #include "MCTargetDesc/AMDGPUMCTargetDesc.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/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/CallingConvLower.h"
40 #include "llvm/CodeGen/DAGCombine.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineModuleInfo.h"
49 #include "llvm/CodeGen/MachineOperand.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetCallingConv.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/IR/Constants.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/DebugLoc.h"
59 #include "llvm/IR/DerivedTypes.h"
60 #include "llvm/IR/DiagnosticInfo.h"
61 #include "llvm/IR/Function.h"
62 #include "llvm/IR/GlobalValue.h"
63 #include "llvm/IR/InstrTypes.h"
64 #include "llvm/IR/Instruction.h"
65 #include "llvm/IR/Instructions.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/Type.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/CodeGen.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/KnownBits.h"
74 #include "llvm/Support/MachineValueType.h"
75 #include "llvm/Support/MathExtras.h"
76 #include "llvm/Target/TargetOptions.h"
77 #include <cassert>
78 #include <cmath>
79 #include <cstdint>
80 #include <iterator>
81 #include <tuple>
82 #include <utility>
83 #include <vector>
84 
85 using namespace llvm;
86 
87 #define DEBUG_TYPE "si-lower"
88 
89 STATISTIC(NumTailCalls, "Number of tail calls");
90 
91 static cl::opt<bool> EnableVGPRIndexMode(
92   "amdgpu-vgpr-index-mode",
93   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
94   cl::init(false));
95 
96 static cl::opt<bool> DisableLoopAlignment(
97   "amdgpu-disable-loop-alignment",
98   cl::desc("Do not align and prefetch loops"),
99   cl::init(false));
100 
101 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
102   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
103   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
104     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
105       return AMDGPU::SGPR0 + Reg;
106     }
107   }
108   llvm_unreachable("Cannot allocate sgpr");
109 }
110 
111 SITargetLowering::SITargetLowering(const TargetMachine &TM,
112                                    const GCNSubtarget &STI)
113     : AMDGPUTargetLowering(TM, STI),
114       Subtarget(&STI) {
115   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
116   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
117 
118   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
119   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
120 
121   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
122   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
123   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
124 
125   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
126   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
127 
128   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
129   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
130 
131   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
132   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
133 
134   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
135   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
136 
137   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
138   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
139 
140   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
141   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
142 
143   if (Subtarget->has16BitInsts()) {
144     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
145     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
146 
147     // Unless there are also VOP3P operations, not operations are really legal.
148     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
149     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
150     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
151     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
152   }
153 
154   if (Subtarget->hasMAIInsts()) {
155     addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
156     addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
157   }
158 
159   computeRegisterProperties(Subtarget->getRegisterInfo());
160 
161   // We need to custom lower vector stores from local memory
162   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
164   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
165   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
166   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
167   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
168   setOperationAction(ISD::LOAD, MVT::i1, Custom);
169   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
170 
171   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
174   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
175   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
176   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
177   setOperationAction(ISD::STORE, MVT::i1, Custom);
178   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
179 
180   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
181   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
182   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
183   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
184   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
185   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
186   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
187   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
188   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
189   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
190 
191   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
192   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
193 
194   setOperationAction(ISD::SELECT, MVT::i1, Promote);
195   setOperationAction(ISD::SELECT, MVT::i64, Custom);
196   setOperationAction(ISD::SELECT, MVT::f64, Promote);
197   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
198 
199   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
200   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
201   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
202   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
203   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
204 
205   setOperationAction(ISD::SETCC, MVT::i1, Promote);
206   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
207   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
208   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
209 
210   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
211   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
212 
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
218   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
219   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
220 
221   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
222   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
223   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
224   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
225   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
226   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
227 
228   setOperationAction(ISD::UADDO, MVT::i32, Legal);
229   setOperationAction(ISD::USUBO, MVT::i32, Legal);
230 
231   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
232   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
233 
234   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
235   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
236   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
237 
238 #if 0
239   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
240   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
241 #endif
242 
243   // We only support LOAD/STORE and vector manipulation ops for vectors
244   // with > 4 elements.
245   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
246                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
247                   MVT::v32i32, MVT::v32f32 }) {
248     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
249       switch (Op) {
250       case ISD::LOAD:
251       case ISD::STORE:
252       case ISD::BUILD_VECTOR:
253       case ISD::BITCAST:
254       case ISD::EXTRACT_VECTOR_ELT:
255       case ISD::INSERT_VECTOR_ELT:
256       case ISD::INSERT_SUBVECTOR:
257       case ISD::EXTRACT_SUBVECTOR:
258       case ISD::SCALAR_TO_VECTOR:
259         break;
260       case ISD::CONCAT_VECTORS:
261         setOperationAction(Op, VT, Custom);
262         break;
263       default:
264         setOperationAction(Op, VT, Expand);
265         break;
266       }
267     }
268   }
269 
270   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
271 
272   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
273   // is expanded to avoid having two separate loops in case the index is a VGPR.
274 
275   // Most operations are naturally 32-bit vector operations. We only support
276   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
277   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
278     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
279     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
280 
281     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
282     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
283 
284     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
285     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
286 
287     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
288     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
289   }
290 
291   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
292   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
293   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
294   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
295 
296   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
297   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
298 
299   // Avoid stack access for these.
300   // TODO: Generalize to more vector types.
301   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
302   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
303   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
304   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
305 
306   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
307   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
308   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
309   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
310   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
311 
312   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
313   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
314   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
315 
316   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
317   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
318   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
319   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
320 
321   // Deal with vec3 vector operations when widened to vec4.
322   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
323   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
324   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
325   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
326 
327   // Deal with vec5 vector operations when widened to vec8.
328   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
329   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
330   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
331   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
332 
333   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
334   // and output demarshalling
335   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
336   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
337 
338   // We can't return success/failure, only the old value,
339   // let LLVM add the comparison
340   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
341   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
342 
343   if (Subtarget->hasFlatAddressSpace()) {
344     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
345     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
346   }
347 
348   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
349   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
350 
351   // On SI this is s_memtime and s_memrealtime on VI.
352   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
353   setOperationAction(ISD::TRAP, MVT::Other, Custom);
354   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
355 
356   if (Subtarget->has16BitInsts()) {
357     setOperationAction(ISD::FLOG, MVT::f16, Custom);
358     setOperationAction(ISD::FEXP, MVT::f16, Custom);
359     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
360   }
361 
362   // v_mad_f32 does not support denormals according to some sources.
363   if (!Subtarget->hasFP32Denormals())
364     setOperationAction(ISD::FMAD, MVT::f32, Legal);
365 
366   if (!Subtarget->hasBFI()) {
367     // fcopysign can be done in a single instruction with BFI.
368     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
369     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
370   }
371 
372   if (!Subtarget->hasBCNT(32))
373     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
374 
375   if (!Subtarget->hasBCNT(64))
376     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
377 
378   if (Subtarget->hasFFBH())
379     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
380 
381   if (Subtarget->hasFFBL())
382     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
383 
384   // We only really have 32-bit BFE instructions (and 16-bit on VI).
385   //
386   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
387   // effort to match them now. We want this to be false for i64 cases when the
388   // extraction isn't restricted to the upper or lower half. Ideally we would
389   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
390   // span the midpoint are probably relatively rare, so don't worry about them
391   // for now.
392   if (Subtarget->hasBFE())
393     setHasExtractBitsInsn(true);
394 
395   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
396   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
397   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
398   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
399 
400 
401   // These are really only legal for ieee_mode functions. We should be avoiding
402   // them for functions that don't have ieee_mode enabled, so just say they are
403   // legal.
404   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
405   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
406   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
407   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
408 
409 
410   if (Subtarget->haveRoundOpsF64()) {
411     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
412     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
413     setOperationAction(ISD::FRINT, MVT::f64, Legal);
414   } else {
415     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
416     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
417     setOperationAction(ISD::FRINT, MVT::f64, Custom);
418     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
419   }
420 
421   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
422 
423   setOperationAction(ISD::FSIN, MVT::f32, Custom);
424   setOperationAction(ISD::FCOS, MVT::f32, Custom);
425   setOperationAction(ISD::FDIV, MVT::f32, Custom);
426   setOperationAction(ISD::FDIV, MVT::f64, Custom);
427 
428   if (Subtarget->has16BitInsts()) {
429     setOperationAction(ISD::Constant, MVT::i16, Legal);
430 
431     setOperationAction(ISD::SMIN, MVT::i16, Legal);
432     setOperationAction(ISD::SMAX, MVT::i16, Legal);
433 
434     setOperationAction(ISD::UMIN, MVT::i16, Legal);
435     setOperationAction(ISD::UMAX, MVT::i16, Legal);
436 
437     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
438     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
439 
440     setOperationAction(ISD::ROTR, MVT::i16, Promote);
441     setOperationAction(ISD::ROTL, MVT::i16, Promote);
442 
443     setOperationAction(ISD::SDIV, MVT::i16, Promote);
444     setOperationAction(ISD::UDIV, MVT::i16, Promote);
445     setOperationAction(ISD::SREM, MVT::i16, Promote);
446     setOperationAction(ISD::UREM, MVT::i16, Promote);
447 
448     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
449     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
450 
451     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
452     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
453     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
454     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
455     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
456 
457     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
458 
459     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
460 
461     setOperationAction(ISD::LOAD, MVT::i16, Custom);
462 
463     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
464 
465     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
466     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
467     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
468     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
469 
470     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
471     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
472     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
473     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
474 
475     // F16 - Constant Actions.
476     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
477 
478     // F16 - Load/Store Actions.
479     setOperationAction(ISD::LOAD, MVT::f16, Promote);
480     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
481     setOperationAction(ISD::STORE, MVT::f16, Promote);
482     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
483 
484     // F16 - VOP1 Actions.
485     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
486     setOperationAction(ISD::FCOS, MVT::f16, Promote);
487     setOperationAction(ISD::FSIN, MVT::f16, Promote);
488     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
489     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
490     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
491     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
492     setOperationAction(ISD::FROUND, MVT::f16, Custom);
493 
494     // F16 - VOP2 Actions.
495     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
496     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
497 
498     setOperationAction(ISD::FDIV, MVT::f16, Custom);
499 
500     // F16 - VOP3 Actions.
501     setOperationAction(ISD::FMA, MVT::f16, Legal);
502     if (!Subtarget->hasFP16Denormals() && STI.hasMadF16())
503       setOperationAction(ISD::FMAD, MVT::f16, Legal);
504 
505     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
506       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
507         switch (Op) {
508         case ISD::LOAD:
509         case ISD::STORE:
510         case ISD::BUILD_VECTOR:
511         case ISD::BITCAST:
512         case ISD::EXTRACT_VECTOR_ELT:
513         case ISD::INSERT_VECTOR_ELT:
514         case ISD::INSERT_SUBVECTOR:
515         case ISD::EXTRACT_SUBVECTOR:
516         case ISD::SCALAR_TO_VECTOR:
517           break;
518         case ISD::CONCAT_VECTORS:
519           setOperationAction(Op, VT, Custom);
520           break;
521         default:
522           setOperationAction(Op, VT, Expand);
523           break;
524         }
525       }
526     }
527 
528     // XXX - Do these do anything? Vector constants turn into build_vector.
529     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
530     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
531 
532     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
533     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
534 
535     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
536     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
537     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
538     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
539 
540     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
541     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
542     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
543     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
544 
545     setOperationAction(ISD::AND, MVT::v2i16, Promote);
546     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
547     setOperationAction(ISD::OR, MVT::v2i16, Promote);
548     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
549     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
550     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
551 
552     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
553     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
554     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
555     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
556 
557     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
558     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
559     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
560     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
561 
562     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
563     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
564     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
565     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
566 
567     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
568     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
569     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
570 
571     if (!Subtarget->hasVOP3PInsts()) {
572       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
573       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
574     }
575 
576     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
577     // This isn't really legal, but this avoids the legalizer unrolling it (and
578     // allows matching fneg (fabs x) patterns)
579     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
580 
581     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
582     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
583     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
584     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
585 
586     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
587     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
588 
589     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
590     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
591   }
592 
593   if (Subtarget->hasVOP3PInsts()) {
594     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
595     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
596     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
597     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
598     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
599     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
600     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
601     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
602     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
603     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
604 
605     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
606     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
607     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
608 
609     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
610     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
611 
612     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
613 
614     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
615     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
616 
617     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
618     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
619 
620     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
621     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
622     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
623     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
624     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
625     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
626 
627     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
628     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
629     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
630     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
631 
632     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
633     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
634     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
635 
636     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
637     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
638 
639     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
640     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
641     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
642 
643     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
644     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
645     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
646   }
647 
648   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
649   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
650 
651   if (Subtarget->has16BitInsts()) {
652     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
653     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
654     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
655     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
656   } else {
657     // Legalization hack.
658     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
659     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
660 
661     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
662     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
663   }
664 
665   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
666     setOperationAction(ISD::SELECT, VT, Custom);
667   }
668 
669   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
670   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
671   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
672   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
673   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
674   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
675   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
676 
677   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
678   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
679   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
680   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
681   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
682   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
683   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
684   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
685   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
686 
687   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
688   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
689   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
690   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
691   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
692   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
693   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
694   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
695 
696   setTargetDAGCombine(ISD::ADD);
697   setTargetDAGCombine(ISD::ADDCARRY);
698   setTargetDAGCombine(ISD::SUB);
699   setTargetDAGCombine(ISD::SUBCARRY);
700   setTargetDAGCombine(ISD::FADD);
701   setTargetDAGCombine(ISD::FSUB);
702   setTargetDAGCombine(ISD::FMINNUM);
703   setTargetDAGCombine(ISD::FMAXNUM);
704   setTargetDAGCombine(ISD::FMINNUM_IEEE);
705   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
706   setTargetDAGCombine(ISD::FMA);
707   setTargetDAGCombine(ISD::SMIN);
708   setTargetDAGCombine(ISD::SMAX);
709   setTargetDAGCombine(ISD::UMIN);
710   setTargetDAGCombine(ISD::UMAX);
711   setTargetDAGCombine(ISD::SETCC);
712   setTargetDAGCombine(ISD::AND);
713   setTargetDAGCombine(ISD::OR);
714   setTargetDAGCombine(ISD::XOR);
715   setTargetDAGCombine(ISD::SINT_TO_FP);
716   setTargetDAGCombine(ISD::UINT_TO_FP);
717   setTargetDAGCombine(ISD::FCANONICALIZE);
718   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
719   setTargetDAGCombine(ISD::ZERO_EXTEND);
720   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
721   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
722   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
723 
724   // All memory operations. Some folding on the pointer operand is done to help
725   // matching the constant offsets in the addressing modes.
726   setTargetDAGCombine(ISD::LOAD);
727   setTargetDAGCombine(ISD::STORE);
728   setTargetDAGCombine(ISD::ATOMIC_LOAD);
729   setTargetDAGCombine(ISD::ATOMIC_STORE);
730   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
731   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
732   setTargetDAGCombine(ISD::ATOMIC_SWAP);
733   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
734   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
735   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
736   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
737   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
738   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
739   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
740   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
741   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
742   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
743   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
744 
745   setSchedulingPreference(Sched::RegPressure);
746 }
747 
748 const GCNSubtarget *SITargetLowering::getSubtarget() const {
749   return Subtarget;
750 }
751 
752 //===----------------------------------------------------------------------===//
753 // TargetLowering queries
754 //===----------------------------------------------------------------------===//
755 
756 // v_mad_mix* support a conversion from f16 to f32.
757 //
758 // There is only one special case when denormals are enabled we don't currently,
759 // where this is OK to use.
760 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
761                                            EVT DestVT, EVT SrcVT) const {
762   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
763           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
764          DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
765          SrcVT.getScalarType() == MVT::f16;
766 }
767 
768 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
769   // SI has some legal vector types, but no legal vector operations. Say no
770   // shuffles are legal in order to prefer scalarizing some vector operations.
771   return false;
772 }
773 
774 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
775                                                     CallingConv::ID CC,
776                                                     EVT VT) const {
777   if (CC == CallingConv::AMDGPU_KERNEL)
778     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
779 
780   if (VT.isVector()) {
781     EVT ScalarVT = VT.getScalarType();
782     unsigned Size = ScalarVT.getSizeInBits();
783     if (Size == 32)
784       return ScalarVT.getSimpleVT();
785 
786     if (Size > 32)
787       return MVT::i32;
788 
789     if (Size == 16 && Subtarget->has16BitInsts())
790       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
791   } else if (VT.getSizeInBits() > 32)
792     return MVT::i32;
793 
794   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
795 }
796 
797 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
798                                                          CallingConv::ID CC,
799                                                          EVT VT) const {
800   if (CC == CallingConv::AMDGPU_KERNEL)
801     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
802 
803   if (VT.isVector()) {
804     unsigned NumElts = VT.getVectorNumElements();
805     EVT ScalarVT = VT.getScalarType();
806     unsigned Size = ScalarVT.getSizeInBits();
807 
808     if (Size == 32)
809       return NumElts;
810 
811     if (Size > 32)
812       return NumElts * ((Size + 31) / 32);
813 
814     if (Size == 16 && Subtarget->has16BitInsts())
815       return (NumElts + 1) / 2;
816   } else if (VT.getSizeInBits() > 32)
817     return (VT.getSizeInBits() + 31) / 32;
818 
819   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
820 }
821 
822 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
823   LLVMContext &Context, CallingConv::ID CC,
824   EVT VT, EVT &IntermediateVT,
825   unsigned &NumIntermediates, MVT &RegisterVT) const {
826   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
827     unsigned NumElts = VT.getVectorNumElements();
828     EVT ScalarVT = VT.getScalarType();
829     unsigned Size = ScalarVT.getSizeInBits();
830     if (Size == 32) {
831       RegisterVT = ScalarVT.getSimpleVT();
832       IntermediateVT = RegisterVT;
833       NumIntermediates = NumElts;
834       return NumIntermediates;
835     }
836 
837     if (Size > 32) {
838       RegisterVT = MVT::i32;
839       IntermediateVT = RegisterVT;
840       NumIntermediates = NumElts * ((Size + 31) / 32);
841       return NumIntermediates;
842     }
843 
844     // FIXME: We should fix the ABI to be the same on targets without 16-bit
845     // support, but unless we can properly handle 3-vectors, it will be still be
846     // inconsistent.
847     if (Size == 16 && Subtarget->has16BitInsts()) {
848       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
849       IntermediateVT = RegisterVT;
850       NumIntermediates = (NumElts + 1) / 2;
851       return NumIntermediates;
852     }
853   }
854 
855   return TargetLowering::getVectorTypeBreakdownForCallingConv(
856     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
857 }
858 
859 static MVT memVTFromAggregate(Type *Ty) {
860   // Only limited forms of aggregate type currently expected.
861   assert(Ty->isStructTy() && "Expected struct type");
862 
863 
864   Type *ElementType = nullptr;
865   unsigned NumElts;
866   if (Ty->getContainedType(0)->isVectorTy()) {
867     VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
868     ElementType = VecComponent->getElementType();
869     NumElts = VecComponent->getNumElements();
870   } else {
871     ElementType = Ty->getContainedType(0);
872     NumElts = 1;
873   }
874 
875   assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
876 
877   // Calculate the size of the memVT type from the aggregate
878   unsigned Pow2Elts = 0;
879   unsigned ElementSize;
880   switch (ElementType->getTypeID()) {
881     default:
882       llvm_unreachable("Unknown type!");
883     case Type::IntegerTyID:
884       ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
885       break;
886     case Type::HalfTyID:
887       ElementSize = 16;
888       break;
889     case Type::FloatTyID:
890       ElementSize = 32;
891       break;
892   }
893   unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
894   Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
895 
896   return MVT::getVectorVT(MVT::getVT(ElementType, false),
897                           Pow2Elts);
898 }
899 
900 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
901                                           const CallInst &CI,
902                                           MachineFunction &MF,
903                                           unsigned IntrID) const {
904   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
905           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
906     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
907                                                   (Intrinsic::ID)IntrID);
908     if (Attr.hasFnAttribute(Attribute::ReadNone))
909       return false;
910 
911     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
912 
913     if (RsrcIntr->IsImage) {
914       Info.ptrVal = MFI->getImagePSV(
915         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
916         CI.getArgOperand(RsrcIntr->RsrcArg));
917       Info.align.reset();
918     } else {
919       Info.ptrVal = MFI->getBufferPSV(
920         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
921         CI.getArgOperand(RsrcIntr->RsrcArg));
922     }
923 
924     Info.flags = MachineMemOperand::MODereferenceable;
925     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
926       Info.opc = ISD::INTRINSIC_W_CHAIN;
927       Info.memVT = MVT::getVT(CI.getType(), true);
928       if (Info.memVT == MVT::Other) {
929         // Some intrinsics return an aggregate type - special case to work out
930         // the correct memVT
931         Info.memVT = memVTFromAggregate(CI.getType());
932       }
933       Info.flags |= MachineMemOperand::MOLoad;
934     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
935       Info.opc = ISD::INTRINSIC_VOID;
936       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
937       Info.flags |= MachineMemOperand::MOStore;
938     } else {
939       // Atomic
940       Info.opc = ISD::INTRINSIC_W_CHAIN;
941       Info.memVT = MVT::getVT(CI.getType());
942       Info.flags = MachineMemOperand::MOLoad |
943                    MachineMemOperand::MOStore |
944                    MachineMemOperand::MODereferenceable;
945 
946       // XXX - Should this be volatile without known ordering?
947       Info.flags |= MachineMemOperand::MOVolatile;
948     }
949     return true;
950   }
951 
952   switch (IntrID) {
953   case Intrinsic::amdgcn_atomic_inc:
954   case Intrinsic::amdgcn_atomic_dec:
955   case Intrinsic::amdgcn_ds_ordered_add:
956   case Intrinsic::amdgcn_ds_ordered_swap:
957   case Intrinsic::amdgcn_ds_fadd:
958   case Intrinsic::amdgcn_ds_fmin:
959   case Intrinsic::amdgcn_ds_fmax: {
960     Info.opc = ISD::INTRINSIC_W_CHAIN;
961     Info.memVT = MVT::getVT(CI.getType());
962     Info.ptrVal = CI.getOperand(0);
963     Info.align.reset();
964     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
965 
966     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
967     if (!Vol->isZero())
968       Info.flags |= MachineMemOperand::MOVolatile;
969 
970     return true;
971   }
972   case Intrinsic::amdgcn_buffer_atomic_fadd: {
973     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
974 
975     Info.opc = ISD::INTRINSIC_VOID;
976     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
977     Info.ptrVal = MFI->getBufferPSV(
978       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
979       CI.getArgOperand(1));
980     Info.align.reset();
981     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
982 
983     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
984     if (!Vol || !Vol->isZero())
985       Info.flags |= MachineMemOperand::MOVolatile;
986 
987     return true;
988   }
989   case Intrinsic::amdgcn_global_atomic_fadd: {
990     Info.opc = ISD::INTRINSIC_VOID;
991     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
992                             ->getPointerElementType());
993     Info.ptrVal = CI.getOperand(0);
994     Info.align.reset();
995     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
996 
997     return true;
998   }
999   case Intrinsic::amdgcn_ds_append:
1000   case Intrinsic::amdgcn_ds_consume: {
1001     Info.opc = ISD::INTRINSIC_W_CHAIN;
1002     Info.memVT = MVT::getVT(CI.getType());
1003     Info.ptrVal = CI.getOperand(0);
1004     Info.align.reset();
1005     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1006 
1007     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1008     if (!Vol->isZero())
1009       Info.flags |= MachineMemOperand::MOVolatile;
1010 
1011     return true;
1012   }
1013   case Intrinsic::amdgcn_ds_gws_init:
1014   case Intrinsic::amdgcn_ds_gws_barrier:
1015   case Intrinsic::amdgcn_ds_gws_sema_v:
1016   case Intrinsic::amdgcn_ds_gws_sema_br:
1017   case Intrinsic::amdgcn_ds_gws_sema_p:
1018   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1019     Info.opc = ISD::INTRINSIC_VOID;
1020 
1021     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1022     Info.ptrVal =
1023         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1024 
1025     // This is an abstract access, but we need to specify a type and size.
1026     Info.memVT = MVT::i32;
1027     Info.size = 4;
1028     Info.align = Align(4);
1029 
1030     Info.flags = MachineMemOperand::MOStore;
1031     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1032       Info.flags = MachineMemOperand::MOLoad;
1033     return true;
1034   }
1035   default:
1036     return false;
1037   }
1038 }
1039 
1040 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1041                                             SmallVectorImpl<Value*> &Ops,
1042                                             Type *&AccessTy) const {
1043   switch (II->getIntrinsicID()) {
1044   case Intrinsic::amdgcn_atomic_inc:
1045   case Intrinsic::amdgcn_atomic_dec:
1046   case Intrinsic::amdgcn_ds_ordered_add:
1047   case Intrinsic::amdgcn_ds_ordered_swap:
1048   case Intrinsic::amdgcn_ds_fadd:
1049   case Intrinsic::amdgcn_ds_fmin:
1050   case Intrinsic::amdgcn_ds_fmax: {
1051     Value *Ptr = II->getArgOperand(0);
1052     AccessTy = II->getType();
1053     Ops.push_back(Ptr);
1054     return true;
1055   }
1056   default:
1057     return false;
1058   }
1059 }
1060 
1061 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1062   if (!Subtarget->hasFlatInstOffsets()) {
1063     // Flat instructions do not have offsets, and only have the register
1064     // address.
1065     return AM.BaseOffs == 0 && AM.Scale == 0;
1066   }
1067 
1068   // GFX9 added a 13-bit signed offset. When using regular flat instructions,
1069   // the sign bit is ignored and is treated as a 12-bit unsigned offset.
1070 
1071   // GFX10 shrinked signed offset to 12 bits. When using regular flat
1072   // instructions, the sign bit is also ignored and is treated as 11-bit
1073   // unsigned offset.
1074 
1075   if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
1076     return isUInt<11>(AM.BaseOffs) && AM.Scale == 0;
1077 
1078   // Just r + i
1079   return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
1080 }
1081 
1082 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1083   if (Subtarget->hasFlatGlobalInsts())
1084     return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
1085 
1086   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1087       // Assume the we will use FLAT for all global memory accesses
1088       // on VI.
1089       // FIXME: This assumption is currently wrong.  On VI we still use
1090       // MUBUF instructions for the r + i addressing mode.  As currently
1091       // implemented, the MUBUF instructions only work on buffer < 4GB.
1092       // It may be possible to support > 4GB buffers with MUBUF instructions,
1093       // by setting the stride value in the resource descriptor which would
1094       // increase the size limit to (stride * 4GB).  However, this is risky,
1095       // because it has never been validated.
1096     return isLegalFlatAddressingMode(AM);
1097   }
1098 
1099   return isLegalMUBUFAddressingMode(AM);
1100 }
1101 
1102 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1103   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1104   // additionally can do r + r + i with addr64. 32-bit has more addressing
1105   // mode options. Depending on the resource constant, it can also do
1106   // (i64 r0) + (i32 r1) * (i14 i).
1107   //
1108   // Private arrays end up using a scratch buffer most of the time, so also
1109   // assume those use MUBUF instructions. Scratch loads / stores are currently
1110   // implemented as mubuf instructions with offen bit set, so slightly
1111   // different than the normal addr64.
1112   if (!isUInt<12>(AM.BaseOffs))
1113     return false;
1114 
1115   // FIXME: Since we can split immediate into soffset and immediate offset,
1116   // would it make sense to allow any immediate?
1117 
1118   switch (AM.Scale) {
1119   case 0: // r + i or just i, depending on HasBaseReg.
1120     return true;
1121   case 1:
1122     return true; // We have r + r or r + i.
1123   case 2:
1124     if (AM.HasBaseReg) {
1125       // Reject 2 * r + r.
1126       return false;
1127     }
1128 
1129     // Allow 2 * r as r + r
1130     // Or  2 * r + i is allowed as r + r + i.
1131     return true;
1132   default: // Don't allow n * r
1133     return false;
1134   }
1135 }
1136 
1137 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1138                                              const AddrMode &AM, Type *Ty,
1139                                              unsigned AS, Instruction *I) const {
1140   // No global is ever allowed as a base.
1141   if (AM.BaseGV)
1142     return false;
1143 
1144   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1145     return isLegalGlobalAddressingMode(AM);
1146 
1147   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1148       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1149       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1150     // If the offset isn't a multiple of 4, it probably isn't going to be
1151     // correctly aligned.
1152     // FIXME: Can we get the real alignment here?
1153     if (AM.BaseOffs % 4 != 0)
1154       return isLegalMUBUFAddressingMode(AM);
1155 
1156     // There are no SMRD extloads, so if we have to do a small type access we
1157     // will use a MUBUF load.
1158     // FIXME?: We also need to do this if unaligned, but we don't know the
1159     // alignment here.
1160     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1161       return isLegalGlobalAddressingMode(AM);
1162 
1163     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1164       // SMRD instructions have an 8-bit, dword offset on SI.
1165       if (!isUInt<8>(AM.BaseOffs / 4))
1166         return false;
1167     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1168       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1169       // in 8-bits, it can use a smaller encoding.
1170       if (!isUInt<32>(AM.BaseOffs / 4))
1171         return false;
1172     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1173       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1174       if (!isUInt<20>(AM.BaseOffs))
1175         return false;
1176     } else
1177       llvm_unreachable("unhandled generation");
1178 
1179     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1180       return true;
1181 
1182     if (AM.Scale == 1 && AM.HasBaseReg)
1183       return true;
1184 
1185     return false;
1186 
1187   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1188     return isLegalMUBUFAddressingMode(AM);
1189   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1190              AS == AMDGPUAS::REGION_ADDRESS) {
1191     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1192     // field.
1193     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1194     // an 8-bit dword offset but we don't know the alignment here.
1195     if (!isUInt<16>(AM.BaseOffs))
1196       return false;
1197 
1198     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1199       return true;
1200 
1201     if (AM.Scale == 1 && AM.HasBaseReg)
1202       return true;
1203 
1204     return false;
1205   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1206              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1207     // For an unknown address space, this usually means that this is for some
1208     // reason being used for pure arithmetic, and not based on some addressing
1209     // computation. We don't have instructions that compute pointers with any
1210     // addressing modes, so treat them as having no offset like flat
1211     // instructions.
1212     return isLegalFlatAddressingMode(AM);
1213   } else {
1214     llvm_unreachable("unhandled address space");
1215   }
1216 }
1217 
1218 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1219                                         const SelectionDAG &DAG) const {
1220   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1221     return (MemVT.getSizeInBits() <= 4 * 32);
1222   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1223     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1224     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1225   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1226     return (MemVT.getSizeInBits() <= 2 * 32);
1227   }
1228   return true;
1229 }
1230 
1231 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1232     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1233     bool *IsFast) const {
1234   if (IsFast)
1235     *IsFast = false;
1236 
1237   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1238   // which isn't a simple VT.
1239   // Until MVT is extended to handle this, simply check for the size and
1240   // rely on the condition below: allow accesses if the size is a multiple of 4.
1241   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1242                            VT.getStoreSize() > 16)) {
1243     return false;
1244   }
1245 
1246   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1247       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1248     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1249     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1250     // with adjacent offsets.
1251     bool AlignedBy4 = (Align % 4 == 0);
1252     if (IsFast)
1253       *IsFast = AlignedBy4;
1254 
1255     return AlignedBy4;
1256   }
1257 
1258   // FIXME: We have to be conservative here and assume that flat operations
1259   // will access scratch.  If we had access to the IR function, then we
1260   // could determine if any private memory was used in the function.
1261   if (!Subtarget->hasUnalignedScratchAccess() &&
1262       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1263        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1264     bool AlignedBy4 = Align >= 4;
1265     if (IsFast)
1266       *IsFast = AlignedBy4;
1267 
1268     return AlignedBy4;
1269   }
1270 
1271   if (Subtarget->hasUnalignedBufferAccess()) {
1272     // If we have an uniform constant load, it still requires using a slow
1273     // buffer instruction if unaligned.
1274     if (IsFast) {
1275       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1276                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1277         (Align % 4 == 0) : true;
1278     }
1279 
1280     return true;
1281   }
1282 
1283   // Smaller than dword value must be aligned.
1284   if (VT.bitsLT(MVT::i32))
1285     return false;
1286 
1287   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1288   // byte-address are ignored, thus forcing Dword alignment.
1289   // This applies to private, global, and constant memory.
1290   if (IsFast)
1291     *IsFast = true;
1292 
1293   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1294 }
1295 
1296 EVT SITargetLowering::getOptimalMemOpType(
1297     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
1298     bool ZeroMemset, bool MemcpyStrSrc,
1299     const AttributeList &FuncAttributes) const {
1300   // FIXME: Should account for address space here.
1301 
1302   // The default fallback uses the private pointer size as a guess for a type to
1303   // use. Make sure we switch these to 64-bit accesses.
1304 
1305   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1306     return MVT::v4i32;
1307 
1308   if (Size >= 8 && DstAlign >= 4)
1309     return MVT::v2i32;
1310 
1311   // Use the default.
1312   return MVT::Other;
1313 }
1314 
1315 static bool isFlatGlobalAddrSpace(unsigned AS) {
1316   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
1317          AS == AMDGPUAS::FLAT_ADDRESS ||
1318          AS == AMDGPUAS::CONSTANT_ADDRESS ||
1319          AS > AMDGPUAS::MAX_AMDGPU_ADDRESS;
1320 }
1321 
1322 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1323                                            unsigned DestAS) const {
1324   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1325 }
1326 
1327 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1328   const MemSDNode *MemNode = cast<MemSDNode>(N);
1329   const Value *Ptr = MemNode->getMemOperand()->getValue();
1330   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1331   return I && I->getMetadata("amdgpu.noclobber");
1332 }
1333 
1334 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1335                                            unsigned DestAS) const {
1336   // Flat -> private/local is a simple truncate.
1337   // Flat -> global is no-op
1338   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1339     return true;
1340 
1341   return isNoopAddrSpaceCast(SrcAS, DestAS);
1342 }
1343 
1344 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1345   const MemSDNode *MemNode = cast<MemSDNode>(N);
1346 
1347   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1348 }
1349 
1350 TargetLoweringBase::LegalizeTypeAction
1351 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1352   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1353     return TypeSplitVector;
1354 
1355   return TargetLoweringBase::getPreferredVectorAction(VT);
1356 }
1357 
1358 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1359                                                          Type *Ty) const {
1360   // FIXME: Could be smarter if called for vector constants.
1361   return true;
1362 }
1363 
1364 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1365   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1366     switch (Op) {
1367     case ISD::LOAD:
1368     case ISD::STORE:
1369 
1370     // These operations are done with 32-bit instructions anyway.
1371     case ISD::AND:
1372     case ISD::OR:
1373     case ISD::XOR:
1374     case ISD::SELECT:
1375       // TODO: Extensions?
1376       return true;
1377     default:
1378       return false;
1379     }
1380   }
1381 
1382   // SimplifySetCC uses this function to determine whether or not it should
1383   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1384   if (VT == MVT::i1 && Op == ISD::SETCC)
1385     return false;
1386 
1387   return TargetLowering::isTypeDesirableForOp(Op, VT);
1388 }
1389 
1390 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1391                                                    const SDLoc &SL,
1392                                                    SDValue Chain,
1393                                                    uint64_t Offset) const {
1394   const DataLayout &DL = DAG.getDataLayout();
1395   MachineFunction &MF = DAG.getMachineFunction();
1396   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1397 
1398   const ArgDescriptor *InputPtrReg;
1399   const TargetRegisterClass *RC;
1400 
1401   std::tie(InputPtrReg, RC)
1402     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1403 
1404   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1405   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1406   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1407     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1408 
1409   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1410 }
1411 
1412 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1413                                             const SDLoc &SL) const {
1414   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1415                                                FIRST_IMPLICIT);
1416   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1417 }
1418 
1419 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1420                                          const SDLoc &SL, SDValue Val,
1421                                          bool Signed,
1422                                          const ISD::InputArg *Arg) const {
1423   // First, if it is a widened vector, narrow it.
1424   if (VT.isVector() &&
1425       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1426     EVT NarrowedVT =
1427         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1428                          VT.getVectorNumElements());
1429     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1430                       DAG.getConstant(0, SL, MVT::i32));
1431   }
1432 
1433   // Then convert the vector elements or scalar value.
1434   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1435       VT.bitsLT(MemVT)) {
1436     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1437     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1438   }
1439 
1440   if (MemVT.isFloatingPoint())
1441     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1442   else if (Signed)
1443     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1444   else
1445     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1446 
1447   return Val;
1448 }
1449 
1450 SDValue SITargetLowering::lowerKernargMemParameter(
1451   SelectionDAG &DAG, EVT VT, EVT MemVT,
1452   const SDLoc &SL, SDValue Chain,
1453   uint64_t Offset, unsigned Align, bool Signed,
1454   const ISD::InputArg *Arg) const {
1455   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1456   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
1457   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1458 
1459   // Try to avoid using an extload by loading earlier than the argument address,
1460   // and extracting the relevant bits. The load should hopefully be merged with
1461   // the previous argument.
1462   if (MemVT.getStoreSize() < 4 && Align < 4) {
1463     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1464     int64_t AlignDownOffset = alignDown(Offset, 4);
1465     int64_t OffsetDiff = Offset - AlignDownOffset;
1466 
1467     EVT IntVT = MemVT.changeTypeToInteger();
1468 
1469     // TODO: If we passed in the base kernel offset we could have a better
1470     // alignment than 4, but we don't really need it.
1471     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1472     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1473                                MachineMemOperand::MODereferenceable |
1474                                MachineMemOperand::MOInvariant);
1475 
1476     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1477     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1478 
1479     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1480     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1481     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1482 
1483 
1484     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1485   }
1486 
1487   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1488   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1489                              MachineMemOperand::MODereferenceable |
1490                              MachineMemOperand::MOInvariant);
1491 
1492   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1493   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1494 }
1495 
1496 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1497                                               const SDLoc &SL, SDValue Chain,
1498                                               const ISD::InputArg &Arg) const {
1499   MachineFunction &MF = DAG.getMachineFunction();
1500   MachineFrameInfo &MFI = MF.getFrameInfo();
1501 
1502   if (Arg.Flags.isByVal()) {
1503     unsigned Size = Arg.Flags.getByValSize();
1504     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1505     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1506   }
1507 
1508   unsigned ArgOffset = VA.getLocMemOffset();
1509   unsigned ArgSize = VA.getValVT().getStoreSize();
1510 
1511   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1512 
1513   // Create load nodes to retrieve arguments from the stack.
1514   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1515   SDValue ArgValue;
1516 
1517   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1518   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1519   MVT MemVT = VA.getValVT();
1520 
1521   switch (VA.getLocInfo()) {
1522   default:
1523     break;
1524   case CCValAssign::BCvt:
1525     MemVT = VA.getLocVT();
1526     break;
1527   case CCValAssign::SExt:
1528     ExtType = ISD::SEXTLOAD;
1529     break;
1530   case CCValAssign::ZExt:
1531     ExtType = ISD::ZEXTLOAD;
1532     break;
1533   case CCValAssign::AExt:
1534     ExtType = ISD::EXTLOAD;
1535     break;
1536   }
1537 
1538   ArgValue = DAG.getExtLoad(
1539     ExtType, SL, VA.getLocVT(), Chain, FIN,
1540     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1541     MemVT);
1542   return ArgValue;
1543 }
1544 
1545 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1546   const SIMachineFunctionInfo &MFI,
1547   EVT VT,
1548   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1549   const ArgDescriptor *Reg;
1550   const TargetRegisterClass *RC;
1551 
1552   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1553   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1554 }
1555 
1556 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1557                                    CallingConv::ID CallConv,
1558                                    ArrayRef<ISD::InputArg> Ins,
1559                                    BitVector &Skipped,
1560                                    FunctionType *FType,
1561                                    SIMachineFunctionInfo *Info) {
1562   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1563     const ISD::InputArg *Arg = &Ins[I];
1564 
1565     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1566            "vector type argument should have been split");
1567 
1568     // First check if it's a PS input addr.
1569     if (CallConv == CallingConv::AMDGPU_PS &&
1570         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1571       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1572 
1573       // Inconveniently only the first part of the split is marked as isSplit,
1574       // so skip to the end. We only want to increment PSInputNum once for the
1575       // entire split argument.
1576       if (Arg->Flags.isSplit()) {
1577         while (!Arg->Flags.isSplitEnd()) {
1578           assert((!Arg->VT.isVector() ||
1579                   Arg->VT.getScalarSizeInBits() == 16) &&
1580                  "unexpected vector split in ps argument type");
1581           if (!SkipArg)
1582             Splits.push_back(*Arg);
1583           Arg = &Ins[++I];
1584         }
1585       }
1586 
1587       if (SkipArg) {
1588         // We can safely skip PS inputs.
1589         Skipped.set(Arg->getOrigArgIndex());
1590         ++PSInputNum;
1591         continue;
1592       }
1593 
1594       Info->markPSInputAllocated(PSInputNum);
1595       if (Arg->Used)
1596         Info->markPSInputEnabled(PSInputNum);
1597 
1598       ++PSInputNum;
1599     }
1600 
1601     Splits.push_back(*Arg);
1602   }
1603 }
1604 
1605 // Allocate special inputs passed in VGPRs.
1606 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1607                                                       MachineFunction &MF,
1608                                                       const SIRegisterInfo &TRI,
1609                                                       SIMachineFunctionInfo &Info) const {
1610   const LLT S32 = LLT::scalar(32);
1611   MachineRegisterInfo &MRI = MF.getRegInfo();
1612 
1613   if (Info.hasWorkItemIDX()) {
1614     Register Reg = AMDGPU::VGPR0;
1615     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1616 
1617     CCInfo.AllocateReg(Reg);
1618     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1619   }
1620 
1621   if (Info.hasWorkItemIDY()) {
1622     Register Reg = AMDGPU::VGPR1;
1623     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1624 
1625     CCInfo.AllocateReg(Reg);
1626     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1627   }
1628 
1629   if (Info.hasWorkItemIDZ()) {
1630     Register Reg = AMDGPU::VGPR2;
1631     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1632 
1633     CCInfo.AllocateReg(Reg);
1634     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1635   }
1636 }
1637 
1638 // Try to allocate a VGPR at the end of the argument list, or if no argument
1639 // VGPRs are left allocating a stack slot.
1640 // If \p Mask is is given it indicates bitfield position in the register.
1641 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1642 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1643                                          ArgDescriptor Arg = ArgDescriptor()) {
1644   if (Arg.isSet())
1645     return ArgDescriptor::createArg(Arg, Mask);
1646 
1647   ArrayRef<MCPhysReg> ArgVGPRs
1648     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1649   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1650   if (RegIdx == ArgVGPRs.size()) {
1651     // Spill to stack required.
1652     int64_t Offset = CCInfo.AllocateStack(4, 4);
1653 
1654     return ArgDescriptor::createStack(Offset, Mask);
1655   }
1656 
1657   unsigned Reg = ArgVGPRs[RegIdx];
1658   Reg = CCInfo.AllocateReg(Reg);
1659   assert(Reg != AMDGPU::NoRegister);
1660 
1661   MachineFunction &MF = CCInfo.getMachineFunction();
1662   MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1663   return ArgDescriptor::createRegister(Reg, Mask);
1664 }
1665 
1666 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1667                                              const TargetRegisterClass *RC,
1668                                              unsigned NumArgRegs) {
1669   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1670   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1671   if (RegIdx == ArgSGPRs.size())
1672     report_fatal_error("ran out of SGPRs for arguments");
1673 
1674   unsigned Reg = ArgSGPRs[RegIdx];
1675   Reg = CCInfo.AllocateReg(Reg);
1676   assert(Reg != AMDGPU::NoRegister);
1677 
1678   MachineFunction &MF = CCInfo.getMachineFunction();
1679   MF.addLiveIn(Reg, RC);
1680   return ArgDescriptor::createRegister(Reg);
1681 }
1682 
1683 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1684   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1685 }
1686 
1687 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1688   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1689 }
1690 
1691 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo,
1692                                                  MachineFunction &MF,
1693                                                  const SIRegisterInfo &TRI,
1694                                                  SIMachineFunctionInfo &Info) const {
1695   const unsigned Mask = 0x3ff;
1696   ArgDescriptor Arg;
1697 
1698   if (Info.hasWorkItemIDX()) {
1699     Arg = allocateVGPR32Input(CCInfo, Mask);
1700     Info.setWorkItemIDX(Arg);
1701   }
1702 
1703   if (Info.hasWorkItemIDY()) {
1704     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1705     Info.setWorkItemIDY(Arg);
1706   }
1707 
1708   if (Info.hasWorkItemIDZ())
1709     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1710 }
1711 
1712 void SITargetLowering::allocateSpecialInputSGPRs(
1713   CCState &CCInfo,
1714   MachineFunction &MF,
1715   const SIRegisterInfo &TRI,
1716   SIMachineFunctionInfo &Info) const {
1717   auto &ArgInfo = Info.getArgInfo();
1718 
1719   // TODO: Unify handling with private memory pointers.
1720 
1721   if (Info.hasDispatchPtr())
1722     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1723 
1724   if (Info.hasQueuePtr())
1725     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1726 
1727   if (Info.hasKernargSegmentPtr())
1728     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1729 
1730   if (Info.hasDispatchID())
1731     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1732 
1733   // flat_scratch_init is not applicable for non-kernel functions.
1734 
1735   if (Info.hasWorkGroupIDX())
1736     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1737 
1738   if (Info.hasWorkGroupIDY())
1739     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1740 
1741   if (Info.hasWorkGroupIDZ())
1742     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1743 
1744   if (Info.hasImplicitArgPtr())
1745     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1746 }
1747 
1748 // Allocate special inputs passed in user SGPRs.
1749 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1750                                             MachineFunction &MF,
1751                                             const SIRegisterInfo &TRI,
1752                                             SIMachineFunctionInfo &Info) const {
1753   if (Info.hasImplicitBufferPtr()) {
1754     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1755     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1756     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1757   }
1758 
1759   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1760   if (Info.hasPrivateSegmentBuffer()) {
1761     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1762     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1763     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1764   }
1765 
1766   if (Info.hasDispatchPtr()) {
1767     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1768     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1769     CCInfo.AllocateReg(DispatchPtrReg);
1770   }
1771 
1772   if (Info.hasQueuePtr()) {
1773     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1774     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1775     CCInfo.AllocateReg(QueuePtrReg);
1776   }
1777 
1778   if (Info.hasKernargSegmentPtr()) {
1779     MachineRegisterInfo &MRI = MF.getRegInfo();
1780     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1781     CCInfo.AllocateReg(InputPtrReg);
1782 
1783     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1784     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1785   }
1786 
1787   if (Info.hasDispatchID()) {
1788     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1789     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1790     CCInfo.AllocateReg(DispatchIDReg);
1791   }
1792 
1793   if (Info.hasFlatScratchInit()) {
1794     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1795     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1796     CCInfo.AllocateReg(FlatScratchInitReg);
1797   }
1798 
1799   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1800   // these from the dispatch pointer.
1801 }
1802 
1803 // Allocate special input registers that are initialized per-wave.
1804 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1805                                            MachineFunction &MF,
1806                                            SIMachineFunctionInfo &Info,
1807                                            CallingConv::ID CallConv,
1808                                            bool IsShader) const {
1809   if (Info.hasWorkGroupIDX()) {
1810     unsigned Reg = Info.addWorkGroupIDX();
1811     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1812     CCInfo.AllocateReg(Reg);
1813   }
1814 
1815   if (Info.hasWorkGroupIDY()) {
1816     unsigned Reg = Info.addWorkGroupIDY();
1817     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1818     CCInfo.AllocateReg(Reg);
1819   }
1820 
1821   if (Info.hasWorkGroupIDZ()) {
1822     unsigned Reg = Info.addWorkGroupIDZ();
1823     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1824     CCInfo.AllocateReg(Reg);
1825   }
1826 
1827   if (Info.hasWorkGroupInfo()) {
1828     unsigned Reg = Info.addWorkGroupInfo();
1829     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1830     CCInfo.AllocateReg(Reg);
1831   }
1832 
1833   if (Info.hasPrivateSegmentWaveByteOffset()) {
1834     // Scratch wave offset passed in system SGPR.
1835     unsigned PrivateSegmentWaveByteOffsetReg;
1836 
1837     if (IsShader) {
1838       PrivateSegmentWaveByteOffsetReg =
1839         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1840 
1841       // This is true if the scratch wave byte offset doesn't have a fixed
1842       // location.
1843       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1844         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1845         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1846       }
1847     } else
1848       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1849 
1850     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1851     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1852   }
1853 }
1854 
1855 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1856                                      MachineFunction &MF,
1857                                      const SIRegisterInfo &TRI,
1858                                      SIMachineFunctionInfo &Info) {
1859   // Now that we've figured out where the scratch register inputs are, see if
1860   // should reserve the arguments and use them directly.
1861   MachineFrameInfo &MFI = MF.getFrameInfo();
1862   bool HasStackObjects = MFI.hasStackObjects();
1863   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1864 
1865   // Record that we know we have non-spill stack objects so we don't need to
1866   // check all stack objects later.
1867   if (HasStackObjects)
1868     Info.setHasNonSpillStackObjects(true);
1869 
1870   // Everything live out of a block is spilled with fast regalloc, so it's
1871   // almost certain that spilling will be required.
1872   if (TM.getOptLevel() == CodeGenOpt::None)
1873     HasStackObjects = true;
1874 
1875   // For now assume stack access is needed in any callee functions, so we need
1876   // the scratch registers to pass in.
1877   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1878 
1879   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1880     // If we have stack objects, we unquestionably need the private buffer
1881     // resource. For the Code Object V2 ABI, this will be the first 4 user
1882     // SGPR inputs. We can reserve those and use them directly.
1883 
1884     unsigned PrivateSegmentBufferReg =
1885         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1886     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1887   } else {
1888     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1889     // We tentatively reserve the last registers (skipping the last registers
1890     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1891     // we'll replace these with the ones immediately after those which were
1892     // really allocated. In the prologue copies will be inserted from the
1893     // argument to these reserved registers.
1894 
1895     // Without HSA, relocations are used for the scratch pointer and the
1896     // buffer resource setup is always inserted in the prologue. Scratch wave
1897     // offset is still in an input SGPR.
1898     Info.setScratchRSrcReg(ReservedBufferReg);
1899   }
1900 
1901   // hasFP should be accurate for kernels even before the frame is finalized.
1902   if (ST.getFrameLowering()->hasFP(MF)) {
1903     MachineRegisterInfo &MRI = MF.getRegInfo();
1904 
1905     // Try to use s32 as the SP, but move it if it would interfere with input
1906     // arguments. This won't work with calls though.
1907     //
1908     // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1909     // registers.
1910     if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1911       Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1912     } else {
1913       assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1914 
1915       if (MFI.hasCalls())
1916         report_fatal_error("call in graphics shader with too many input SGPRs");
1917 
1918       for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1919         if (!MRI.isLiveIn(Reg)) {
1920           Info.setStackPtrOffsetReg(Reg);
1921           break;
1922         }
1923       }
1924 
1925       if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1926         report_fatal_error("failed to find register for SP");
1927     }
1928 
1929     if (MFI.hasCalls()) {
1930       Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
1931       Info.setFrameOffsetReg(AMDGPU::SGPR33);
1932     } else {
1933       unsigned ReservedOffsetReg =
1934         TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1935       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1936       Info.setFrameOffsetReg(ReservedOffsetReg);
1937     }
1938   } else if (RequiresStackAccess) {
1939     assert(!MFI.hasCalls());
1940     // We know there are accesses and they will be done relative to SP, so just
1941     // pin it to the input.
1942     //
1943     // FIXME: Should not do this if inline asm is reading/writing these
1944     // registers.
1945     unsigned PreloadedSP = Info.getPreloadedReg(
1946         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1947 
1948     Info.setStackPtrOffsetReg(PreloadedSP);
1949     Info.setScratchWaveOffsetReg(PreloadedSP);
1950     Info.setFrameOffsetReg(PreloadedSP);
1951   } else {
1952     assert(!MFI.hasCalls());
1953 
1954     // There may not be stack access at all. There may still be spills, or
1955     // access of a constant pointer (in which cases an extra copy will be
1956     // emitted in the prolog).
1957     unsigned ReservedOffsetReg
1958       = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1959     Info.setStackPtrOffsetReg(ReservedOffsetReg);
1960     Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1961     Info.setFrameOffsetReg(ReservedOffsetReg);
1962   }
1963 }
1964 
1965 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1966   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1967   return !Info->isEntryFunction();
1968 }
1969 
1970 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1971 
1972 }
1973 
1974 void SITargetLowering::insertCopiesSplitCSR(
1975   MachineBasicBlock *Entry,
1976   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1977   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1978 
1979   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1980   if (!IStart)
1981     return;
1982 
1983   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1984   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1985   MachineBasicBlock::iterator MBBI = Entry->begin();
1986   for (const MCPhysReg *I = IStart; *I; ++I) {
1987     const TargetRegisterClass *RC = nullptr;
1988     if (AMDGPU::SReg_64RegClass.contains(*I))
1989       RC = &AMDGPU::SGPR_64RegClass;
1990     else if (AMDGPU::SReg_32RegClass.contains(*I))
1991       RC = &AMDGPU::SGPR_32RegClass;
1992     else
1993       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1994 
1995     unsigned NewVR = MRI->createVirtualRegister(RC);
1996     // Create copy from CSR to a virtual register.
1997     Entry->addLiveIn(*I);
1998     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1999       .addReg(*I);
2000 
2001     // Insert the copy-back instructions right before the terminator.
2002     for (auto *Exit : Exits)
2003       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2004               TII->get(TargetOpcode::COPY), *I)
2005         .addReg(NewVR);
2006   }
2007 }
2008 
2009 SDValue SITargetLowering::LowerFormalArguments(
2010     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2011     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2012     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2013   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2014 
2015   MachineFunction &MF = DAG.getMachineFunction();
2016   const Function &Fn = MF.getFunction();
2017   FunctionType *FType = MF.getFunction().getFunctionType();
2018   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2019 
2020   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2021     DiagnosticInfoUnsupported NoGraphicsHSA(
2022         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2023     DAG.getContext()->diagnose(NoGraphicsHSA);
2024     return DAG.getEntryNode();
2025   }
2026 
2027   SmallVector<ISD::InputArg, 16> Splits;
2028   SmallVector<CCValAssign, 16> ArgLocs;
2029   BitVector Skipped(Ins.size());
2030   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2031                  *DAG.getContext());
2032 
2033   bool IsShader = AMDGPU::isShader(CallConv);
2034   bool IsKernel = AMDGPU::isKernel(CallConv);
2035   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2036 
2037   if (IsShader) {
2038     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2039 
2040     // At least one interpolation mode must be enabled or else the GPU will
2041     // hang.
2042     //
2043     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2044     // set PSInputAddr, the user wants to enable some bits after the compilation
2045     // based on run-time states. Since we can't know what the final PSInputEna
2046     // will look like, so we shouldn't do anything here and the user should take
2047     // responsibility for the correct programming.
2048     //
2049     // Otherwise, the following restrictions apply:
2050     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2051     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2052     //   enabled too.
2053     if (CallConv == CallingConv::AMDGPU_PS) {
2054       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2055            ((Info->getPSInputAddr() & 0xF) == 0 &&
2056             Info->isPSInputAllocated(11))) {
2057         CCInfo.AllocateReg(AMDGPU::VGPR0);
2058         CCInfo.AllocateReg(AMDGPU::VGPR1);
2059         Info->markPSInputAllocated(0);
2060         Info->markPSInputEnabled(0);
2061       }
2062       if (Subtarget->isAmdPalOS()) {
2063         // For isAmdPalOS, the user does not enable some bits after compilation
2064         // based on run-time states; the register values being generated here are
2065         // the final ones set in hardware. Therefore we need to apply the
2066         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2067         // a bit is set in PSInputAddr but not PSInputEnable is where the
2068         // frontend set up an input arg for a particular interpolation mode, but
2069         // nothing uses that input arg. Really we should have an earlier pass
2070         // that removes such an arg.)
2071         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2072         if ((PsInputBits & 0x7F) == 0 ||
2073             ((PsInputBits & 0xF) == 0 &&
2074              (PsInputBits >> 11 & 1)))
2075           Info->markPSInputEnabled(
2076               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2077       }
2078     }
2079 
2080     assert(!Info->hasDispatchPtr() &&
2081            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2082            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2083            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2084            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2085            !Info->hasWorkItemIDZ());
2086   } else if (IsKernel) {
2087     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2088   } else {
2089     Splits.append(Ins.begin(), Ins.end());
2090   }
2091 
2092   if (IsEntryFunc) {
2093     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2094     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2095   }
2096 
2097   if (IsKernel) {
2098     analyzeFormalArgumentsCompute(CCInfo, Ins);
2099   } else {
2100     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2101     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2102   }
2103 
2104   SmallVector<SDValue, 16> Chains;
2105 
2106   // FIXME: This is the minimum kernel argument alignment. We should improve
2107   // this to the maximum alignment of the arguments.
2108   //
2109   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2110   // kern arg offset.
2111   const unsigned KernelArgBaseAlign = 16;
2112 
2113    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2114     const ISD::InputArg &Arg = Ins[i];
2115     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2116       InVals.push_back(DAG.getUNDEF(Arg.VT));
2117       continue;
2118     }
2119 
2120     CCValAssign &VA = ArgLocs[ArgIdx++];
2121     MVT VT = VA.getLocVT();
2122 
2123     if (IsEntryFunc && VA.isMemLoc()) {
2124       VT = Ins[i].VT;
2125       EVT MemVT = VA.getLocVT();
2126 
2127       const uint64_t Offset = VA.getLocMemOffset();
2128       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2129 
2130       SDValue Arg = lowerKernargMemParameter(
2131         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2132       Chains.push_back(Arg.getValue(1));
2133 
2134       auto *ParamTy =
2135         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2136       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2137           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2138                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2139         // On SI local pointers are just offsets into LDS, so they are always
2140         // less than 16-bits.  On CI and newer they could potentially be
2141         // real pointers, so we can't guarantee their size.
2142         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2143                           DAG.getValueType(MVT::i16));
2144       }
2145 
2146       InVals.push_back(Arg);
2147       continue;
2148     } else if (!IsEntryFunc && VA.isMemLoc()) {
2149       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2150       InVals.push_back(Val);
2151       if (!Arg.Flags.isByVal())
2152         Chains.push_back(Val.getValue(1));
2153       continue;
2154     }
2155 
2156     assert(VA.isRegLoc() && "Parameter must be in a register!");
2157 
2158     unsigned Reg = VA.getLocReg();
2159     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2160     EVT ValVT = VA.getValVT();
2161 
2162     Reg = MF.addLiveIn(Reg, RC);
2163     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2164 
2165     if (Arg.Flags.isSRet()) {
2166       // The return object should be reasonably addressable.
2167 
2168       // FIXME: This helps when the return is a real sret. If it is a
2169       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2170       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2171       unsigned NumBits
2172         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2173       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2174         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2175     }
2176 
2177     // If this is an 8 or 16-bit value, it is really passed promoted
2178     // to 32 bits. Insert an assert[sz]ext to capture this, then
2179     // truncate to the right size.
2180     switch (VA.getLocInfo()) {
2181     case CCValAssign::Full:
2182       break;
2183     case CCValAssign::BCvt:
2184       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2185       break;
2186     case CCValAssign::SExt:
2187       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2188                         DAG.getValueType(ValVT));
2189       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2190       break;
2191     case CCValAssign::ZExt:
2192       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2193                         DAG.getValueType(ValVT));
2194       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2195       break;
2196     case CCValAssign::AExt:
2197       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2198       break;
2199     default:
2200       llvm_unreachable("Unknown loc info!");
2201     }
2202 
2203     InVals.push_back(Val);
2204   }
2205 
2206   if (!IsEntryFunc) {
2207     // Special inputs come after user arguments.
2208     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2209   }
2210 
2211   // Start adding system SGPRs.
2212   if (IsEntryFunc) {
2213     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2214   } else {
2215     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2216     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2217     CCInfo.AllocateReg(Info->getFrameOffsetReg());
2218     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2219   }
2220 
2221   auto &ArgUsageInfo =
2222     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2223   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2224 
2225   unsigned StackArgSize = CCInfo.getNextStackOffset();
2226   Info->setBytesInStackArgArea(StackArgSize);
2227 
2228   return Chains.empty() ? Chain :
2229     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2230 }
2231 
2232 // TODO: If return values can't fit in registers, we should return as many as
2233 // possible in registers before passing on stack.
2234 bool SITargetLowering::CanLowerReturn(
2235   CallingConv::ID CallConv,
2236   MachineFunction &MF, bool IsVarArg,
2237   const SmallVectorImpl<ISD::OutputArg> &Outs,
2238   LLVMContext &Context) const {
2239   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2240   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2241   // for shaders. Vector types should be explicitly handled by CC.
2242   if (AMDGPU::isEntryFunctionCC(CallConv))
2243     return true;
2244 
2245   SmallVector<CCValAssign, 16> RVLocs;
2246   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2247   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2248 }
2249 
2250 SDValue
2251 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2252                               bool isVarArg,
2253                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2254                               const SmallVectorImpl<SDValue> &OutVals,
2255                               const SDLoc &DL, SelectionDAG &DAG) const {
2256   MachineFunction &MF = DAG.getMachineFunction();
2257   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2258 
2259   if (AMDGPU::isKernel(CallConv)) {
2260     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2261                                              OutVals, DL, DAG);
2262   }
2263 
2264   bool IsShader = AMDGPU::isShader(CallConv);
2265 
2266   Info->setIfReturnsVoid(Outs.empty());
2267   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2268 
2269   // CCValAssign - represent the assignment of the return value to a location.
2270   SmallVector<CCValAssign, 48> RVLocs;
2271   SmallVector<ISD::OutputArg, 48> Splits;
2272 
2273   // CCState - Info about the registers and stack slots.
2274   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2275                  *DAG.getContext());
2276 
2277   // Analyze outgoing return values.
2278   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2279 
2280   SDValue Flag;
2281   SmallVector<SDValue, 48> RetOps;
2282   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2283 
2284   // Add return address for callable functions.
2285   if (!Info->isEntryFunction()) {
2286     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2287     SDValue ReturnAddrReg = CreateLiveInRegister(
2288       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2289 
2290     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2291         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2292         MVT::i64);
2293     Chain =
2294         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2295     Flag = Chain.getValue(1);
2296     RetOps.push_back(ReturnAddrVirtualReg);
2297   }
2298 
2299   // Copy the result values into the output registers.
2300   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2301        ++I, ++RealRVLocIdx) {
2302     CCValAssign &VA = RVLocs[I];
2303     assert(VA.isRegLoc() && "Can only return in registers!");
2304     // TODO: Partially return in registers if return values don't fit.
2305     SDValue Arg = OutVals[RealRVLocIdx];
2306 
2307     // Copied from other backends.
2308     switch (VA.getLocInfo()) {
2309     case CCValAssign::Full:
2310       break;
2311     case CCValAssign::BCvt:
2312       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2313       break;
2314     case CCValAssign::SExt:
2315       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2316       break;
2317     case CCValAssign::ZExt:
2318       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2319       break;
2320     case CCValAssign::AExt:
2321       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2322       break;
2323     default:
2324       llvm_unreachable("Unknown loc info!");
2325     }
2326 
2327     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2328     Flag = Chain.getValue(1);
2329     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2330   }
2331 
2332   // FIXME: Does sret work properly?
2333   if (!Info->isEntryFunction()) {
2334     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2335     const MCPhysReg *I =
2336       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2337     if (I) {
2338       for (; *I; ++I) {
2339         if (AMDGPU::SReg_64RegClass.contains(*I))
2340           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2341         else if (AMDGPU::SReg_32RegClass.contains(*I))
2342           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2343         else
2344           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2345       }
2346     }
2347   }
2348 
2349   // Update chain and glue.
2350   RetOps[0] = Chain;
2351   if (Flag.getNode())
2352     RetOps.push_back(Flag);
2353 
2354   unsigned Opc = AMDGPUISD::ENDPGM;
2355   if (!IsWaveEnd)
2356     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2357   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2358 }
2359 
2360 SDValue SITargetLowering::LowerCallResult(
2361     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2362     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2363     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2364     SDValue ThisVal) const {
2365   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2366 
2367   // Assign locations to each value returned by this call.
2368   SmallVector<CCValAssign, 16> RVLocs;
2369   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2370                  *DAG.getContext());
2371   CCInfo.AnalyzeCallResult(Ins, RetCC);
2372 
2373   // Copy all of the result registers out of their specified physreg.
2374   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2375     CCValAssign VA = RVLocs[i];
2376     SDValue Val;
2377 
2378     if (VA.isRegLoc()) {
2379       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2380       Chain = Val.getValue(1);
2381       InFlag = Val.getValue(2);
2382     } else if (VA.isMemLoc()) {
2383       report_fatal_error("TODO: return values in memory");
2384     } else
2385       llvm_unreachable("unknown argument location type");
2386 
2387     switch (VA.getLocInfo()) {
2388     case CCValAssign::Full:
2389       break;
2390     case CCValAssign::BCvt:
2391       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2392       break;
2393     case CCValAssign::ZExt:
2394       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2395                         DAG.getValueType(VA.getValVT()));
2396       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2397       break;
2398     case CCValAssign::SExt:
2399       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2400                         DAG.getValueType(VA.getValVT()));
2401       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2402       break;
2403     case CCValAssign::AExt:
2404       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2405       break;
2406     default:
2407       llvm_unreachable("Unknown loc info!");
2408     }
2409 
2410     InVals.push_back(Val);
2411   }
2412 
2413   return Chain;
2414 }
2415 
2416 // Add code to pass special inputs required depending on used features separate
2417 // from the explicit user arguments present in the IR.
2418 void SITargetLowering::passSpecialInputs(
2419     CallLoweringInfo &CLI,
2420     CCState &CCInfo,
2421     const SIMachineFunctionInfo &Info,
2422     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2423     SmallVectorImpl<SDValue> &MemOpChains,
2424     SDValue Chain) const {
2425   // If we don't have a call site, this was a call inserted by
2426   // legalization. These can never use special inputs.
2427   if (!CLI.CS)
2428     return;
2429 
2430   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2431   assert(CalleeFunc);
2432 
2433   SelectionDAG &DAG = CLI.DAG;
2434   const SDLoc &DL = CLI.DL;
2435 
2436   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2437 
2438   auto &ArgUsageInfo =
2439     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2440   const AMDGPUFunctionArgInfo &CalleeArgInfo
2441     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2442 
2443   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2444 
2445   // TODO: Unify with private memory register handling. This is complicated by
2446   // the fact that at least in kernels, the input argument is not necessarily
2447   // in the same location as the input.
2448   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2449     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2450     AMDGPUFunctionArgInfo::QUEUE_PTR,
2451     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2452     AMDGPUFunctionArgInfo::DISPATCH_ID,
2453     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2454     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2455     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2456     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2457   };
2458 
2459   for (auto InputID : InputRegs) {
2460     const ArgDescriptor *OutgoingArg;
2461     const TargetRegisterClass *ArgRC;
2462 
2463     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2464     if (!OutgoingArg)
2465       continue;
2466 
2467     const ArgDescriptor *IncomingArg;
2468     const TargetRegisterClass *IncomingArgRC;
2469     std::tie(IncomingArg, IncomingArgRC)
2470       = CallerArgInfo.getPreloadedValue(InputID);
2471     assert(IncomingArgRC == ArgRC);
2472 
2473     // All special arguments are ints for now.
2474     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2475     SDValue InputReg;
2476 
2477     if (IncomingArg) {
2478       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2479     } else {
2480       // The implicit arg ptr is special because it doesn't have a corresponding
2481       // input for kernels, and is computed from the kernarg segment pointer.
2482       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2483       InputReg = getImplicitArgPtr(DAG, DL);
2484     }
2485 
2486     if (OutgoingArg->isRegister()) {
2487       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2488     } else {
2489       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2490       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2491                                               SpecialArgOffset);
2492       MemOpChains.push_back(ArgStore);
2493     }
2494   }
2495 
2496   // Pack workitem IDs into a single register or pass it as is if already
2497   // packed.
2498   const ArgDescriptor *OutgoingArg;
2499   const TargetRegisterClass *ArgRC;
2500 
2501   std::tie(OutgoingArg, ArgRC) =
2502     CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2503   if (!OutgoingArg)
2504     std::tie(OutgoingArg, ArgRC) =
2505       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2506   if (!OutgoingArg)
2507     std::tie(OutgoingArg, ArgRC) =
2508       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2509   if (!OutgoingArg)
2510     return;
2511 
2512   const ArgDescriptor *IncomingArgX
2513     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2514   const ArgDescriptor *IncomingArgY
2515     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2516   const ArgDescriptor *IncomingArgZ
2517     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2518 
2519   SDValue InputReg;
2520   SDLoc SL;
2521 
2522   // If incoming ids are not packed we need to pack them.
2523   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX)
2524     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2525 
2526   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) {
2527     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2528     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2529                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2530     InputReg = InputReg.getNode() ?
2531                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2532   }
2533 
2534   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) {
2535     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2536     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2537                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2538     InputReg = InputReg.getNode() ?
2539                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2540   }
2541 
2542   if (!InputReg.getNode()) {
2543     // Workitem ids are already packed, any of present incoming arguments
2544     // will carry all required fields.
2545     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2546       IncomingArgX ? *IncomingArgX :
2547       IncomingArgY ? *IncomingArgY :
2548                      *IncomingArgZ, ~0u);
2549     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2550   }
2551 
2552   if (OutgoingArg->isRegister()) {
2553     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2554   } else {
2555     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2556     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2557                                             SpecialArgOffset);
2558     MemOpChains.push_back(ArgStore);
2559   }
2560 }
2561 
2562 static bool canGuaranteeTCO(CallingConv::ID CC) {
2563   return CC == CallingConv::Fast;
2564 }
2565 
2566 /// Return true if we might ever do TCO for calls with this calling convention.
2567 static bool mayTailCallThisCC(CallingConv::ID CC) {
2568   switch (CC) {
2569   case CallingConv::C:
2570     return true;
2571   default:
2572     return canGuaranteeTCO(CC);
2573   }
2574 }
2575 
2576 bool SITargetLowering::isEligibleForTailCallOptimization(
2577     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2578     const SmallVectorImpl<ISD::OutputArg> &Outs,
2579     const SmallVectorImpl<SDValue> &OutVals,
2580     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2581   if (!mayTailCallThisCC(CalleeCC))
2582     return false;
2583 
2584   MachineFunction &MF = DAG.getMachineFunction();
2585   const Function &CallerF = MF.getFunction();
2586   CallingConv::ID CallerCC = CallerF.getCallingConv();
2587   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2588   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2589 
2590   // Kernels aren't callable, and don't have a live in return address so it
2591   // doesn't make sense to do a tail call with entry functions.
2592   if (!CallerPreserved)
2593     return false;
2594 
2595   bool CCMatch = CallerCC == CalleeCC;
2596 
2597   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2598     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2599       return true;
2600     return false;
2601   }
2602 
2603   // TODO: Can we handle var args?
2604   if (IsVarArg)
2605     return false;
2606 
2607   for (const Argument &Arg : CallerF.args()) {
2608     if (Arg.hasByValAttr())
2609       return false;
2610   }
2611 
2612   LLVMContext &Ctx = *DAG.getContext();
2613 
2614   // Check that the call results are passed in the same way.
2615   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2616                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2617                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2618     return false;
2619 
2620   // The callee has to preserve all registers the caller needs to preserve.
2621   if (!CCMatch) {
2622     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2623     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2624       return false;
2625   }
2626 
2627   // Nothing more to check if the callee is taking no arguments.
2628   if (Outs.empty())
2629     return true;
2630 
2631   SmallVector<CCValAssign, 16> ArgLocs;
2632   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2633 
2634   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2635 
2636   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2637   // If the stack arguments for this call do not fit into our own save area then
2638   // the call cannot be made tail.
2639   // TODO: Is this really necessary?
2640   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2641     return false;
2642 
2643   const MachineRegisterInfo &MRI = MF.getRegInfo();
2644   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2645 }
2646 
2647 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2648   if (!CI->isTailCall())
2649     return false;
2650 
2651   const Function *ParentFn = CI->getParent()->getParent();
2652   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2653     return false;
2654 
2655   auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2656   return (Attr.getValueAsString() != "true");
2657 }
2658 
2659 // The wave scratch offset register is used as the global base pointer.
2660 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2661                                     SmallVectorImpl<SDValue> &InVals) const {
2662   SelectionDAG &DAG = CLI.DAG;
2663   const SDLoc &DL = CLI.DL;
2664   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2665   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2666   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2667   SDValue Chain = CLI.Chain;
2668   SDValue Callee = CLI.Callee;
2669   bool &IsTailCall = CLI.IsTailCall;
2670   CallingConv::ID CallConv = CLI.CallConv;
2671   bool IsVarArg = CLI.IsVarArg;
2672   bool IsSibCall = false;
2673   bool IsThisReturn = false;
2674   MachineFunction &MF = DAG.getMachineFunction();
2675 
2676   if (IsVarArg) {
2677     return lowerUnhandledCall(CLI, InVals,
2678                               "unsupported call to variadic function ");
2679   }
2680 
2681   if (!CLI.CS.getInstruction())
2682     report_fatal_error("unsupported libcall legalization");
2683 
2684   if (!CLI.CS.getCalledFunction()) {
2685     return lowerUnhandledCall(CLI, InVals,
2686                               "unsupported indirect call to function ");
2687   }
2688 
2689   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2690     return lowerUnhandledCall(CLI, InVals,
2691                               "unsupported required tail call to function ");
2692   }
2693 
2694   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2695     // Note the issue is with the CC of the calling function, not of the call
2696     // itself.
2697     return lowerUnhandledCall(CLI, InVals,
2698                           "unsupported call from graphics shader of function ");
2699   }
2700 
2701   if (IsTailCall) {
2702     IsTailCall = isEligibleForTailCallOptimization(
2703       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2704     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2705       report_fatal_error("failed to perform tail call elimination on a call "
2706                          "site marked musttail");
2707     }
2708 
2709     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2710 
2711     // A sibling call is one where we're under the usual C ABI and not planning
2712     // to change that but can still do a tail call:
2713     if (!TailCallOpt && IsTailCall)
2714       IsSibCall = true;
2715 
2716     if (IsTailCall)
2717       ++NumTailCalls;
2718   }
2719 
2720   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2721 
2722   // Analyze operands of the call, assigning locations to each operand.
2723   SmallVector<CCValAssign, 16> ArgLocs;
2724   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2725   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2726 
2727   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2728 
2729   // Get a count of how many bytes are to be pushed on the stack.
2730   unsigned NumBytes = CCInfo.getNextStackOffset();
2731 
2732   if (IsSibCall) {
2733     // Since we're not changing the ABI to make this a tail call, the memory
2734     // operands are already available in the caller's incoming argument space.
2735     NumBytes = 0;
2736   }
2737 
2738   // FPDiff is the byte offset of the call's argument area from the callee's.
2739   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2740   // by this amount for a tail call. In a sibling call it must be 0 because the
2741   // caller will deallocate the entire stack and the callee still expects its
2742   // arguments to begin at SP+0. Completely unused for non-tail calls.
2743   int32_t FPDiff = 0;
2744   MachineFrameInfo &MFI = MF.getFrameInfo();
2745   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2746 
2747   // Adjust the stack pointer for the new arguments...
2748   // These operations are automatically eliminated by the prolog/epilog pass
2749   if (!IsSibCall) {
2750     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2751 
2752     SmallVector<SDValue, 4> CopyFromChains;
2753 
2754     // In the HSA case, this should be an identity copy.
2755     SDValue ScratchRSrcReg
2756       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2757     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2758     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2759     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2760   }
2761 
2762   SmallVector<SDValue, 8> MemOpChains;
2763   MVT PtrVT = MVT::i32;
2764 
2765   // Walk the register/memloc assignments, inserting copies/loads.
2766   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2767        ++i, ++realArgIdx) {
2768     CCValAssign &VA = ArgLocs[i];
2769     SDValue Arg = OutVals[realArgIdx];
2770 
2771     // Promote the value if needed.
2772     switch (VA.getLocInfo()) {
2773     case CCValAssign::Full:
2774       break;
2775     case CCValAssign::BCvt:
2776       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2777       break;
2778     case CCValAssign::ZExt:
2779       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2780       break;
2781     case CCValAssign::SExt:
2782       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2783       break;
2784     case CCValAssign::AExt:
2785       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2786       break;
2787     case CCValAssign::FPExt:
2788       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2789       break;
2790     default:
2791       llvm_unreachable("Unknown loc info!");
2792     }
2793 
2794     if (VA.isRegLoc()) {
2795       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2796     } else {
2797       assert(VA.isMemLoc());
2798 
2799       SDValue DstAddr;
2800       MachinePointerInfo DstInfo;
2801 
2802       unsigned LocMemOffset = VA.getLocMemOffset();
2803       int32_t Offset = LocMemOffset;
2804 
2805       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2806       unsigned Align = 0;
2807 
2808       if (IsTailCall) {
2809         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2810         unsigned OpSize = Flags.isByVal() ?
2811           Flags.getByValSize() : VA.getValVT().getStoreSize();
2812 
2813         // FIXME: We can have better than the minimum byval required alignment.
2814         Align = Flags.isByVal() ? Flags.getByValAlign() :
2815           MinAlign(Subtarget->getStackAlignment(), Offset);
2816 
2817         Offset = Offset + FPDiff;
2818         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2819 
2820         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2821         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2822 
2823         // Make sure any stack arguments overlapping with where we're storing
2824         // are loaded before this eventual operation. Otherwise they'll be
2825         // clobbered.
2826 
2827         // FIXME: Why is this really necessary? This seems to just result in a
2828         // lot of code to copy the stack and write them back to the same
2829         // locations, which are supposed to be immutable?
2830         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2831       } else {
2832         DstAddr = PtrOff;
2833         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2834         Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset);
2835       }
2836 
2837       if (Outs[i].Flags.isByVal()) {
2838         SDValue SizeNode =
2839             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2840         SDValue Cpy = DAG.getMemcpy(
2841             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2842             /*isVol = */ false, /*AlwaysInline = */ true,
2843             /*isTailCall = */ false, DstInfo,
2844             MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2845                 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
2846 
2847         MemOpChains.push_back(Cpy);
2848       } else {
2849         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align);
2850         MemOpChains.push_back(Store);
2851       }
2852     }
2853   }
2854 
2855   // Copy special input registers after user input arguments.
2856   passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2857 
2858   if (!MemOpChains.empty())
2859     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2860 
2861   // Build a sequence of copy-to-reg nodes chained together with token chain
2862   // and flag operands which copy the outgoing args into the appropriate regs.
2863   SDValue InFlag;
2864   for (auto &RegToPass : RegsToPass) {
2865     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2866                              RegToPass.second, InFlag);
2867     InFlag = Chain.getValue(1);
2868   }
2869 
2870 
2871   SDValue PhysReturnAddrReg;
2872   if (IsTailCall) {
2873     // Since the return is being combined with the call, we need to pass on the
2874     // return address.
2875 
2876     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2877     SDValue ReturnAddrReg = CreateLiveInRegister(
2878       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2879 
2880     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2881                                         MVT::i64);
2882     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2883     InFlag = Chain.getValue(1);
2884   }
2885 
2886   // We don't usually want to end the call-sequence here because we would tidy
2887   // the frame up *after* the call, however in the ABI-changing tail-call case
2888   // we've carefully laid out the parameters so that when sp is reset they'll be
2889   // in the correct location.
2890   if (IsTailCall && !IsSibCall) {
2891     Chain = DAG.getCALLSEQ_END(Chain,
2892                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2893                                DAG.getTargetConstant(0, DL, MVT::i32),
2894                                InFlag, DL);
2895     InFlag = Chain.getValue(1);
2896   }
2897 
2898   std::vector<SDValue> Ops;
2899   Ops.push_back(Chain);
2900   Ops.push_back(Callee);
2901   // Add a redundant copy of the callee global which will not be legalized, as
2902   // we need direct access to the callee later.
2903   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2904   const GlobalValue *GV = GSD->getGlobal();
2905   Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2906 
2907   if (IsTailCall) {
2908     // Each tail call may have to adjust the stack by a different amount, so
2909     // this information must travel along with the operation for eventual
2910     // consumption by emitEpilogue.
2911     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2912 
2913     Ops.push_back(PhysReturnAddrReg);
2914   }
2915 
2916   // Add argument registers to the end of the list so that they are known live
2917   // into the call.
2918   for (auto &RegToPass : RegsToPass) {
2919     Ops.push_back(DAG.getRegister(RegToPass.first,
2920                                   RegToPass.second.getValueType()));
2921   }
2922 
2923   // Add a register mask operand representing the call-preserved registers.
2924 
2925   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2926   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2927   assert(Mask && "Missing call preserved mask for calling convention");
2928   Ops.push_back(DAG.getRegisterMask(Mask));
2929 
2930   if (InFlag.getNode())
2931     Ops.push_back(InFlag);
2932 
2933   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2934 
2935   // If we're doing a tall call, use a TC_RETURN here rather than an
2936   // actual call instruction.
2937   if (IsTailCall) {
2938     MFI.setHasTailCall();
2939     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2940   }
2941 
2942   // Returns a chain and a flag for retval copy to use.
2943   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2944   Chain = Call.getValue(0);
2945   InFlag = Call.getValue(1);
2946 
2947   uint64_t CalleePopBytes = NumBytes;
2948   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2949                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2950                              InFlag, DL);
2951   if (!Ins.empty())
2952     InFlag = Chain.getValue(1);
2953 
2954   // Handle result values, copying them out of physregs into vregs that we
2955   // return.
2956   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2957                          InVals, IsThisReturn,
2958                          IsThisReturn ? OutVals[0] : SDValue());
2959 }
2960 
2961 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2962                                              SelectionDAG &DAG) const {
2963   unsigned Reg = StringSwitch<unsigned>(RegName)
2964     .Case("m0", AMDGPU::M0)
2965     .Case("exec", AMDGPU::EXEC)
2966     .Case("exec_lo", AMDGPU::EXEC_LO)
2967     .Case("exec_hi", AMDGPU::EXEC_HI)
2968     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2969     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2970     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2971     .Default(AMDGPU::NoRegister);
2972 
2973   if (Reg == AMDGPU::NoRegister) {
2974     report_fatal_error(Twine("invalid register name \""
2975                              + StringRef(RegName)  + "\"."));
2976 
2977   }
2978 
2979   if (!Subtarget->hasFlatScrRegister() &&
2980        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2981     report_fatal_error(Twine("invalid register \""
2982                              + StringRef(RegName)  + "\" for subtarget."));
2983   }
2984 
2985   switch (Reg) {
2986   case AMDGPU::M0:
2987   case AMDGPU::EXEC_LO:
2988   case AMDGPU::EXEC_HI:
2989   case AMDGPU::FLAT_SCR_LO:
2990   case AMDGPU::FLAT_SCR_HI:
2991     if (VT.getSizeInBits() == 32)
2992       return Reg;
2993     break;
2994   case AMDGPU::EXEC:
2995   case AMDGPU::FLAT_SCR:
2996     if (VT.getSizeInBits() == 64)
2997       return Reg;
2998     break;
2999   default:
3000     llvm_unreachable("missing register type checking");
3001   }
3002 
3003   report_fatal_error(Twine("invalid type for register \""
3004                            + StringRef(RegName) + "\"."));
3005 }
3006 
3007 // If kill is not the last instruction, split the block so kill is always a
3008 // proper terminator.
3009 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3010                                                     MachineBasicBlock *BB) const {
3011   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3012 
3013   MachineBasicBlock::iterator SplitPoint(&MI);
3014   ++SplitPoint;
3015 
3016   if (SplitPoint == BB->end()) {
3017     // Don't bother with a new block.
3018     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3019     return BB;
3020   }
3021 
3022   MachineFunction *MF = BB->getParent();
3023   MachineBasicBlock *SplitBB
3024     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3025 
3026   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3027   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3028 
3029   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3030   BB->addSuccessor(SplitBB);
3031 
3032   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3033   return SplitBB;
3034 }
3035 
3036 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3037 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3038 // be the first instruction in the remainder block.
3039 //
3040 /// \returns { LoopBody, Remainder }
3041 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3042 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3043   MachineFunction *MF = MBB.getParent();
3044   MachineBasicBlock::iterator I(&MI);
3045 
3046   // To insert the loop we need to split the block. Move everything after this
3047   // point to a new block, and insert a new empty block between the two.
3048   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3049   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3050   MachineFunction::iterator MBBI(MBB);
3051   ++MBBI;
3052 
3053   MF->insert(MBBI, LoopBB);
3054   MF->insert(MBBI, RemainderBB);
3055 
3056   LoopBB->addSuccessor(LoopBB);
3057   LoopBB->addSuccessor(RemainderBB);
3058 
3059   // Move the rest of the block into a new block.
3060   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3061 
3062   if (InstInLoop) {
3063     auto Next = std::next(I);
3064 
3065     // Move instruction to loop body.
3066     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3067 
3068     // Move the rest of the block.
3069     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3070   } else {
3071     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3072   }
3073 
3074   MBB.addSuccessor(LoopBB);
3075 
3076   return std::make_pair(LoopBB, RemainderBB);
3077 }
3078 
3079 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3080 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3081   MachineBasicBlock *MBB = MI.getParent();
3082   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3083   auto I = MI.getIterator();
3084   auto E = std::next(I);
3085 
3086   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3087     .addImm(0);
3088 
3089   MIBundleBuilder Bundler(*MBB, I, E);
3090   finalizeBundle(*MBB, Bundler.begin());
3091 }
3092 
3093 MachineBasicBlock *
3094 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3095                                          MachineBasicBlock *BB) const {
3096   const DebugLoc &DL = MI.getDebugLoc();
3097 
3098   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3099 
3100   MachineBasicBlock *LoopBB;
3101   MachineBasicBlock *RemainderBB;
3102   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3103 
3104   // Apparently kill flags are only valid if the def is in the same block?
3105   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3106     Src->setIsKill(false);
3107 
3108   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3109 
3110   MachineBasicBlock::iterator I = LoopBB->end();
3111 
3112   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3113     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3114 
3115   // Clear TRAP_STS.MEM_VIOL
3116   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3117     .addImm(0)
3118     .addImm(EncodedReg);
3119 
3120   bundleInstWithWaitcnt(MI);
3121 
3122   unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3123 
3124   // Load and check TRAP_STS.MEM_VIOL
3125   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3126     .addImm(EncodedReg);
3127 
3128   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3129   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3130     .addReg(Reg, RegState::Kill)
3131     .addImm(0);
3132   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3133     .addMBB(LoopBB);
3134 
3135   return RemainderBB;
3136 }
3137 
3138 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3139 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3140 // will only do one iteration. In the worst case, this will loop 64 times.
3141 //
3142 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3143 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3144   const SIInstrInfo *TII,
3145   MachineRegisterInfo &MRI,
3146   MachineBasicBlock &OrigBB,
3147   MachineBasicBlock &LoopBB,
3148   const DebugLoc &DL,
3149   const MachineOperand &IdxReg,
3150   unsigned InitReg,
3151   unsigned ResultReg,
3152   unsigned PhiReg,
3153   unsigned InitSaveExecReg,
3154   int Offset,
3155   bool UseGPRIdxMode,
3156   bool IsIndirectSrc) {
3157   MachineFunction *MF = OrigBB.getParent();
3158   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3159   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3160   MachineBasicBlock::iterator I = LoopBB.begin();
3161 
3162   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3163   unsigned PhiExec = MRI.createVirtualRegister(BoolRC);
3164   unsigned NewExec = MRI.createVirtualRegister(BoolRC);
3165   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3166   unsigned CondReg = MRI.createVirtualRegister(BoolRC);
3167 
3168   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3169     .addReg(InitReg)
3170     .addMBB(&OrigBB)
3171     .addReg(ResultReg)
3172     .addMBB(&LoopBB);
3173 
3174   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3175     .addReg(InitSaveExecReg)
3176     .addMBB(&OrigBB)
3177     .addReg(NewExec)
3178     .addMBB(&LoopBB);
3179 
3180   // Read the next variant <- also loop target.
3181   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3182     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3183 
3184   // Compare the just read M0 value to all possible Idx values.
3185   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3186     .addReg(CurrentIdxReg)
3187     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3188 
3189   // Update EXEC, save the original EXEC value to VCC.
3190   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3191                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3192           NewExec)
3193     .addReg(CondReg, RegState::Kill);
3194 
3195   MRI.setSimpleHint(NewExec, CondReg);
3196 
3197   if (UseGPRIdxMode) {
3198     unsigned IdxReg;
3199     if (Offset == 0) {
3200       IdxReg = CurrentIdxReg;
3201     } else {
3202       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3203       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3204         .addReg(CurrentIdxReg, RegState::Kill)
3205         .addImm(Offset);
3206     }
3207     unsigned IdxMode = IsIndirectSrc ?
3208       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3209     MachineInstr *SetOn =
3210       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3211       .addReg(IdxReg, RegState::Kill)
3212       .addImm(IdxMode);
3213     SetOn->getOperand(3).setIsUndef();
3214   } else {
3215     // Move index from VCC into M0
3216     if (Offset == 0) {
3217       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3218         .addReg(CurrentIdxReg, RegState::Kill);
3219     } else {
3220       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3221         .addReg(CurrentIdxReg, RegState::Kill)
3222         .addImm(Offset);
3223     }
3224   }
3225 
3226   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3227   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3228   MachineInstr *InsertPt =
3229     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3230                                                   : AMDGPU::S_XOR_B64_term), Exec)
3231       .addReg(Exec)
3232       .addReg(NewExec);
3233 
3234   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3235   // s_cbranch_scc0?
3236 
3237   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3238   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3239     .addMBB(&LoopBB);
3240 
3241   return InsertPt->getIterator();
3242 }
3243 
3244 // This has slightly sub-optimal regalloc when the source vector is killed by
3245 // the read. The register allocator does not understand that the kill is
3246 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3247 // subregister from it, using 1 more VGPR than necessary. This was saved when
3248 // this was expanded after register allocation.
3249 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3250                                                   MachineBasicBlock &MBB,
3251                                                   MachineInstr &MI,
3252                                                   unsigned InitResultReg,
3253                                                   unsigned PhiReg,
3254                                                   int Offset,
3255                                                   bool UseGPRIdxMode,
3256                                                   bool IsIndirectSrc) {
3257   MachineFunction *MF = MBB.getParent();
3258   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3259   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3260   MachineRegisterInfo &MRI = MF->getRegInfo();
3261   const DebugLoc &DL = MI.getDebugLoc();
3262   MachineBasicBlock::iterator I(&MI);
3263 
3264   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3265   unsigned DstReg = MI.getOperand(0).getReg();
3266   unsigned SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3267   unsigned TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3268   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3269   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3270 
3271   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3272 
3273   // Save the EXEC mask
3274   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3275     .addReg(Exec);
3276 
3277   MachineBasicBlock *LoopBB;
3278   MachineBasicBlock *RemainderBB;
3279   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3280 
3281   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3282 
3283   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3284                                       InitResultReg, DstReg, PhiReg, TmpExec,
3285                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3286 
3287   MachineBasicBlock::iterator First = RemainderBB->begin();
3288   BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
3289     .addReg(SaveExec);
3290 
3291   return InsPt;
3292 }
3293 
3294 // Returns subreg index, offset
3295 static std::pair<unsigned, int>
3296 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3297                             const TargetRegisterClass *SuperRC,
3298                             unsigned VecReg,
3299                             int Offset) {
3300   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3301 
3302   // Skip out of bounds offsets, or else we would end up using an undefined
3303   // register.
3304   if (Offset >= NumElts || Offset < 0)
3305     return std::make_pair(AMDGPU::sub0, Offset);
3306 
3307   return std::make_pair(AMDGPU::sub0 + Offset, 0);
3308 }
3309 
3310 // Return true if the index is an SGPR and was set.
3311 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3312                                  MachineRegisterInfo &MRI,
3313                                  MachineInstr &MI,
3314                                  int Offset,
3315                                  bool UseGPRIdxMode,
3316                                  bool IsIndirectSrc) {
3317   MachineBasicBlock *MBB = MI.getParent();
3318   const DebugLoc &DL = MI.getDebugLoc();
3319   MachineBasicBlock::iterator I(&MI);
3320 
3321   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3322   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3323 
3324   assert(Idx->getReg() != AMDGPU::NoRegister);
3325 
3326   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3327     return false;
3328 
3329   if (UseGPRIdxMode) {
3330     unsigned IdxMode = IsIndirectSrc ?
3331       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3332     if (Offset == 0) {
3333       MachineInstr *SetOn =
3334           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3335               .add(*Idx)
3336               .addImm(IdxMode);
3337 
3338       SetOn->getOperand(3).setIsUndef();
3339     } else {
3340       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3341       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3342           .add(*Idx)
3343           .addImm(Offset);
3344       MachineInstr *SetOn =
3345         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3346         .addReg(Tmp, RegState::Kill)
3347         .addImm(IdxMode);
3348 
3349       SetOn->getOperand(3).setIsUndef();
3350     }
3351 
3352     return true;
3353   }
3354 
3355   if (Offset == 0) {
3356     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3357       .add(*Idx);
3358   } else {
3359     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3360       .add(*Idx)
3361       .addImm(Offset);
3362   }
3363 
3364   return true;
3365 }
3366 
3367 // Control flow needs to be inserted if indexing with a VGPR.
3368 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3369                                           MachineBasicBlock &MBB,
3370                                           const GCNSubtarget &ST) {
3371   const SIInstrInfo *TII = ST.getInstrInfo();
3372   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3373   MachineFunction *MF = MBB.getParent();
3374   MachineRegisterInfo &MRI = MF->getRegInfo();
3375 
3376   unsigned Dst = MI.getOperand(0).getReg();
3377   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3378   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3379 
3380   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3381 
3382   unsigned SubReg;
3383   std::tie(SubReg, Offset)
3384     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3385 
3386   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3387 
3388   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3389     MachineBasicBlock::iterator I(&MI);
3390     const DebugLoc &DL = MI.getDebugLoc();
3391 
3392     if (UseGPRIdxMode) {
3393       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3394       // to avoid interfering with other uses, so probably requires a new
3395       // optimization pass.
3396       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3397         .addReg(SrcReg, RegState::Undef, SubReg)
3398         .addReg(SrcReg, RegState::Implicit)
3399         .addReg(AMDGPU::M0, RegState::Implicit);
3400       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3401     } else {
3402       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3403         .addReg(SrcReg, RegState::Undef, SubReg)
3404         .addReg(SrcReg, RegState::Implicit);
3405     }
3406 
3407     MI.eraseFromParent();
3408 
3409     return &MBB;
3410   }
3411 
3412   const DebugLoc &DL = MI.getDebugLoc();
3413   MachineBasicBlock::iterator I(&MI);
3414 
3415   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3416   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3417 
3418   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3419 
3420   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3421                               Offset, UseGPRIdxMode, true);
3422   MachineBasicBlock *LoopBB = InsPt->getParent();
3423 
3424   if (UseGPRIdxMode) {
3425     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3426       .addReg(SrcReg, RegState::Undef, SubReg)
3427       .addReg(SrcReg, RegState::Implicit)
3428       .addReg(AMDGPU::M0, RegState::Implicit);
3429     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3430   } else {
3431     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3432       .addReg(SrcReg, RegState::Undef, SubReg)
3433       .addReg(SrcReg, RegState::Implicit);
3434   }
3435 
3436   MI.eraseFromParent();
3437 
3438   return LoopBB;
3439 }
3440 
3441 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3442                                  const TargetRegisterClass *VecRC) {
3443   switch (TRI.getRegSizeInBits(*VecRC)) {
3444   case 32: // 4 bytes
3445     return AMDGPU::V_MOVRELD_B32_V1;
3446   case 64: // 8 bytes
3447     return AMDGPU::V_MOVRELD_B32_V2;
3448   case 128: // 16 bytes
3449     return AMDGPU::V_MOVRELD_B32_V4;
3450   case 256: // 32 bytes
3451     return AMDGPU::V_MOVRELD_B32_V8;
3452   case 512: // 64 bytes
3453     return AMDGPU::V_MOVRELD_B32_V16;
3454   default:
3455     llvm_unreachable("unsupported size for MOVRELD pseudos");
3456   }
3457 }
3458 
3459 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3460                                           MachineBasicBlock &MBB,
3461                                           const GCNSubtarget &ST) {
3462   const SIInstrInfo *TII = ST.getInstrInfo();
3463   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3464   MachineFunction *MF = MBB.getParent();
3465   MachineRegisterInfo &MRI = MF->getRegInfo();
3466 
3467   unsigned Dst = MI.getOperand(0).getReg();
3468   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3469   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3470   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3471   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3472   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3473 
3474   // This can be an immediate, but will be folded later.
3475   assert(Val->getReg());
3476 
3477   unsigned SubReg;
3478   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3479                                                          SrcVec->getReg(),
3480                                                          Offset);
3481   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3482 
3483   if (Idx->getReg() == AMDGPU::NoRegister) {
3484     MachineBasicBlock::iterator I(&MI);
3485     const DebugLoc &DL = MI.getDebugLoc();
3486 
3487     assert(Offset == 0);
3488 
3489     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3490         .add(*SrcVec)
3491         .add(*Val)
3492         .addImm(SubReg);
3493 
3494     MI.eraseFromParent();
3495     return &MBB;
3496   }
3497 
3498   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3499     MachineBasicBlock::iterator I(&MI);
3500     const DebugLoc &DL = MI.getDebugLoc();
3501 
3502     if (UseGPRIdxMode) {
3503       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3504           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3505           .add(*Val)
3506           .addReg(Dst, RegState::ImplicitDefine)
3507           .addReg(SrcVec->getReg(), RegState::Implicit)
3508           .addReg(AMDGPU::M0, RegState::Implicit);
3509 
3510       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3511     } else {
3512       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3513 
3514       BuildMI(MBB, I, DL, MovRelDesc)
3515           .addReg(Dst, RegState::Define)
3516           .addReg(SrcVec->getReg())
3517           .add(*Val)
3518           .addImm(SubReg - AMDGPU::sub0);
3519     }
3520 
3521     MI.eraseFromParent();
3522     return &MBB;
3523   }
3524 
3525   if (Val->isReg())
3526     MRI.clearKillFlags(Val->getReg());
3527 
3528   const DebugLoc &DL = MI.getDebugLoc();
3529 
3530   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3531 
3532   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3533                               Offset, UseGPRIdxMode, false);
3534   MachineBasicBlock *LoopBB = InsPt->getParent();
3535 
3536   if (UseGPRIdxMode) {
3537     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3538         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3539         .add(*Val)                               // src0
3540         .addReg(Dst, RegState::ImplicitDefine)
3541         .addReg(PhiReg, RegState::Implicit)
3542         .addReg(AMDGPU::M0, RegState::Implicit);
3543     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3544   } else {
3545     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3546 
3547     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3548         .addReg(Dst, RegState::Define)
3549         .addReg(PhiReg)
3550         .add(*Val)
3551         .addImm(SubReg - AMDGPU::sub0);
3552   }
3553 
3554   MI.eraseFromParent();
3555 
3556   return LoopBB;
3557 }
3558 
3559 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3560   MachineInstr &MI, MachineBasicBlock *BB) const {
3561 
3562   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3563   MachineFunction *MF = BB->getParent();
3564   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3565 
3566   if (TII->isMIMG(MI)) {
3567     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3568       report_fatal_error("missing mem operand from MIMG instruction");
3569     }
3570     // Add a memoperand for mimg instructions so that they aren't assumed to
3571     // be ordered memory instuctions.
3572 
3573     return BB;
3574   }
3575 
3576   switch (MI.getOpcode()) {
3577   case AMDGPU::S_ADD_U64_PSEUDO:
3578   case AMDGPU::S_SUB_U64_PSEUDO: {
3579     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3580     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3581     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3582     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3583     const DebugLoc &DL = MI.getDebugLoc();
3584 
3585     MachineOperand &Dest = MI.getOperand(0);
3586     MachineOperand &Src0 = MI.getOperand(1);
3587     MachineOperand &Src1 = MI.getOperand(2);
3588 
3589     unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3590     unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3591 
3592     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3593      Src0, BoolRC, AMDGPU::sub0,
3594      &AMDGPU::SReg_32_XM0RegClass);
3595     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3596       Src0, BoolRC, AMDGPU::sub1,
3597       &AMDGPU::SReg_32_XM0RegClass);
3598 
3599     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3600       Src1, BoolRC, AMDGPU::sub0,
3601       &AMDGPU::SReg_32_XM0RegClass);
3602     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3603       Src1, BoolRC, AMDGPU::sub1,
3604       &AMDGPU::SReg_32_XM0RegClass);
3605 
3606     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3607 
3608     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3609     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3610     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3611       .add(Src0Sub0)
3612       .add(Src1Sub0);
3613     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3614       .add(Src0Sub1)
3615       .add(Src1Sub1);
3616     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3617       .addReg(DestSub0)
3618       .addImm(AMDGPU::sub0)
3619       .addReg(DestSub1)
3620       .addImm(AMDGPU::sub1);
3621     MI.eraseFromParent();
3622     return BB;
3623   }
3624   case AMDGPU::SI_INIT_M0: {
3625     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3626             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3627         .add(MI.getOperand(0));
3628     MI.eraseFromParent();
3629     return BB;
3630   }
3631   case AMDGPU::SI_INIT_EXEC:
3632     // This should be before all vector instructions.
3633     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3634             AMDGPU::EXEC)
3635         .addImm(MI.getOperand(0).getImm());
3636     MI.eraseFromParent();
3637     return BB;
3638 
3639   case AMDGPU::SI_INIT_EXEC_LO:
3640     // This should be before all vector instructions.
3641     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3642             AMDGPU::EXEC_LO)
3643         .addImm(MI.getOperand(0).getImm());
3644     MI.eraseFromParent();
3645     return BB;
3646 
3647   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3648     // Extract the thread count from an SGPR input and set EXEC accordingly.
3649     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3650     //
3651     // S_BFE_U32 count, input, {shift, 7}
3652     // S_BFM_B64 exec, count, 0
3653     // S_CMP_EQ_U32 count, 64
3654     // S_CMOV_B64 exec, -1
3655     MachineInstr *FirstMI = &*BB->begin();
3656     MachineRegisterInfo &MRI = MF->getRegInfo();
3657     unsigned InputReg = MI.getOperand(0).getReg();
3658     unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3659     bool Found = false;
3660 
3661     // Move the COPY of the input reg to the beginning, so that we can use it.
3662     for (auto I = BB->begin(); I != &MI; I++) {
3663       if (I->getOpcode() != TargetOpcode::COPY ||
3664           I->getOperand(0).getReg() != InputReg)
3665         continue;
3666 
3667       if (I == FirstMI) {
3668         FirstMI = &*++BB->begin();
3669       } else {
3670         I->removeFromParent();
3671         BB->insert(FirstMI, &*I);
3672       }
3673       Found = true;
3674       break;
3675     }
3676     assert(Found);
3677     (void)Found;
3678 
3679     // This should be before all vector instructions.
3680     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3681     bool isWave32 = getSubtarget()->isWave32();
3682     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3683     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3684         .addReg(InputReg)
3685         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3686     BuildMI(*BB, FirstMI, DebugLoc(),
3687             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3688             Exec)
3689         .addReg(CountReg)
3690         .addImm(0);
3691     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3692         .addReg(CountReg, RegState::Kill)
3693         .addImm(getSubtarget()->getWavefrontSize());
3694     BuildMI(*BB, FirstMI, DebugLoc(),
3695             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3696             Exec)
3697         .addImm(-1);
3698     MI.eraseFromParent();
3699     return BB;
3700   }
3701 
3702   case AMDGPU::GET_GROUPSTATICSIZE: {
3703     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3704            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3705     DebugLoc DL = MI.getDebugLoc();
3706     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3707         .add(MI.getOperand(0))
3708         .addImm(MFI->getLDSSize());
3709     MI.eraseFromParent();
3710     return BB;
3711   }
3712   case AMDGPU::SI_INDIRECT_SRC_V1:
3713   case AMDGPU::SI_INDIRECT_SRC_V2:
3714   case AMDGPU::SI_INDIRECT_SRC_V4:
3715   case AMDGPU::SI_INDIRECT_SRC_V8:
3716   case AMDGPU::SI_INDIRECT_SRC_V16:
3717     return emitIndirectSrc(MI, *BB, *getSubtarget());
3718   case AMDGPU::SI_INDIRECT_DST_V1:
3719   case AMDGPU::SI_INDIRECT_DST_V2:
3720   case AMDGPU::SI_INDIRECT_DST_V4:
3721   case AMDGPU::SI_INDIRECT_DST_V8:
3722   case AMDGPU::SI_INDIRECT_DST_V16:
3723     return emitIndirectDst(MI, *BB, *getSubtarget());
3724   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3725   case AMDGPU::SI_KILL_I1_PSEUDO:
3726     return splitKillBlock(MI, BB);
3727   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3728     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3729     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3730     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3731 
3732     unsigned Dst = MI.getOperand(0).getReg();
3733     unsigned Src0 = MI.getOperand(1).getReg();
3734     unsigned Src1 = MI.getOperand(2).getReg();
3735     const DebugLoc &DL = MI.getDebugLoc();
3736     unsigned SrcCond = MI.getOperand(3).getReg();
3737 
3738     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3739     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3740     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3741     unsigned SrcCondCopy = MRI.createVirtualRegister(CondRC);
3742 
3743     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3744       .addReg(SrcCond);
3745     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3746       .addImm(0)
3747       .addReg(Src0, 0, AMDGPU::sub0)
3748       .addImm(0)
3749       .addReg(Src1, 0, AMDGPU::sub0)
3750       .addReg(SrcCondCopy);
3751     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3752       .addImm(0)
3753       .addReg(Src0, 0, AMDGPU::sub1)
3754       .addImm(0)
3755       .addReg(Src1, 0, AMDGPU::sub1)
3756       .addReg(SrcCondCopy);
3757 
3758     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3759       .addReg(DstLo)
3760       .addImm(AMDGPU::sub0)
3761       .addReg(DstHi)
3762       .addImm(AMDGPU::sub1);
3763     MI.eraseFromParent();
3764     return BB;
3765   }
3766   case AMDGPU::SI_BR_UNDEF: {
3767     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3768     const DebugLoc &DL = MI.getDebugLoc();
3769     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3770                            .add(MI.getOperand(0));
3771     Br->getOperand(1).setIsUndef(true); // read undef SCC
3772     MI.eraseFromParent();
3773     return BB;
3774   }
3775   case AMDGPU::ADJCALLSTACKUP:
3776   case AMDGPU::ADJCALLSTACKDOWN: {
3777     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3778     MachineInstrBuilder MIB(*MF, &MI);
3779 
3780     // Add an implicit use of the frame offset reg to prevent the restore copy
3781     // inserted after the call from being reorderd after stack operations in the
3782     // the caller's frame.
3783     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3784         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3785         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3786     return BB;
3787   }
3788   case AMDGPU::SI_CALL_ISEL: {
3789     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3790     const DebugLoc &DL = MI.getDebugLoc();
3791 
3792     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3793 
3794     MachineInstrBuilder MIB;
3795     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3796 
3797     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3798       MIB.add(MI.getOperand(I));
3799 
3800     MIB.cloneMemRefs(MI);
3801     MI.eraseFromParent();
3802     return BB;
3803   }
3804   case AMDGPU::V_ADD_I32_e32:
3805   case AMDGPU::V_SUB_I32_e32:
3806   case AMDGPU::V_SUBREV_I32_e32: {
3807     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3808     const DebugLoc &DL = MI.getDebugLoc();
3809     unsigned Opc = MI.getOpcode();
3810 
3811     bool NeedClampOperand = false;
3812     if (TII->pseudoToMCOpcode(Opc) == -1) {
3813       Opc = AMDGPU::getVOPe64(Opc);
3814       NeedClampOperand = true;
3815     }
3816 
3817     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3818     if (TII->isVOP3(*I)) {
3819       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3820       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3821       I.addReg(TRI->getVCC(), RegState::Define);
3822     }
3823     I.add(MI.getOperand(1))
3824      .add(MI.getOperand(2));
3825     if (NeedClampOperand)
3826       I.addImm(0); // clamp bit for e64 encoding
3827 
3828     TII->legalizeOperands(*I);
3829 
3830     MI.eraseFromParent();
3831     return BB;
3832   }
3833   case AMDGPU::DS_GWS_INIT:
3834   case AMDGPU::DS_GWS_SEMA_V:
3835   case AMDGPU::DS_GWS_SEMA_BR:
3836   case AMDGPU::DS_GWS_SEMA_P:
3837   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3838   case AMDGPU::DS_GWS_BARRIER:
3839     // A s_waitcnt 0 is required to be the instruction immediately following.
3840     if (getSubtarget()->hasGWSAutoReplay()) {
3841       bundleInstWithWaitcnt(MI);
3842       return BB;
3843     }
3844 
3845     return emitGWSMemViolTestLoop(MI, BB);
3846   default:
3847     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3848   }
3849 }
3850 
3851 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3852   return isTypeLegal(VT.getScalarType());
3853 }
3854 
3855 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3856   // This currently forces unfolding various combinations of fsub into fma with
3857   // free fneg'd operands. As long as we have fast FMA (controlled by
3858   // isFMAFasterThanFMulAndFAdd), we should perform these.
3859 
3860   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3861   // most of these combines appear to be cycle neutral but save on instruction
3862   // count / code size.
3863   return true;
3864 }
3865 
3866 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3867                                          EVT VT) const {
3868   if (!VT.isVector()) {
3869     return MVT::i1;
3870   }
3871   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3872 }
3873 
3874 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3875   // TODO: Should i16 be used always if legal? For now it would force VALU
3876   // shifts.
3877   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3878 }
3879 
3880 // Answering this is somewhat tricky and depends on the specific device which
3881 // have different rates for fma or all f64 operations.
3882 //
3883 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3884 // regardless of which device (although the number of cycles differs between
3885 // devices), so it is always profitable for f64.
3886 //
3887 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3888 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3889 // which we can always do even without fused FP ops since it returns the same
3890 // result as the separate operations and since it is always full
3891 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3892 // however does not support denormals, so we do report fma as faster if we have
3893 // a fast fma device and require denormals.
3894 //
3895 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3896   VT = VT.getScalarType();
3897 
3898   switch (VT.getSimpleVT().SimpleTy) {
3899   case MVT::f32: {
3900     // This is as fast on some subtargets. However, we always have full rate f32
3901     // mad available which returns the same result as the separate operations
3902     // which we should prefer over fma. We can't use this if we want to support
3903     // denormals, so only report this in these cases.
3904     if (Subtarget->hasFP32Denormals())
3905       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3906 
3907     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3908     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3909   }
3910   case MVT::f64:
3911     return true;
3912   case MVT::f16:
3913     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3914   default:
3915     break;
3916   }
3917 
3918   return false;
3919 }
3920 
3921 //===----------------------------------------------------------------------===//
3922 // Custom DAG Lowering Operations
3923 //===----------------------------------------------------------------------===//
3924 
3925 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3926 // wider vector type is legal.
3927 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3928                                              SelectionDAG &DAG) const {
3929   unsigned Opc = Op.getOpcode();
3930   EVT VT = Op.getValueType();
3931   assert(VT == MVT::v4f16);
3932 
3933   SDValue Lo, Hi;
3934   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3935 
3936   SDLoc SL(Op);
3937   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3938                              Op->getFlags());
3939   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3940                              Op->getFlags());
3941 
3942   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3943 }
3944 
3945 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3946 // wider vector type is legal.
3947 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3948                                               SelectionDAG &DAG) const {
3949   unsigned Opc = Op.getOpcode();
3950   EVT VT = Op.getValueType();
3951   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3952 
3953   SDValue Lo0, Hi0;
3954   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3955   SDValue Lo1, Hi1;
3956   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3957 
3958   SDLoc SL(Op);
3959 
3960   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3961                              Op->getFlags());
3962   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3963                              Op->getFlags());
3964 
3965   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3966 }
3967 
3968 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
3969                                               SelectionDAG &DAG) const {
3970   unsigned Opc = Op.getOpcode();
3971   EVT VT = Op.getValueType();
3972   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3973 
3974   SDValue Lo0, Hi0;
3975   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3976   SDValue Lo1, Hi1;
3977   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3978   SDValue Lo2, Hi2;
3979   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
3980 
3981   SDLoc SL(Op);
3982 
3983   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
3984                              Op->getFlags());
3985   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
3986                              Op->getFlags());
3987 
3988   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3989 }
3990 
3991 
3992 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3993   switch (Op.getOpcode()) {
3994   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3995   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3996   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3997   case ISD::LOAD: {
3998     SDValue Result = LowerLOAD(Op, DAG);
3999     assert((!Result.getNode() ||
4000             Result.getNode()->getNumValues() == 2) &&
4001            "Load should return a value and a chain");
4002     return Result;
4003   }
4004 
4005   case ISD::FSIN:
4006   case ISD::FCOS:
4007     return LowerTrig(Op, DAG);
4008   case ISD::SELECT: return LowerSELECT(Op, DAG);
4009   case ISD::FDIV: return LowerFDIV(Op, DAG);
4010   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4011   case ISD::STORE: return LowerSTORE(Op, DAG);
4012   case ISD::GlobalAddress: {
4013     MachineFunction &MF = DAG.getMachineFunction();
4014     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4015     return LowerGlobalAddress(MFI, Op, DAG);
4016   }
4017   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4018   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4019   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4020   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4021   case ISD::INSERT_SUBVECTOR:
4022     return lowerINSERT_SUBVECTOR(Op, DAG);
4023   case ISD::INSERT_VECTOR_ELT:
4024     return lowerINSERT_VECTOR_ELT(Op, DAG);
4025   case ISD::EXTRACT_VECTOR_ELT:
4026     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4027   case ISD::VECTOR_SHUFFLE:
4028     return lowerVECTOR_SHUFFLE(Op, DAG);
4029   case ISD::BUILD_VECTOR:
4030     return lowerBUILD_VECTOR(Op, DAG);
4031   case ISD::FP_ROUND:
4032     return lowerFP_ROUND(Op, DAG);
4033   case ISD::TRAP:
4034     return lowerTRAP(Op, DAG);
4035   case ISD::DEBUGTRAP:
4036     return lowerDEBUGTRAP(Op, DAG);
4037   case ISD::FABS:
4038   case ISD::FNEG:
4039   case ISD::FCANONICALIZE:
4040     return splitUnaryVectorOp(Op, DAG);
4041   case ISD::FMINNUM:
4042   case ISD::FMAXNUM:
4043     return lowerFMINNUM_FMAXNUM(Op, DAG);
4044   case ISD::FMA:
4045     return splitTernaryVectorOp(Op, DAG);
4046   case ISD::SHL:
4047   case ISD::SRA:
4048   case ISD::SRL:
4049   case ISD::ADD:
4050   case ISD::SUB:
4051   case ISD::MUL:
4052   case ISD::SMIN:
4053   case ISD::SMAX:
4054   case ISD::UMIN:
4055   case ISD::UMAX:
4056   case ISD::FADD:
4057   case ISD::FMUL:
4058   case ISD::FMINNUM_IEEE:
4059   case ISD::FMAXNUM_IEEE:
4060     return splitBinaryVectorOp(Op, DAG);
4061   }
4062   return SDValue();
4063 }
4064 
4065 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4066                                        const SDLoc &DL,
4067                                        SelectionDAG &DAG, bool Unpacked) {
4068   if (!LoadVT.isVector())
4069     return Result;
4070 
4071   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4072     // Truncate to v2i16/v4i16.
4073     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4074 
4075     // Workaround legalizer not scalarizing truncate after vector op
4076     // legalization byt not creating intermediate vector trunc.
4077     SmallVector<SDValue, 4> Elts;
4078     DAG.ExtractVectorElements(Result, Elts);
4079     for (SDValue &Elt : Elts)
4080       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4081 
4082     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4083 
4084     // Bitcast to original type (v2f16/v4f16).
4085     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4086   }
4087 
4088   // Cast back to the original packed type.
4089   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4090 }
4091 
4092 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4093                                               MemSDNode *M,
4094                                               SelectionDAG &DAG,
4095                                               ArrayRef<SDValue> Ops,
4096                                               bool IsIntrinsic) const {
4097   SDLoc DL(M);
4098 
4099   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4100   EVT LoadVT = M->getValueType(0);
4101 
4102   EVT EquivLoadVT = LoadVT;
4103   if (Unpacked && LoadVT.isVector()) {
4104     EquivLoadVT = LoadVT.isVector() ?
4105       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4106                        LoadVT.getVectorNumElements()) : LoadVT;
4107   }
4108 
4109   // Change from v4f16/v2f16 to EquivLoadVT.
4110   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4111 
4112   SDValue Load
4113     = DAG.getMemIntrinsicNode(
4114       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4115       VTList, Ops, M->getMemoryVT(),
4116       M->getMemOperand());
4117   if (!Unpacked) // Just adjusted the opcode.
4118     return Load;
4119 
4120   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4121 
4122   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4123 }
4124 
4125 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4126                                              SelectionDAG &DAG,
4127                                              ArrayRef<SDValue> Ops) const {
4128   SDLoc DL(M);
4129   EVT LoadVT = M->getValueType(0);
4130   EVT EltType = LoadVT.getScalarType();
4131   EVT IntVT = LoadVT.changeTypeToInteger();
4132 
4133   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4134 
4135   unsigned Opc =
4136       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4137 
4138   if (IsD16) {
4139     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4140   }
4141 
4142   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4143   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4144     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4145 
4146   if (isTypeLegal(LoadVT)) {
4147     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4148                                M->getMemOperand(), DAG);
4149   }
4150 
4151   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4152   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4153   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4154                                         M->getMemOperand(), DAG);
4155   return DAG.getMergeValues(
4156       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4157       DL);
4158 }
4159 
4160 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4161                                   SDNode *N, SelectionDAG &DAG) {
4162   EVT VT = N->getValueType(0);
4163   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4164   int CondCode = CD->getSExtValue();
4165   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4166       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4167     return DAG.getUNDEF(VT);
4168 
4169   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4170 
4171   SDValue LHS = N->getOperand(1);
4172   SDValue RHS = N->getOperand(2);
4173 
4174   SDLoc DL(N);
4175 
4176   EVT CmpVT = LHS.getValueType();
4177   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4178     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4179       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4180     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4181     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4182   }
4183 
4184   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4185 
4186   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4187   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4188 
4189   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4190                               DAG.getCondCode(CCOpcode));
4191   if (VT.bitsEq(CCVT))
4192     return SetCC;
4193   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4194 }
4195 
4196 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4197                                   SDNode *N, SelectionDAG &DAG) {
4198   EVT VT = N->getValueType(0);
4199   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4200 
4201   int CondCode = CD->getSExtValue();
4202   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4203       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4204     return DAG.getUNDEF(VT);
4205   }
4206 
4207   SDValue Src0 = N->getOperand(1);
4208   SDValue Src1 = N->getOperand(2);
4209   EVT CmpVT = Src0.getValueType();
4210   SDLoc SL(N);
4211 
4212   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4213     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4214     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4215   }
4216 
4217   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4218   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4219   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4220   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4221   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4222                               Src1, DAG.getCondCode(CCOpcode));
4223   if (VT.bitsEq(CCVT))
4224     return SetCC;
4225   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4226 }
4227 
4228 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4229                                           SmallVectorImpl<SDValue> &Results,
4230                                           SelectionDAG &DAG) const {
4231   switch (N->getOpcode()) {
4232   case ISD::INSERT_VECTOR_ELT: {
4233     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4234       Results.push_back(Res);
4235     return;
4236   }
4237   case ISD::EXTRACT_VECTOR_ELT: {
4238     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4239       Results.push_back(Res);
4240     return;
4241   }
4242   case ISD::INTRINSIC_WO_CHAIN: {
4243     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4244     switch (IID) {
4245     case Intrinsic::amdgcn_cvt_pkrtz: {
4246       SDValue Src0 = N->getOperand(1);
4247       SDValue Src1 = N->getOperand(2);
4248       SDLoc SL(N);
4249       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4250                                 Src0, Src1);
4251       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4252       return;
4253     }
4254     case Intrinsic::amdgcn_cvt_pknorm_i16:
4255     case Intrinsic::amdgcn_cvt_pknorm_u16:
4256     case Intrinsic::amdgcn_cvt_pk_i16:
4257     case Intrinsic::amdgcn_cvt_pk_u16: {
4258       SDValue Src0 = N->getOperand(1);
4259       SDValue Src1 = N->getOperand(2);
4260       SDLoc SL(N);
4261       unsigned Opcode;
4262 
4263       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4264         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4265       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4266         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4267       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4268         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4269       else
4270         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4271 
4272       EVT VT = N->getValueType(0);
4273       if (isTypeLegal(VT))
4274         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4275       else {
4276         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4277         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4278       }
4279       return;
4280     }
4281     }
4282     break;
4283   }
4284   case ISD::INTRINSIC_W_CHAIN: {
4285     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4286       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4287         // FIXME: Hacky
4288         Results.push_back(Res.getOperand(0));
4289         Results.push_back(Res.getOperand(1));
4290       } else {
4291         Results.push_back(Res);
4292         Results.push_back(Res.getValue(1));
4293       }
4294       return;
4295     }
4296 
4297     break;
4298   }
4299   case ISD::SELECT: {
4300     SDLoc SL(N);
4301     EVT VT = N->getValueType(0);
4302     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4303     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4304     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4305 
4306     EVT SelectVT = NewVT;
4307     if (NewVT.bitsLT(MVT::i32)) {
4308       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4309       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4310       SelectVT = MVT::i32;
4311     }
4312 
4313     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4314                                     N->getOperand(0), LHS, RHS);
4315 
4316     if (NewVT != SelectVT)
4317       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4318     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4319     return;
4320   }
4321   case ISD::FNEG: {
4322     if (N->getValueType(0) != MVT::v2f16)
4323       break;
4324 
4325     SDLoc SL(N);
4326     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4327 
4328     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4329                              BC,
4330                              DAG.getConstant(0x80008000, SL, MVT::i32));
4331     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4332     return;
4333   }
4334   case ISD::FABS: {
4335     if (N->getValueType(0) != MVT::v2f16)
4336       break;
4337 
4338     SDLoc SL(N);
4339     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4340 
4341     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4342                              BC,
4343                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4344     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4345     return;
4346   }
4347   default:
4348     break;
4349   }
4350 }
4351 
4352 /// Helper function for LowerBRCOND
4353 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4354 
4355   SDNode *Parent = Value.getNode();
4356   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4357        I != E; ++I) {
4358 
4359     if (I.getUse().get() != Value)
4360       continue;
4361 
4362     if (I->getOpcode() == Opcode)
4363       return *I;
4364   }
4365   return nullptr;
4366 }
4367 
4368 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4369   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4370     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4371     case Intrinsic::amdgcn_if:
4372       return AMDGPUISD::IF;
4373     case Intrinsic::amdgcn_else:
4374       return AMDGPUISD::ELSE;
4375     case Intrinsic::amdgcn_loop:
4376       return AMDGPUISD::LOOP;
4377     case Intrinsic::amdgcn_end_cf:
4378       llvm_unreachable("should not occur");
4379     default:
4380       return 0;
4381     }
4382   }
4383 
4384   // break, if_break, else_break are all only used as inputs to loop, not
4385   // directly as branch conditions.
4386   return 0;
4387 }
4388 
4389 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4390   const Triple &TT = getTargetMachine().getTargetTriple();
4391   return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4392           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4393          AMDGPU::shouldEmitConstantsToTextSection(TT);
4394 }
4395 
4396 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4397   // FIXME: Either avoid relying on address space here or change the default
4398   // address space for functions to avoid the explicit check.
4399   return (GV->getValueType()->isFunctionTy() ||
4400           GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4401           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4402           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4403          !shouldEmitFixup(GV) &&
4404          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4405 }
4406 
4407 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4408   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4409 }
4410 
4411 /// This transforms the control flow intrinsics to get the branch destination as
4412 /// last parameter, also switches branch target with BR if the need arise
4413 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4414                                       SelectionDAG &DAG) const {
4415   SDLoc DL(BRCOND);
4416 
4417   SDNode *Intr = BRCOND.getOperand(1).getNode();
4418   SDValue Target = BRCOND.getOperand(2);
4419   SDNode *BR = nullptr;
4420   SDNode *SetCC = nullptr;
4421 
4422   if (Intr->getOpcode() == ISD::SETCC) {
4423     // As long as we negate the condition everything is fine
4424     SetCC = Intr;
4425     Intr = SetCC->getOperand(0).getNode();
4426 
4427   } else {
4428     // Get the target from BR if we don't negate the condition
4429     BR = findUser(BRCOND, ISD::BR);
4430     Target = BR->getOperand(1);
4431   }
4432 
4433   // FIXME: This changes the types of the intrinsics instead of introducing new
4434   // nodes with the correct types.
4435   // e.g. llvm.amdgcn.loop
4436 
4437   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4438   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4439 
4440   unsigned CFNode = isCFIntrinsic(Intr);
4441   if (CFNode == 0) {
4442     // This is a uniform branch so we don't need to legalize.
4443     return BRCOND;
4444   }
4445 
4446   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4447                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4448 
4449   assert(!SetCC ||
4450         (SetCC->getConstantOperandVal(1) == 1 &&
4451          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4452                                                              ISD::SETNE));
4453 
4454   // operands of the new intrinsic call
4455   SmallVector<SDValue, 4> Ops;
4456   if (HaveChain)
4457     Ops.push_back(BRCOND.getOperand(0));
4458 
4459   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4460   Ops.push_back(Target);
4461 
4462   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4463 
4464   // build the new intrinsic call
4465   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4466 
4467   if (!HaveChain) {
4468     SDValue Ops[] =  {
4469       SDValue(Result, 0),
4470       BRCOND.getOperand(0)
4471     };
4472 
4473     Result = DAG.getMergeValues(Ops, DL).getNode();
4474   }
4475 
4476   if (BR) {
4477     // Give the branch instruction our target
4478     SDValue Ops[] = {
4479       BR->getOperand(0),
4480       BRCOND.getOperand(2)
4481     };
4482     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4483     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4484     BR = NewBR.getNode();
4485   }
4486 
4487   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4488 
4489   // Copy the intrinsic results to registers
4490   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4491     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4492     if (!CopyToReg)
4493       continue;
4494 
4495     Chain = DAG.getCopyToReg(
4496       Chain, DL,
4497       CopyToReg->getOperand(1),
4498       SDValue(Result, i - 1),
4499       SDValue());
4500 
4501     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4502   }
4503 
4504   // Remove the old intrinsic from the chain
4505   DAG.ReplaceAllUsesOfValueWith(
4506     SDValue(Intr, Intr->getNumValues() - 1),
4507     Intr->getOperand(0));
4508 
4509   return Chain;
4510 }
4511 
4512 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4513                                           SelectionDAG &DAG) const {
4514   MVT VT = Op.getSimpleValueType();
4515   SDLoc DL(Op);
4516   // Checking the depth
4517   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4518     return DAG.getConstant(0, DL, VT);
4519 
4520   MachineFunction &MF = DAG.getMachineFunction();
4521   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4522   // Check for kernel and shader functions
4523   if (Info->isEntryFunction())
4524     return DAG.getConstant(0, DL, VT);
4525 
4526   MachineFrameInfo &MFI = MF.getFrameInfo();
4527   // There is a call to @llvm.returnaddress in this function
4528   MFI.setReturnAddressIsTaken(true);
4529 
4530   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4531   // Get the return address reg and mark it as an implicit live-in
4532   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4533 
4534   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4535 }
4536 
4537 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4538                                             SDValue Op,
4539                                             const SDLoc &DL,
4540                                             EVT VT) const {
4541   return Op.getValueType().bitsLE(VT) ?
4542       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4543       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4544 }
4545 
4546 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4547   assert(Op.getValueType() == MVT::f16 &&
4548          "Do not know how to custom lower FP_ROUND for non-f16 type");
4549 
4550   SDValue Src = Op.getOperand(0);
4551   EVT SrcVT = Src.getValueType();
4552   if (SrcVT != MVT::f64)
4553     return Op;
4554 
4555   SDLoc DL(Op);
4556 
4557   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4558   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4559   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4560 }
4561 
4562 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4563                                                SelectionDAG &DAG) const {
4564   EVT VT = Op.getValueType();
4565   const MachineFunction &MF = DAG.getMachineFunction();
4566   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4567   bool IsIEEEMode = Info->getMode().IEEE;
4568 
4569   // FIXME: Assert during eslection that this is only selected for
4570   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4571   // mode functions, but this happens to be OK since it's only done in cases
4572   // where there is known no sNaN.
4573   if (IsIEEEMode)
4574     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4575 
4576   if (VT == MVT::v4f16)
4577     return splitBinaryVectorOp(Op, DAG);
4578   return Op;
4579 }
4580 
4581 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4582   SDLoc SL(Op);
4583   SDValue Chain = Op.getOperand(0);
4584 
4585   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4586       !Subtarget->isTrapHandlerEnabled())
4587     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4588 
4589   MachineFunction &MF = DAG.getMachineFunction();
4590   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4591   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4592   assert(UserSGPR != AMDGPU::NoRegister);
4593   SDValue QueuePtr = CreateLiveInRegister(
4594     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4595   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4596   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4597                                    QueuePtr, SDValue());
4598   SDValue Ops[] = {
4599     ToReg,
4600     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4601     SGPR01,
4602     ToReg.getValue(1)
4603   };
4604   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4605 }
4606 
4607 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4608   SDLoc SL(Op);
4609   SDValue Chain = Op.getOperand(0);
4610   MachineFunction &MF = DAG.getMachineFunction();
4611 
4612   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4613       !Subtarget->isTrapHandlerEnabled()) {
4614     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4615                                      "debugtrap handler not supported",
4616                                      Op.getDebugLoc(),
4617                                      DS_Warning);
4618     LLVMContext &Ctx = MF.getFunction().getContext();
4619     Ctx.diagnose(NoTrap);
4620     return Chain;
4621   }
4622 
4623   SDValue Ops[] = {
4624     Chain,
4625     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4626   };
4627   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4628 }
4629 
4630 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4631                                              SelectionDAG &DAG) const {
4632   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4633   if (Subtarget->hasApertureRegs()) {
4634     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4635         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4636         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4637     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4638         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4639         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4640     unsigned Encoding =
4641         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4642         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4643         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4644 
4645     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4646     SDValue ApertureReg = SDValue(
4647         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4648     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4649     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4650   }
4651 
4652   MachineFunction &MF = DAG.getMachineFunction();
4653   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4654   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4655   assert(UserSGPR != AMDGPU::NoRegister);
4656 
4657   SDValue QueuePtr = CreateLiveInRegister(
4658     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4659 
4660   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4661   // private_segment_aperture_base_hi.
4662   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4663 
4664   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4665 
4666   // TODO: Use custom target PseudoSourceValue.
4667   // TODO: We should use the value from the IR intrinsic call, but it might not
4668   // be available and how do we get it?
4669   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4670                                               AMDGPUAS::CONSTANT_ADDRESS));
4671 
4672   MachinePointerInfo PtrInfo(V, StructOffset);
4673   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4674                      MinAlign(64, StructOffset),
4675                      MachineMemOperand::MODereferenceable |
4676                          MachineMemOperand::MOInvariant);
4677 }
4678 
4679 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4680                                              SelectionDAG &DAG) const {
4681   SDLoc SL(Op);
4682   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4683 
4684   SDValue Src = ASC->getOperand(0);
4685   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4686 
4687   const AMDGPUTargetMachine &TM =
4688     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4689 
4690   // flat -> local/private
4691   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4692     unsigned DestAS = ASC->getDestAddressSpace();
4693 
4694     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4695         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4696       unsigned NullVal = TM.getNullPointerValue(DestAS);
4697       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4698       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4699       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4700 
4701       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4702                          NonNull, Ptr, SegmentNullPtr);
4703     }
4704   }
4705 
4706   // local/private -> flat
4707   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4708     unsigned SrcAS = ASC->getSrcAddressSpace();
4709 
4710     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4711         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4712       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4713       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4714 
4715       SDValue NonNull
4716         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4717 
4718       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4719       SDValue CvtPtr
4720         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4721 
4722       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4723                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4724                          FlatNullPtr);
4725     }
4726   }
4727 
4728   // global <-> flat are no-ops and never emitted.
4729 
4730   const MachineFunction &MF = DAG.getMachineFunction();
4731   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4732     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4733   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4734 
4735   return DAG.getUNDEF(ASC->getValueType(0));
4736 }
4737 
4738 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4739 // the small vector and inserting them into the big vector. That is better than
4740 // the default expansion of doing it via a stack slot. Even though the use of
4741 // the stack slot would be optimized away afterwards, the stack slot itself
4742 // remains.
4743 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4744                                                 SelectionDAG &DAG) const {
4745   SDValue Vec = Op.getOperand(0);
4746   SDValue Ins = Op.getOperand(1);
4747   SDValue Idx = Op.getOperand(2);
4748   EVT VecVT = Vec.getValueType();
4749   EVT InsVT = Ins.getValueType();
4750   EVT EltVT = VecVT.getVectorElementType();
4751   unsigned InsNumElts = InsVT.getVectorNumElements();
4752   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4753   SDLoc SL(Op);
4754 
4755   for (unsigned I = 0; I != InsNumElts; ++I) {
4756     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4757                               DAG.getConstant(I, SL, MVT::i32));
4758     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4759                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4760   }
4761   return Vec;
4762 }
4763 
4764 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4765                                                  SelectionDAG &DAG) const {
4766   SDValue Vec = Op.getOperand(0);
4767   SDValue InsVal = Op.getOperand(1);
4768   SDValue Idx = Op.getOperand(2);
4769   EVT VecVT = Vec.getValueType();
4770   EVT EltVT = VecVT.getVectorElementType();
4771   unsigned VecSize = VecVT.getSizeInBits();
4772   unsigned EltSize = EltVT.getSizeInBits();
4773 
4774 
4775   assert(VecSize <= 64);
4776 
4777   unsigned NumElts = VecVT.getVectorNumElements();
4778   SDLoc SL(Op);
4779   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4780 
4781   if (NumElts == 4 && EltSize == 16 && KIdx) {
4782     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4783 
4784     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4785                                  DAG.getConstant(0, SL, MVT::i32));
4786     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4787                                  DAG.getConstant(1, SL, MVT::i32));
4788 
4789     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4790     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4791 
4792     unsigned Idx = KIdx->getZExtValue();
4793     bool InsertLo = Idx < 2;
4794     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4795       InsertLo ? LoVec : HiVec,
4796       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4797       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4798 
4799     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4800 
4801     SDValue Concat = InsertLo ?
4802       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4803       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4804 
4805     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4806   }
4807 
4808   if (isa<ConstantSDNode>(Idx))
4809     return SDValue();
4810 
4811   MVT IntVT = MVT::getIntegerVT(VecSize);
4812 
4813   // Avoid stack access for dynamic indexing.
4814   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4815 
4816   // Create a congruent vector with the target value in each element so that
4817   // the required element can be masked and ORed into the target vector.
4818   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4819                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4820 
4821   assert(isPowerOf2_32(EltSize));
4822   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4823 
4824   // Convert vector index to bit-index.
4825   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4826 
4827   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4828   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4829                             DAG.getConstant(0xffff, SL, IntVT),
4830                             ScaledIdx);
4831 
4832   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4833   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4834                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4835 
4836   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4837   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4838 }
4839 
4840 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4841                                                   SelectionDAG &DAG) const {
4842   SDLoc SL(Op);
4843 
4844   EVT ResultVT = Op.getValueType();
4845   SDValue Vec = Op.getOperand(0);
4846   SDValue Idx = Op.getOperand(1);
4847   EVT VecVT = Vec.getValueType();
4848   unsigned VecSize = VecVT.getSizeInBits();
4849   EVT EltVT = VecVT.getVectorElementType();
4850   assert(VecSize <= 64);
4851 
4852   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4853 
4854   // Make sure we do any optimizations that will make it easier to fold
4855   // source modifiers before obscuring it with bit operations.
4856 
4857   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4858   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4859     return Combined;
4860 
4861   unsigned EltSize = EltVT.getSizeInBits();
4862   assert(isPowerOf2_32(EltSize));
4863 
4864   MVT IntVT = MVT::getIntegerVT(VecSize);
4865   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4866 
4867   // Convert vector index to bit-index (* EltSize)
4868   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4869 
4870   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4871   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4872 
4873   if (ResultVT == MVT::f16) {
4874     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4875     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4876   }
4877 
4878   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4879 }
4880 
4881 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4882   assert(Elt % 2 == 0);
4883   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4884 }
4885 
4886 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4887                                               SelectionDAG &DAG) const {
4888   SDLoc SL(Op);
4889   EVT ResultVT = Op.getValueType();
4890   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4891 
4892   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4893   EVT EltVT = PackVT.getVectorElementType();
4894   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4895 
4896   // vector_shuffle <0,1,6,7> lhs, rhs
4897   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4898   //
4899   // vector_shuffle <6,7,2,3> lhs, rhs
4900   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4901   //
4902   // vector_shuffle <6,7,0,1> lhs, rhs
4903   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4904 
4905   // Avoid scalarizing when both halves are reading from consecutive elements.
4906   SmallVector<SDValue, 4> Pieces;
4907   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4908     if (elementPairIsContiguous(SVN->getMask(), I)) {
4909       const int Idx = SVN->getMaskElt(I);
4910       int VecIdx = Idx < SrcNumElts ? 0 : 1;
4911       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4912       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4913                                     PackVT, SVN->getOperand(VecIdx),
4914                                     DAG.getConstant(EltIdx, SL, MVT::i32));
4915       Pieces.push_back(SubVec);
4916     } else {
4917       const int Idx0 = SVN->getMaskElt(I);
4918       const int Idx1 = SVN->getMaskElt(I + 1);
4919       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4920       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
4921       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
4922       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
4923 
4924       SDValue Vec0 = SVN->getOperand(VecIdx0);
4925       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4926                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
4927 
4928       SDValue Vec1 = SVN->getOperand(VecIdx1);
4929       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4930                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
4931       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
4932     }
4933   }
4934 
4935   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
4936 }
4937 
4938 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4939                                             SelectionDAG &DAG) const {
4940   SDLoc SL(Op);
4941   EVT VT = Op.getValueType();
4942 
4943   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4944     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4945 
4946     // Turn into pair of packed build_vectors.
4947     // TODO: Special case for constants that can be materialized with s_mov_b64.
4948     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4949                                     { Op.getOperand(0), Op.getOperand(1) });
4950     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4951                                     { Op.getOperand(2), Op.getOperand(3) });
4952 
4953     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4954     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4955 
4956     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4957     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4958   }
4959 
4960   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4961   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4962 
4963   SDValue Lo = Op.getOperand(0);
4964   SDValue Hi = Op.getOperand(1);
4965 
4966   // Avoid adding defined bits with the zero_extend.
4967   if (Hi.isUndef()) {
4968     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4969     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4970     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4971   }
4972 
4973   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4974   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4975 
4976   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4977                               DAG.getConstant(16, SL, MVT::i32));
4978   if (Lo.isUndef())
4979     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4980 
4981   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4982   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4983 
4984   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4985   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4986 }
4987 
4988 bool
4989 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4990   // We can fold offsets for anything that doesn't require a GOT relocation.
4991   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4992           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4993           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4994          !shouldEmitGOTReloc(GA->getGlobal());
4995 }
4996 
4997 static SDValue
4998 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4999                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5000                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5001   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5002   // lowered to the following code sequence:
5003   //
5004   // For constant address space:
5005   //   s_getpc_b64 s[0:1]
5006   //   s_add_u32 s0, s0, $symbol
5007   //   s_addc_u32 s1, s1, 0
5008   //
5009   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5010   //   a fixup or relocation is emitted to replace $symbol with a literal
5011   //   constant, which is a pc-relative offset from the encoding of the $symbol
5012   //   operand to the global variable.
5013   //
5014   // For global address space:
5015   //   s_getpc_b64 s[0:1]
5016   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5017   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5018   //
5019   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5020   //   fixups or relocations are emitted to replace $symbol@*@lo and
5021   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5022   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5023   //   operand to the global variable.
5024   //
5025   // What we want here is an offset from the value returned by s_getpc
5026   // (which is the address of the s_add_u32 instruction) to the global
5027   // variable, but since the encoding of $symbol starts 4 bytes after the start
5028   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5029   // small. This requires us to add 4 to the global variable offset in order to
5030   // compute the correct address.
5031   unsigned LoFlags = GAFlags;
5032   if (LoFlags == SIInstrInfo::MO_NONE)
5033     LoFlags = SIInstrInfo::MO_REL32;
5034   SDValue PtrLo =
5035       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, LoFlags);
5036   SDValue PtrHi;
5037   if (GAFlags == SIInstrInfo::MO_NONE) {
5038     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5039   } else {
5040     PtrHi =
5041         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5042   }
5043   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5044 }
5045 
5046 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5047                                              SDValue Op,
5048                                              SelectionDAG &DAG) const {
5049   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5050   const GlobalValue *GV = GSD->getGlobal();
5051   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5052        (!GV->hasExternalLinkage() ||
5053         getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
5054         getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) ||
5055       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5056       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5057     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5058 
5059   SDLoc DL(GSD);
5060   EVT PtrVT = Op.getValueType();
5061 
5062   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5063     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5064                                             SIInstrInfo::MO_ABS32_LO);
5065     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5066   }
5067 
5068   if (shouldEmitFixup(GV))
5069     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5070   else if (shouldEmitPCReloc(GV))
5071     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5072                                    SIInstrInfo::MO_REL32);
5073 
5074   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5075                                             SIInstrInfo::MO_GOTPCREL32);
5076 
5077   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5078   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5079   const DataLayout &DataLayout = DAG.getDataLayout();
5080   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5081   MachinePointerInfo PtrInfo
5082     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5083 
5084   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5085                      MachineMemOperand::MODereferenceable |
5086                          MachineMemOperand::MOInvariant);
5087 }
5088 
5089 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5090                                    const SDLoc &DL, SDValue V) const {
5091   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5092   // the destination register.
5093   //
5094   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5095   // so we will end up with redundant moves to m0.
5096   //
5097   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5098 
5099   // A Null SDValue creates a glue result.
5100   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5101                                   V, Chain);
5102   return SDValue(M0, 0);
5103 }
5104 
5105 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5106                                                  SDValue Op,
5107                                                  MVT VT,
5108                                                  unsigned Offset) const {
5109   SDLoc SL(Op);
5110   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5111                                            DAG.getEntryNode(), Offset, 4, false);
5112   // The local size values will have the hi 16-bits as zero.
5113   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5114                      DAG.getValueType(VT));
5115 }
5116 
5117 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5118                                         EVT VT) {
5119   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5120                                       "non-hsa intrinsic with hsa target",
5121                                       DL.getDebugLoc());
5122   DAG.getContext()->diagnose(BadIntrin);
5123   return DAG.getUNDEF(VT);
5124 }
5125 
5126 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5127                                          EVT VT) {
5128   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5129                                       "intrinsic not supported on subtarget",
5130                                       DL.getDebugLoc());
5131   DAG.getContext()->diagnose(BadIntrin);
5132   return DAG.getUNDEF(VT);
5133 }
5134 
5135 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5136                                     ArrayRef<SDValue> Elts) {
5137   assert(!Elts.empty());
5138   MVT Type;
5139   unsigned NumElts;
5140 
5141   if (Elts.size() == 1) {
5142     Type = MVT::f32;
5143     NumElts = 1;
5144   } else if (Elts.size() == 2) {
5145     Type = MVT::v2f32;
5146     NumElts = 2;
5147   } else if (Elts.size() <= 4) {
5148     Type = MVT::v4f32;
5149     NumElts = 4;
5150   } else if (Elts.size() <= 8) {
5151     Type = MVT::v8f32;
5152     NumElts = 8;
5153   } else {
5154     assert(Elts.size() <= 16);
5155     Type = MVT::v16f32;
5156     NumElts = 16;
5157   }
5158 
5159   SmallVector<SDValue, 16> VecElts(NumElts);
5160   for (unsigned i = 0; i < Elts.size(); ++i) {
5161     SDValue Elt = Elts[i];
5162     if (Elt.getValueType() != MVT::f32)
5163       Elt = DAG.getBitcast(MVT::f32, Elt);
5164     VecElts[i] = Elt;
5165   }
5166   for (unsigned i = Elts.size(); i < NumElts; ++i)
5167     VecElts[i] = DAG.getUNDEF(MVT::f32);
5168 
5169   if (NumElts == 1)
5170     return VecElts[0];
5171   return DAG.getBuildVector(Type, DL, VecElts);
5172 }
5173 
5174 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5175                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5176   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5177 
5178   uint64_t Value = CachePolicyConst->getZExtValue();
5179   SDLoc DL(CachePolicy);
5180   if (GLC) {
5181     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5182     Value &= ~(uint64_t)0x1;
5183   }
5184   if (SLC) {
5185     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5186     Value &= ~(uint64_t)0x2;
5187   }
5188   if (DLC) {
5189     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5190     Value &= ~(uint64_t)0x4;
5191   }
5192 
5193   return Value == 0;
5194 }
5195 
5196 // Re-construct the required return value for a image load intrinsic.
5197 // This is more complicated due to the optional use TexFailCtrl which means the required
5198 // return type is an aggregate
5199 static SDValue constructRetValue(SelectionDAG &DAG,
5200                                  MachineSDNode *Result,
5201                                  ArrayRef<EVT> ResultTypes,
5202                                  bool IsTexFail, bool Unpacked, bool IsD16,
5203                                  int DMaskPop, int NumVDataDwords,
5204                                  const SDLoc &DL, LLVMContext &Context) {
5205   // Determine the required return type. This is the same regardless of IsTexFail flag
5206   EVT ReqRetVT = ResultTypes[0];
5207   EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
5208   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5209   EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
5210   EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
5211                                            : AdjEltVT
5212                        : ReqRetVT;
5213 
5214   // Extract data part of the result
5215   // Bitcast the result to the same type as the required return type
5216   int NumElts;
5217   if (IsD16 && !Unpacked)
5218     NumElts = NumVDataDwords << 1;
5219   else
5220     NumElts = NumVDataDwords;
5221 
5222   EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
5223                            : AdjEltVT;
5224 
5225   // Special case for v6f16. Rather than add support for this, use v3i32 to
5226   // extract the data elements
5227   bool V6F16Special = false;
5228   if (NumElts == 6) {
5229     CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
5230     DMaskPop >>= 1;
5231     ReqRetNumElts >>= 1;
5232     V6F16Special = true;
5233     AdjVT = MVT::v2i32;
5234   }
5235 
5236   SDValue N = SDValue(Result, 0);
5237   SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
5238 
5239   // Iterate over the result
5240   SmallVector<SDValue, 4> BVElts;
5241 
5242   if (CastVT.isVector()) {
5243     DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
5244   } else {
5245     BVElts.push_back(CastRes);
5246   }
5247   int ExtraElts = ReqRetNumElts - DMaskPop;
5248   while(ExtraElts--)
5249     BVElts.push_back(DAG.getUNDEF(AdjEltVT));
5250 
5251   SDValue PreTFCRes;
5252   if (ReqRetNumElts > 1) {
5253     SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
5254     if (IsD16 && Unpacked)
5255       PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
5256     else
5257       PreTFCRes = NewVec;
5258   } else {
5259     PreTFCRes = BVElts[0];
5260   }
5261 
5262   if (V6F16Special)
5263     PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
5264 
5265   if (!IsTexFail) {
5266     if (Result->getNumValues() > 1)
5267       return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
5268     else
5269       return PreTFCRes;
5270   }
5271 
5272   // Extract the TexFail result and insert into aggregate return
5273   SmallVector<SDValue, 1> TFCElt;
5274   DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
5275   SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
5276   return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
5277 }
5278 
5279 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5280                          SDValue *LWE, bool &IsTexFail) {
5281   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5282 
5283   uint64_t Value = TexFailCtrlConst->getZExtValue();
5284   if (Value) {
5285     IsTexFail = true;
5286   }
5287 
5288   SDLoc DL(TexFailCtrlConst);
5289   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5290   Value &= ~(uint64_t)0x1;
5291   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5292   Value &= ~(uint64_t)0x2;
5293 
5294   return Value == 0;
5295 }
5296 
5297 SDValue SITargetLowering::lowerImage(SDValue Op,
5298                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5299                                      SelectionDAG &DAG) const {
5300   SDLoc DL(Op);
5301   MachineFunction &MF = DAG.getMachineFunction();
5302   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5303   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5304       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5305   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5306   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5307       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5308   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5309       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5310   unsigned IntrOpcode = Intr->BaseOpcode;
5311   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5312 
5313   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5314   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5315   bool IsD16 = false;
5316   bool IsA16 = false;
5317   SDValue VData;
5318   int NumVDataDwords;
5319   bool AdjustRetType = false;
5320 
5321   unsigned AddrIdx; // Index of first address argument
5322   unsigned DMask;
5323   unsigned DMaskLanes = 0;
5324 
5325   if (BaseOpcode->Atomic) {
5326     VData = Op.getOperand(2);
5327 
5328     bool Is64Bit = VData.getValueType() == MVT::i64;
5329     if (BaseOpcode->AtomicX2) {
5330       SDValue VData2 = Op.getOperand(3);
5331       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5332                                  {VData, VData2});
5333       if (Is64Bit)
5334         VData = DAG.getBitcast(MVT::v4i32, VData);
5335 
5336       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5337       DMask = Is64Bit ? 0xf : 0x3;
5338       NumVDataDwords = Is64Bit ? 4 : 2;
5339       AddrIdx = 4;
5340     } else {
5341       DMask = Is64Bit ? 0x3 : 0x1;
5342       NumVDataDwords = Is64Bit ? 2 : 1;
5343       AddrIdx = 3;
5344     }
5345   } else {
5346     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5347     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5348     DMask = DMaskConst->getZExtValue();
5349     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5350 
5351     if (BaseOpcode->Store) {
5352       VData = Op.getOperand(2);
5353 
5354       MVT StoreVT = VData.getSimpleValueType();
5355       if (StoreVT.getScalarType() == MVT::f16) {
5356         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5357           return Op; // D16 is unsupported for this instruction
5358 
5359         IsD16 = true;
5360         VData = handleD16VData(VData, DAG);
5361       }
5362 
5363       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5364     } else {
5365       // Work out the num dwords based on the dmask popcount and underlying type
5366       // and whether packing is supported.
5367       MVT LoadVT = ResultTypes[0].getSimpleVT();
5368       if (LoadVT.getScalarType() == MVT::f16) {
5369         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5370           return Op; // D16 is unsupported for this instruction
5371 
5372         IsD16 = true;
5373       }
5374 
5375       // Confirm that the return type is large enough for the dmask specified
5376       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5377           (!LoadVT.isVector() && DMaskLanes > 1))
5378           return Op;
5379 
5380       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5381         NumVDataDwords = (DMaskLanes + 1) / 2;
5382       else
5383         NumVDataDwords = DMaskLanes;
5384 
5385       AdjustRetType = true;
5386     }
5387 
5388     AddrIdx = DMaskIdx + 1;
5389   }
5390 
5391   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5392   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5393   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5394   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5395                        NumCoords + NumLCM;
5396   unsigned NumMIVAddrs = NumVAddrs;
5397 
5398   SmallVector<SDValue, 4> VAddrs;
5399 
5400   // Optimize _L to _LZ when _L is zero
5401   if (LZMappingInfo) {
5402     if (auto ConstantLod =
5403          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5404       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5405         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5406         NumMIVAddrs--;               // remove 'lod'
5407       }
5408     }
5409   }
5410 
5411   // Optimize _mip away, when 'lod' is zero
5412   if (MIPMappingInfo) {
5413     if (auto ConstantLod =
5414          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5415       if (ConstantLod->isNullValue()) {
5416         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5417         NumMIVAddrs--;               // remove 'lod'
5418       }
5419     }
5420   }
5421 
5422   // Check for 16 bit addresses and pack if true.
5423   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5424   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5425   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5426   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
5427       ST->hasFeature(AMDGPU::FeatureR128A16)) {
5428     IsA16 = true;
5429     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5430     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5431       SDValue AddrLo, AddrHi;
5432       // Push back extra arguments.
5433       if (i < DimIdx) {
5434         AddrLo = Op.getOperand(i);
5435       } else {
5436         AddrLo = Op.getOperand(i);
5437         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5438         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5439         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5440             ((NumGradients / 2) % 2 == 1 &&
5441             (i == DimIdx + (NumGradients / 2) - 1 ||
5442              i == DimIdx + NumGradients - 1))) {
5443           AddrHi = DAG.getUNDEF(MVT::f16);
5444         } else {
5445           AddrHi = Op.getOperand(i + 1);
5446           i++;
5447         }
5448         AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
5449                              {AddrLo, AddrHi});
5450         AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
5451       }
5452       VAddrs.push_back(AddrLo);
5453     }
5454   } else {
5455     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5456       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5457   }
5458 
5459   // If the register allocator cannot place the address registers contiguously
5460   // without introducing moves, then using the non-sequential address encoding
5461   // is always preferable, since it saves VALU instructions and is usually a
5462   // wash in terms of code size or even better.
5463   //
5464   // However, we currently have no way of hinting to the register allocator that
5465   // MIMG addresses should be placed contiguously when it is possible to do so,
5466   // so force non-NSA for the common 2-address case as a heuristic.
5467   //
5468   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5469   // allocation when possible.
5470   bool UseNSA =
5471       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5472   SDValue VAddr;
5473   if (!UseNSA)
5474     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5475 
5476   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5477   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5478   unsigned CtrlIdx; // Index of texfailctrl argument
5479   SDValue Unorm;
5480   if (!BaseOpcode->Sampler) {
5481     Unorm = True;
5482     CtrlIdx = AddrIdx + NumVAddrs + 1;
5483   } else {
5484     auto UnormConst =
5485         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5486 
5487     Unorm = UnormConst->getZExtValue() ? True : False;
5488     CtrlIdx = AddrIdx + NumVAddrs + 3;
5489   }
5490 
5491   SDValue TFE;
5492   SDValue LWE;
5493   SDValue TexFail = Op.getOperand(CtrlIdx);
5494   bool IsTexFail = false;
5495   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5496     return Op;
5497 
5498   if (IsTexFail) {
5499     if (!DMaskLanes) {
5500       // Expecting to get an error flag since TFC is on - and dmask is 0
5501       // Force dmask to be at least 1 otherwise the instruction will fail
5502       DMask = 0x1;
5503       DMaskLanes = 1;
5504       NumVDataDwords = 1;
5505     }
5506     NumVDataDwords += 1;
5507     AdjustRetType = true;
5508   }
5509 
5510   // Has something earlier tagged that the return type needs adjusting
5511   // This happens if the instruction is a load or has set TexFailCtrl flags
5512   if (AdjustRetType) {
5513     // NumVDataDwords reflects the true number of dwords required in the return type
5514     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5515       // This is a no-op load. This can be eliminated
5516       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5517       if (isa<MemSDNode>(Op))
5518         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5519       return Undef;
5520     }
5521 
5522     EVT NewVT = NumVDataDwords > 1 ?
5523                   EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
5524                 : MVT::f32;
5525 
5526     ResultTypes[0] = NewVT;
5527     if (ResultTypes.size() == 3) {
5528       // Original result was aggregate type used for TexFailCtrl results
5529       // The actual instruction returns as a vector type which has now been
5530       // created. Remove the aggregate result.
5531       ResultTypes.erase(&ResultTypes[1]);
5532     }
5533   }
5534 
5535   SDValue GLC;
5536   SDValue SLC;
5537   SDValue DLC;
5538   if (BaseOpcode->Atomic) {
5539     GLC = True; // TODO no-return optimization
5540     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5541                           IsGFX10 ? &DLC : nullptr))
5542       return Op;
5543   } else {
5544     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5545                           IsGFX10 ? &DLC : nullptr))
5546       return Op;
5547   }
5548 
5549   SmallVector<SDValue, 26> Ops;
5550   if (BaseOpcode->Store || BaseOpcode->Atomic)
5551     Ops.push_back(VData); // vdata
5552   if (UseNSA) {
5553     for (const SDValue &Addr : VAddrs)
5554       Ops.push_back(Addr);
5555   } else {
5556     Ops.push_back(VAddr);
5557   }
5558   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5559   if (BaseOpcode->Sampler)
5560     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5561   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5562   if (IsGFX10)
5563     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5564   Ops.push_back(Unorm);
5565   if (IsGFX10)
5566     Ops.push_back(DLC);
5567   Ops.push_back(GLC);
5568   Ops.push_back(SLC);
5569   Ops.push_back(IsA16 &&  // a16 or r128
5570                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5571   Ops.push_back(TFE); // tfe
5572   Ops.push_back(LWE); // lwe
5573   if (!IsGFX10)
5574     Ops.push_back(DimInfo->DA ? True : False);
5575   if (BaseOpcode->HasD16)
5576     Ops.push_back(IsD16 ? True : False);
5577   if (isa<MemSDNode>(Op))
5578     Ops.push_back(Op.getOperand(0)); // chain
5579 
5580   int NumVAddrDwords =
5581       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5582   int Opcode = -1;
5583 
5584   if (IsGFX10) {
5585     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5586                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5587                                           : AMDGPU::MIMGEncGfx10Default,
5588                                    NumVDataDwords, NumVAddrDwords);
5589   } else {
5590     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5591       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5592                                      NumVDataDwords, NumVAddrDwords);
5593     if (Opcode == -1)
5594       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5595                                      NumVDataDwords, NumVAddrDwords);
5596   }
5597   assert(Opcode != -1);
5598 
5599   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5600   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5601     MachineMemOperand *MemRef = MemOp->getMemOperand();
5602     DAG.setNodeMemRefs(NewNode, {MemRef});
5603   }
5604 
5605   if (BaseOpcode->AtomicX2) {
5606     SmallVector<SDValue, 1> Elt;
5607     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5608     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5609   } else if (!BaseOpcode->Store) {
5610     return constructRetValue(DAG, NewNode,
5611                              OrigResultTypes, IsTexFail,
5612                              Subtarget->hasUnpackedD16VMem(), IsD16,
5613                              DMaskLanes, NumVDataDwords, DL,
5614                              *DAG.getContext());
5615   }
5616 
5617   return SDValue(NewNode, 0);
5618 }
5619 
5620 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5621                                        SDValue Offset, SDValue GLC, SDValue DLC,
5622                                        SelectionDAG &DAG) const {
5623   MachineFunction &MF = DAG.getMachineFunction();
5624   MachineMemOperand *MMO = MF.getMachineMemOperand(
5625       MachinePointerInfo(),
5626       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5627           MachineMemOperand::MOInvariant,
5628       VT.getStoreSize(), VT.getStoreSize());
5629 
5630   if (!Offset->isDivergent()) {
5631     SDValue Ops[] = {
5632         Rsrc,
5633         Offset, // Offset
5634         GLC,
5635         DLC,
5636     };
5637     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5638                                    DAG.getVTList(VT), Ops, VT, MMO);
5639   }
5640 
5641   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5642   // assume that the buffer is unswizzled.
5643   SmallVector<SDValue, 4> Loads;
5644   unsigned NumLoads = 1;
5645   MVT LoadVT = VT.getSimpleVT();
5646   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5647   assert((LoadVT.getScalarType() == MVT::i32 ||
5648           LoadVT.getScalarType() == MVT::f32) &&
5649          isPowerOf2_32(NumElts));
5650 
5651   if (NumElts == 8 || NumElts == 16) {
5652     NumLoads = NumElts == 16 ? 4 : 2;
5653     LoadVT = MVT::v4i32;
5654   }
5655 
5656   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5657   unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5658   SDValue Ops[] = {
5659       DAG.getEntryNode(),                         // Chain
5660       Rsrc,                                       // rsrc
5661       DAG.getConstant(0, DL, MVT::i32),           // vindex
5662       {},                                         // voffset
5663       {},                                         // soffset
5664       {},                                         // offset
5665       DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5666       DAG.getConstant(0, DL, MVT::i1),            // idxen
5667   };
5668 
5669   // Use the alignment to ensure that the required offsets will fit into the
5670   // immediate offsets.
5671   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5672 
5673   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5674   for (unsigned i = 0; i < NumLoads; ++i) {
5675     Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32);
5676     Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
5677                                             Ops, LoadVT, MMO));
5678   }
5679 
5680   if (VT == MVT::v8i32 || VT == MVT::v16i32)
5681     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5682 
5683   return Loads[0];
5684 }
5685 
5686 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5687                                                   SelectionDAG &DAG) const {
5688   MachineFunction &MF = DAG.getMachineFunction();
5689   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5690 
5691   EVT VT = Op.getValueType();
5692   SDLoc DL(Op);
5693   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5694 
5695   // TODO: Should this propagate fast-math-flags?
5696 
5697   switch (IntrinsicID) {
5698   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5699     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5700       return emitNonHSAIntrinsicError(DAG, DL, VT);
5701     return getPreloadedValue(DAG, *MFI, VT,
5702                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5703   }
5704   case Intrinsic::amdgcn_dispatch_ptr:
5705   case Intrinsic::amdgcn_queue_ptr: {
5706     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5707       DiagnosticInfoUnsupported BadIntrin(
5708           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5709           DL.getDebugLoc());
5710       DAG.getContext()->diagnose(BadIntrin);
5711       return DAG.getUNDEF(VT);
5712     }
5713 
5714     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5715       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5716     return getPreloadedValue(DAG, *MFI, VT, RegID);
5717   }
5718   case Intrinsic::amdgcn_implicitarg_ptr: {
5719     if (MFI->isEntryFunction())
5720       return getImplicitArgPtr(DAG, DL);
5721     return getPreloadedValue(DAG, *MFI, VT,
5722                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5723   }
5724   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5725     return getPreloadedValue(DAG, *MFI, VT,
5726                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5727   }
5728   case Intrinsic::amdgcn_dispatch_id: {
5729     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5730   }
5731   case Intrinsic::amdgcn_rcp:
5732     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5733   case Intrinsic::amdgcn_rsq:
5734     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5735   case Intrinsic::amdgcn_rsq_legacy:
5736     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5737       return emitRemovedIntrinsicError(DAG, DL, VT);
5738 
5739     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5740   case Intrinsic::amdgcn_rcp_legacy:
5741     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5742       return emitRemovedIntrinsicError(DAG, DL, VT);
5743     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5744   case Intrinsic::amdgcn_rsq_clamp: {
5745     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5746       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5747 
5748     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5749     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5750     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5751 
5752     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5753     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5754                               DAG.getConstantFP(Max, DL, VT));
5755     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5756                        DAG.getConstantFP(Min, DL, VT));
5757   }
5758   case Intrinsic::r600_read_ngroups_x:
5759     if (Subtarget->isAmdHsaOS())
5760       return emitNonHSAIntrinsicError(DAG, DL, VT);
5761 
5762     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5763                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5764   case Intrinsic::r600_read_ngroups_y:
5765     if (Subtarget->isAmdHsaOS())
5766       return emitNonHSAIntrinsicError(DAG, DL, VT);
5767 
5768     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5769                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5770   case Intrinsic::r600_read_ngroups_z:
5771     if (Subtarget->isAmdHsaOS())
5772       return emitNonHSAIntrinsicError(DAG, DL, VT);
5773 
5774     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5775                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5776   case Intrinsic::r600_read_global_size_x:
5777     if (Subtarget->isAmdHsaOS())
5778       return emitNonHSAIntrinsicError(DAG, DL, VT);
5779 
5780     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5781                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5782   case Intrinsic::r600_read_global_size_y:
5783     if (Subtarget->isAmdHsaOS())
5784       return emitNonHSAIntrinsicError(DAG, DL, VT);
5785 
5786     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5787                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5788   case Intrinsic::r600_read_global_size_z:
5789     if (Subtarget->isAmdHsaOS())
5790       return emitNonHSAIntrinsicError(DAG, DL, VT);
5791 
5792     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5793                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5794   case Intrinsic::r600_read_local_size_x:
5795     if (Subtarget->isAmdHsaOS())
5796       return emitNonHSAIntrinsicError(DAG, DL, VT);
5797 
5798     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5799                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5800   case Intrinsic::r600_read_local_size_y:
5801     if (Subtarget->isAmdHsaOS())
5802       return emitNonHSAIntrinsicError(DAG, DL, VT);
5803 
5804     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5805                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5806   case Intrinsic::r600_read_local_size_z:
5807     if (Subtarget->isAmdHsaOS())
5808       return emitNonHSAIntrinsicError(DAG, DL, VT);
5809 
5810     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5811                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5812   case Intrinsic::amdgcn_workgroup_id_x:
5813   case Intrinsic::r600_read_tgid_x:
5814     return getPreloadedValue(DAG, *MFI, VT,
5815                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5816   case Intrinsic::amdgcn_workgroup_id_y:
5817   case Intrinsic::r600_read_tgid_y:
5818     return getPreloadedValue(DAG, *MFI, VT,
5819                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5820   case Intrinsic::amdgcn_workgroup_id_z:
5821   case Intrinsic::r600_read_tgid_z:
5822     return getPreloadedValue(DAG, *MFI, VT,
5823                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5824   case Intrinsic::amdgcn_workitem_id_x:
5825   case Intrinsic::r600_read_tidig_x:
5826     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5827                           SDLoc(DAG.getEntryNode()),
5828                           MFI->getArgInfo().WorkItemIDX);
5829   case Intrinsic::amdgcn_workitem_id_y:
5830   case Intrinsic::r600_read_tidig_y:
5831     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5832                           SDLoc(DAG.getEntryNode()),
5833                           MFI->getArgInfo().WorkItemIDY);
5834   case Intrinsic::amdgcn_workitem_id_z:
5835   case Intrinsic::r600_read_tidig_z:
5836     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5837                           SDLoc(DAG.getEntryNode()),
5838                           MFI->getArgInfo().WorkItemIDZ);
5839   case Intrinsic::amdgcn_wavefrontsize:
5840     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5841                            SDLoc(Op), MVT::i32);
5842   case Intrinsic::amdgcn_s_buffer_load: {
5843     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5844     SDValue GLC;
5845     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5846     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5847                           IsGFX10 ? &DLC : nullptr))
5848       return Op;
5849     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC,
5850                         DAG);
5851   }
5852   case Intrinsic::amdgcn_fdiv_fast:
5853     return lowerFDIV_FAST(Op, DAG);
5854   case Intrinsic::amdgcn_interp_mov: {
5855     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5856     SDValue Glue = M0.getValue(1);
5857     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
5858                        Op.getOperand(2), Op.getOperand(3), Glue);
5859   }
5860   case Intrinsic::amdgcn_interp_p1: {
5861     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5862     SDValue Glue = M0.getValue(1);
5863     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
5864                        Op.getOperand(2), Op.getOperand(3), Glue);
5865   }
5866   case Intrinsic::amdgcn_interp_p2: {
5867     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5868     SDValue Glue = SDValue(M0.getNode(), 1);
5869     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
5870                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
5871                        Glue);
5872   }
5873   case Intrinsic::amdgcn_interp_p1_f16: {
5874     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5875     SDValue Glue = M0.getValue(1);
5876     if (getSubtarget()->getLDSBankCount() == 16) {
5877       // 16 bank LDS
5878       SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
5879                               DAG.getConstant(2, DL, MVT::i32), // P0
5880                               Op.getOperand(2), // Attrchan
5881                               Op.getOperand(3), // Attr
5882                               Glue);
5883       SDValue Ops[] = {
5884         Op.getOperand(1), // Src0
5885         Op.getOperand(2), // Attrchan
5886         Op.getOperand(3), // Attr
5887         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5888         S, // Src2 - holds two f16 values selected by high
5889         DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5890         Op.getOperand(4), // high
5891         DAG.getConstant(0, DL, MVT::i1), // $clamp
5892         DAG.getConstant(0, DL, MVT::i32) // $omod
5893       };
5894       return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
5895     } else {
5896       // 32 bank LDS
5897       SDValue Ops[] = {
5898         Op.getOperand(1), // Src0
5899         Op.getOperand(2), // Attrchan
5900         Op.getOperand(3), // Attr
5901         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5902         Op.getOperand(4), // high
5903         DAG.getConstant(0, DL, MVT::i1), // $clamp
5904         DAG.getConstant(0, DL, MVT::i32), // $omod
5905         Glue
5906       };
5907       return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
5908     }
5909   }
5910   case Intrinsic::amdgcn_interp_p2_f16: {
5911     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6));
5912     SDValue Glue = SDValue(M0.getNode(), 1);
5913     SDValue Ops[] = {
5914       Op.getOperand(2), // Src0
5915       Op.getOperand(3), // Attrchan
5916       Op.getOperand(4), // Attr
5917       DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5918       Op.getOperand(1), // Src2
5919       DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5920       Op.getOperand(5), // high
5921       DAG.getConstant(0, DL, MVT::i1), // $clamp
5922       Glue
5923     };
5924     return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops);
5925   }
5926   case Intrinsic::amdgcn_sin:
5927     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5928 
5929   case Intrinsic::amdgcn_cos:
5930     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5931 
5932   case Intrinsic::amdgcn_mul_u24:
5933     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5934   case Intrinsic::amdgcn_mul_i24:
5935     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5936 
5937   case Intrinsic::amdgcn_log_clamp: {
5938     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5939       return SDValue();
5940 
5941     DiagnosticInfoUnsupported BadIntrin(
5942       MF.getFunction(), "intrinsic not supported on subtarget",
5943       DL.getDebugLoc());
5944       DAG.getContext()->diagnose(BadIntrin);
5945       return DAG.getUNDEF(VT);
5946   }
5947   case Intrinsic::amdgcn_ldexp:
5948     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5949                        Op.getOperand(1), Op.getOperand(2));
5950 
5951   case Intrinsic::amdgcn_fract:
5952     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5953 
5954   case Intrinsic::amdgcn_class:
5955     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5956                        Op.getOperand(1), Op.getOperand(2));
5957   case Intrinsic::amdgcn_div_fmas:
5958     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5959                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5960                        Op.getOperand(4));
5961 
5962   case Intrinsic::amdgcn_div_fixup:
5963     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5964                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5965 
5966   case Intrinsic::amdgcn_trig_preop:
5967     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5968                        Op.getOperand(1), Op.getOperand(2));
5969   case Intrinsic::amdgcn_div_scale: {
5970     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5971 
5972     // Translate to the operands expected by the machine instruction. The
5973     // first parameter must be the same as the first instruction.
5974     SDValue Numerator = Op.getOperand(1);
5975     SDValue Denominator = Op.getOperand(2);
5976 
5977     // Note this order is opposite of the machine instruction's operations,
5978     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5979     // intrinsic has the numerator as the first operand to match a normal
5980     // division operation.
5981 
5982     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5983 
5984     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5985                        Denominator, Numerator);
5986   }
5987   case Intrinsic::amdgcn_icmp: {
5988     // There is a Pat that handles this variant, so return it as-is.
5989     if (Op.getOperand(1).getValueType() == MVT::i1 &&
5990         Op.getConstantOperandVal(2) == 0 &&
5991         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
5992       return Op;
5993     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
5994   }
5995   case Intrinsic::amdgcn_fcmp: {
5996     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
5997   }
5998   case Intrinsic::amdgcn_fmed3:
5999     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6000                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6001   case Intrinsic::amdgcn_fdot2:
6002     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6003                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6004                        Op.getOperand(4));
6005   case Intrinsic::amdgcn_fmul_legacy:
6006     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6007                        Op.getOperand(1), Op.getOperand(2));
6008   case Intrinsic::amdgcn_sffbh:
6009     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6010   case Intrinsic::amdgcn_sbfe:
6011     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6012                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6013   case Intrinsic::amdgcn_ubfe:
6014     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6015                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6016   case Intrinsic::amdgcn_cvt_pkrtz:
6017   case Intrinsic::amdgcn_cvt_pknorm_i16:
6018   case Intrinsic::amdgcn_cvt_pknorm_u16:
6019   case Intrinsic::amdgcn_cvt_pk_i16:
6020   case Intrinsic::amdgcn_cvt_pk_u16: {
6021     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6022     EVT VT = Op.getValueType();
6023     unsigned Opcode;
6024 
6025     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6026       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6027     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6028       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6029     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6030       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6031     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6032       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6033     else
6034       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6035 
6036     if (isTypeLegal(VT))
6037       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6038 
6039     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6040                                Op.getOperand(1), Op.getOperand(2));
6041     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6042   }
6043   case Intrinsic::amdgcn_fmad_ftz:
6044     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6045                        Op.getOperand(2), Op.getOperand(3));
6046 
6047   case Intrinsic::amdgcn_if_break:
6048     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6049                                       Op->getOperand(1), Op->getOperand(2)), 0);
6050 
6051   case Intrinsic::amdgcn_groupstaticsize: {
6052     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6053     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6054       return Op;
6055 
6056     const Module *M = MF.getFunction().getParent();
6057     const GlobalValue *GV =
6058         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6059     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6060                                             SIInstrInfo::MO_ABS32_LO);
6061     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6062   }
6063   default:
6064     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6065             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6066       return lowerImage(Op, ImageDimIntr, DAG);
6067 
6068     return Op;
6069   }
6070 }
6071 
6072 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6073                                                  SelectionDAG &DAG) const {
6074   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6075   SDLoc DL(Op);
6076 
6077   switch (IntrID) {
6078   case Intrinsic::amdgcn_ds_ordered_add:
6079   case Intrinsic::amdgcn_ds_ordered_swap: {
6080     MemSDNode *M = cast<MemSDNode>(Op);
6081     SDValue Chain = M->getOperand(0);
6082     SDValue M0 = M->getOperand(2);
6083     SDValue Value = M->getOperand(3);
6084     unsigned IndexOperand = M->getConstantOperandVal(7);
6085     unsigned WaveRelease = M->getConstantOperandVal(8);
6086     unsigned WaveDone = M->getConstantOperandVal(9);
6087     unsigned ShaderType;
6088     unsigned Instruction;
6089 
6090     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6091     IndexOperand &= ~0x3f;
6092     unsigned CountDw = 0;
6093 
6094     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6095       CountDw = (IndexOperand >> 24) & 0xf;
6096       IndexOperand &= ~(0xf << 24);
6097 
6098       if (CountDw < 1 || CountDw > 4) {
6099         report_fatal_error(
6100             "ds_ordered_count: dword count must be between 1 and 4");
6101       }
6102     }
6103 
6104     if (IndexOperand)
6105       report_fatal_error("ds_ordered_count: bad index operand");
6106 
6107     switch (IntrID) {
6108     case Intrinsic::amdgcn_ds_ordered_add:
6109       Instruction = 0;
6110       break;
6111     case Intrinsic::amdgcn_ds_ordered_swap:
6112       Instruction = 1;
6113       break;
6114     }
6115 
6116     if (WaveDone && !WaveRelease)
6117       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6118 
6119     switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
6120     case CallingConv::AMDGPU_CS:
6121     case CallingConv::AMDGPU_KERNEL:
6122       ShaderType = 0;
6123       break;
6124     case CallingConv::AMDGPU_PS:
6125       ShaderType = 1;
6126       break;
6127     case CallingConv::AMDGPU_VS:
6128       ShaderType = 2;
6129       break;
6130     case CallingConv::AMDGPU_GS:
6131       ShaderType = 3;
6132       break;
6133     default:
6134       report_fatal_error("ds_ordered_count unsupported for this calling conv");
6135     }
6136 
6137     unsigned Offset0 = OrderedCountIndex << 2;
6138     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6139                        (Instruction << 4);
6140 
6141     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6142       Offset1 |= (CountDw - 1) << 6;
6143 
6144     unsigned Offset = Offset0 | (Offset1 << 8);
6145 
6146     SDValue Ops[] = {
6147       Chain,
6148       Value,
6149       DAG.getTargetConstant(Offset, DL, MVT::i16),
6150       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6151     };
6152     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6153                                    M->getVTList(), Ops, M->getMemoryVT(),
6154                                    M->getMemOperand());
6155   }
6156   case Intrinsic::amdgcn_ds_fadd: {
6157     MemSDNode *M = cast<MemSDNode>(Op);
6158     unsigned Opc;
6159     switch (IntrID) {
6160     case Intrinsic::amdgcn_ds_fadd:
6161       Opc = ISD::ATOMIC_LOAD_FADD;
6162       break;
6163     }
6164 
6165     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6166                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6167                          M->getMemOperand());
6168   }
6169   case Intrinsic::amdgcn_atomic_inc:
6170   case Intrinsic::amdgcn_atomic_dec:
6171   case Intrinsic::amdgcn_ds_fmin:
6172   case Intrinsic::amdgcn_ds_fmax: {
6173     MemSDNode *M = cast<MemSDNode>(Op);
6174     unsigned Opc;
6175     switch (IntrID) {
6176     case Intrinsic::amdgcn_atomic_inc:
6177       Opc = AMDGPUISD::ATOMIC_INC;
6178       break;
6179     case Intrinsic::amdgcn_atomic_dec:
6180       Opc = AMDGPUISD::ATOMIC_DEC;
6181       break;
6182     case Intrinsic::amdgcn_ds_fmin:
6183       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6184       break;
6185     case Intrinsic::amdgcn_ds_fmax:
6186       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6187       break;
6188     default:
6189       llvm_unreachable("Unknown intrinsic!");
6190     }
6191     SDValue Ops[] = {
6192       M->getOperand(0), // Chain
6193       M->getOperand(2), // Ptr
6194       M->getOperand(3)  // Value
6195     };
6196 
6197     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6198                                    M->getMemoryVT(), M->getMemOperand());
6199   }
6200   case Intrinsic::amdgcn_buffer_load:
6201   case Intrinsic::amdgcn_buffer_load_format: {
6202     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6203     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6204     unsigned IdxEn = 1;
6205     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6206       IdxEn = Idx->getZExtValue() != 0;
6207     SDValue Ops[] = {
6208       Op.getOperand(0), // Chain
6209       Op.getOperand(2), // rsrc
6210       Op.getOperand(3), // vindex
6211       SDValue(),        // voffset -- will be set by setBufferOffsets
6212       SDValue(),        // soffset -- will be set by setBufferOffsets
6213       SDValue(),        // offset -- will be set by setBufferOffsets
6214       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6215       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6216     };
6217 
6218     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6219     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6220         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6221 
6222     EVT VT = Op.getValueType();
6223     EVT IntVT = VT.changeTypeToInteger();
6224     auto *M = cast<MemSDNode>(Op);
6225     EVT LoadVT = Op.getValueType();
6226 
6227     if (LoadVT.getScalarType() == MVT::f16)
6228       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6229                                  M, DAG, Ops);
6230 
6231     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6232     if (LoadVT.getScalarType() == MVT::i8 ||
6233         LoadVT.getScalarType() == MVT::i16)
6234       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6235 
6236     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6237                                M->getMemOperand(), DAG);
6238   }
6239   case Intrinsic::amdgcn_raw_buffer_load:
6240   case Intrinsic::amdgcn_raw_buffer_load_format: {
6241     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6242 
6243     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6244     SDValue Ops[] = {
6245       Op.getOperand(0), // Chain
6246       Op.getOperand(2), // rsrc
6247       DAG.getConstant(0, DL, MVT::i32), // vindex
6248       Offsets.first,    // voffset
6249       Op.getOperand(4), // soffset
6250       Offsets.second,   // offset
6251       Op.getOperand(5), // cachepolicy
6252       DAG.getConstant(0, DL, MVT::i1), // idxen
6253     };
6254 
6255     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6256   }
6257   case Intrinsic::amdgcn_struct_buffer_load:
6258   case Intrinsic::amdgcn_struct_buffer_load_format: {
6259     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6260 
6261     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6262     SDValue Ops[] = {
6263       Op.getOperand(0), // Chain
6264       Op.getOperand(2), // rsrc
6265       Op.getOperand(3), // vindex
6266       Offsets.first,    // voffset
6267       Op.getOperand(5), // soffset
6268       Offsets.second,   // offset
6269       Op.getOperand(6), // cachepolicy
6270       DAG.getConstant(1, DL, MVT::i1), // idxen
6271     };
6272 
6273     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6274   }
6275   case Intrinsic::amdgcn_tbuffer_load: {
6276     MemSDNode *M = cast<MemSDNode>(Op);
6277     EVT LoadVT = Op.getValueType();
6278 
6279     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6280     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6281     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6282     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6283     unsigned IdxEn = 1;
6284     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6285       IdxEn = Idx->getZExtValue() != 0;
6286     SDValue Ops[] = {
6287       Op.getOperand(0),  // Chain
6288       Op.getOperand(2),  // rsrc
6289       Op.getOperand(3),  // vindex
6290       Op.getOperand(4),  // voffset
6291       Op.getOperand(5),  // soffset
6292       Op.getOperand(6),  // offset
6293       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6294       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6295       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6296     };
6297 
6298     if (LoadVT.getScalarType() == MVT::f16)
6299       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6300                                  M, DAG, Ops);
6301     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6302                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6303                                DAG);
6304   }
6305   case Intrinsic::amdgcn_raw_tbuffer_load: {
6306     MemSDNode *M = cast<MemSDNode>(Op);
6307     EVT LoadVT = Op.getValueType();
6308     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6309 
6310     SDValue Ops[] = {
6311       Op.getOperand(0),  // Chain
6312       Op.getOperand(2),  // rsrc
6313       DAG.getConstant(0, DL, MVT::i32), // vindex
6314       Offsets.first,     // voffset
6315       Op.getOperand(4),  // soffset
6316       Offsets.second,    // offset
6317       Op.getOperand(5),  // format
6318       Op.getOperand(6),  // cachepolicy
6319       DAG.getConstant(0, DL, MVT::i1), // idxen
6320     };
6321 
6322     if (LoadVT.getScalarType() == MVT::f16)
6323       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6324                                  M, DAG, Ops);
6325     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6326                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6327                                DAG);
6328   }
6329   case Intrinsic::amdgcn_struct_tbuffer_load: {
6330     MemSDNode *M = cast<MemSDNode>(Op);
6331     EVT LoadVT = Op.getValueType();
6332     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6333 
6334     SDValue Ops[] = {
6335       Op.getOperand(0),  // Chain
6336       Op.getOperand(2),  // rsrc
6337       Op.getOperand(3),  // vindex
6338       Offsets.first,     // voffset
6339       Op.getOperand(5),  // soffset
6340       Offsets.second,    // offset
6341       Op.getOperand(6),  // format
6342       Op.getOperand(7),  // cachepolicy
6343       DAG.getConstant(1, DL, MVT::i1), // idxen
6344     };
6345 
6346     if (LoadVT.getScalarType() == MVT::f16)
6347       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6348                                  M, DAG, Ops);
6349     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6350                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6351                                DAG);
6352   }
6353   case Intrinsic::amdgcn_buffer_atomic_swap:
6354   case Intrinsic::amdgcn_buffer_atomic_add:
6355   case Intrinsic::amdgcn_buffer_atomic_sub:
6356   case Intrinsic::amdgcn_buffer_atomic_smin:
6357   case Intrinsic::amdgcn_buffer_atomic_umin:
6358   case Intrinsic::amdgcn_buffer_atomic_smax:
6359   case Intrinsic::amdgcn_buffer_atomic_umax:
6360   case Intrinsic::amdgcn_buffer_atomic_and:
6361   case Intrinsic::amdgcn_buffer_atomic_or:
6362   case Intrinsic::amdgcn_buffer_atomic_xor: {
6363     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6364     unsigned IdxEn = 1;
6365     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6366       IdxEn = Idx->getZExtValue() != 0;
6367     SDValue Ops[] = {
6368       Op.getOperand(0), // Chain
6369       Op.getOperand(2), // vdata
6370       Op.getOperand(3), // rsrc
6371       Op.getOperand(4), // vindex
6372       SDValue(),        // voffset -- will be set by setBufferOffsets
6373       SDValue(),        // soffset -- will be set by setBufferOffsets
6374       SDValue(),        // offset -- will be set by setBufferOffsets
6375       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6376       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6377     };
6378     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6379     EVT VT = Op.getValueType();
6380 
6381     auto *M = cast<MemSDNode>(Op);
6382     unsigned Opcode = 0;
6383 
6384     switch (IntrID) {
6385     case Intrinsic::amdgcn_buffer_atomic_swap:
6386       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6387       break;
6388     case Intrinsic::amdgcn_buffer_atomic_add:
6389       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6390       break;
6391     case Intrinsic::amdgcn_buffer_atomic_sub:
6392       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6393       break;
6394     case Intrinsic::amdgcn_buffer_atomic_smin:
6395       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6396       break;
6397     case Intrinsic::amdgcn_buffer_atomic_umin:
6398       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6399       break;
6400     case Intrinsic::amdgcn_buffer_atomic_smax:
6401       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6402       break;
6403     case Intrinsic::amdgcn_buffer_atomic_umax:
6404       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6405       break;
6406     case Intrinsic::amdgcn_buffer_atomic_and:
6407       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6408       break;
6409     case Intrinsic::amdgcn_buffer_atomic_or:
6410       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6411       break;
6412     case Intrinsic::amdgcn_buffer_atomic_xor:
6413       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6414       break;
6415     default:
6416       llvm_unreachable("unhandled atomic opcode");
6417     }
6418 
6419     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6420                                    M->getMemOperand());
6421   }
6422   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6423   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6424   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6425   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6426   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6427   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6428   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6429   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6430   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6431   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6432   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6433   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6434     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6435     SDValue Ops[] = {
6436       Op.getOperand(0), // Chain
6437       Op.getOperand(2), // vdata
6438       Op.getOperand(3), // rsrc
6439       DAG.getConstant(0, DL, MVT::i32), // vindex
6440       Offsets.first,    // voffset
6441       Op.getOperand(5), // soffset
6442       Offsets.second,   // offset
6443       Op.getOperand(6), // cachepolicy
6444       DAG.getConstant(0, DL, MVT::i1), // idxen
6445     };
6446     EVT VT = Op.getValueType();
6447 
6448     auto *M = cast<MemSDNode>(Op);
6449     unsigned Opcode = 0;
6450 
6451     switch (IntrID) {
6452     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6453       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6454       break;
6455     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6456       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6457       break;
6458     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6459       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6460       break;
6461     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6462       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6463       break;
6464     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6465       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6466       break;
6467     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6468       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6469       break;
6470     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6471       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6472       break;
6473     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6474       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6475       break;
6476     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6477       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6478       break;
6479     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6480       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6481       break;
6482     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6483       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6484       break;
6485     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6486       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6487       break;
6488     default:
6489       llvm_unreachable("unhandled atomic opcode");
6490     }
6491 
6492     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6493                                    M->getMemOperand());
6494   }
6495   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6496   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6497   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6498   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6499   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6500   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6501   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6502   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6503   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6504   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6505   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6506   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6507     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6508     SDValue Ops[] = {
6509       Op.getOperand(0), // Chain
6510       Op.getOperand(2), // vdata
6511       Op.getOperand(3), // rsrc
6512       Op.getOperand(4), // vindex
6513       Offsets.first,    // voffset
6514       Op.getOperand(6), // soffset
6515       Offsets.second,   // offset
6516       Op.getOperand(7), // cachepolicy
6517       DAG.getConstant(1, DL, MVT::i1), // idxen
6518     };
6519     EVT VT = Op.getValueType();
6520 
6521     auto *M = cast<MemSDNode>(Op);
6522     unsigned Opcode = 0;
6523 
6524     switch (IntrID) {
6525     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6526       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6527       break;
6528     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6529       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6530       break;
6531     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6532       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6533       break;
6534     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6535       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6536       break;
6537     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6538       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6539       break;
6540     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6541       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6542       break;
6543     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6544       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6545       break;
6546     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6547       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6548       break;
6549     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6550       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6551       break;
6552     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6553       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6554       break;
6555     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6556       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6557       break;
6558     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6559       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6560       break;
6561     default:
6562       llvm_unreachable("unhandled atomic opcode");
6563     }
6564 
6565     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6566                                    M->getMemOperand());
6567   }
6568   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6569     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6570     unsigned IdxEn = 1;
6571     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6572       IdxEn = Idx->getZExtValue() != 0;
6573     SDValue Ops[] = {
6574       Op.getOperand(0), // Chain
6575       Op.getOperand(2), // src
6576       Op.getOperand(3), // cmp
6577       Op.getOperand(4), // rsrc
6578       Op.getOperand(5), // vindex
6579       SDValue(),        // voffset -- will be set by setBufferOffsets
6580       SDValue(),        // soffset -- will be set by setBufferOffsets
6581       SDValue(),        // offset -- will be set by setBufferOffsets
6582       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6583       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6584     };
6585     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6586     EVT VT = Op.getValueType();
6587     auto *M = cast<MemSDNode>(Op);
6588 
6589     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6590                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6591   }
6592   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6593     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6594     SDValue Ops[] = {
6595       Op.getOperand(0), // Chain
6596       Op.getOperand(2), // src
6597       Op.getOperand(3), // cmp
6598       Op.getOperand(4), // rsrc
6599       DAG.getConstant(0, DL, MVT::i32), // vindex
6600       Offsets.first,    // voffset
6601       Op.getOperand(6), // soffset
6602       Offsets.second,   // offset
6603       Op.getOperand(7), // cachepolicy
6604       DAG.getConstant(0, DL, MVT::i1), // idxen
6605     };
6606     EVT VT = Op.getValueType();
6607     auto *M = cast<MemSDNode>(Op);
6608 
6609     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6610                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6611   }
6612   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6613     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6614     SDValue Ops[] = {
6615       Op.getOperand(0), // Chain
6616       Op.getOperand(2), // src
6617       Op.getOperand(3), // cmp
6618       Op.getOperand(4), // rsrc
6619       Op.getOperand(5), // vindex
6620       Offsets.first,    // voffset
6621       Op.getOperand(7), // soffset
6622       Offsets.second,   // offset
6623       Op.getOperand(8), // cachepolicy
6624       DAG.getConstant(1, DL, MVT::i1), // idxen
6625     };
6626     EVT VT = Op.getValueType();
6627     auto *M = cast<MemSDNode>(Op);
6628 
6629     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6630                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6631   }
6632 
6633   default:
6634     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6635             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6636       return lowerImage(Op, ImageDimIntr, DAG);
6637 
6638     return SDValue();
6639   }
6640 }
6641 
6642 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6643 // dwordx4 if on SI.
6644 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6645                                               SDVTList VTList,
6646                                               ArrayRef<SDValue> Ops, EVT MemVT,
6647                                               MachineMemOperand *MMO,
6648                                               SelectionDAG &DAG) const {
6649   EVT VT = VTList.VTs[0];
6650   EVT WidenedVT = VT;
6651   EVT WidenedMemVT = MemVT;
6652   if (!Subtarget->hasDwordx3LoadStores() &&
6653       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6654     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6655                                  WidenedVT.getVectorElementType(), 4);
6656     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6657                                     WidenedMemVT.getVectorElementType(), 4);
6658     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6659   }
6660 
6661   assert(VTList.NumVTs == 2);
6662   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6663 
6664   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6665                                        WidenedMemVT, MMO);
6666   if (WidenedVT != VT) {
6667     auto Extract = DAG.getNode(
6668         ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6669         DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
6670     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6671   }
6672   return NewOp;
6673 }
6674 
6675 SDValue SITargetLowering::handleD16VData(SDValue VData,
6676                                          SelectionDAG &DAG) const {
6677   EVT StoreVT = VData.getValueType();
6678 
6679   // No change for f16 and legal vector D16 types.
6680   if (!StoreVT.isVector())
6681     return VData;
6682 
6683   SDLoc DL(VData);
6684   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6685 
6686   if (Subtarget->hasUnpackedD16VMem()) {
6687     // We need to unpack the packed data to store.
6688     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6689     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6690 
6691     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6692                                         StoreVT.getVectorNumElements());
6693     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6694     return DAG.UnrollVectorOp(ZExt.getNode());
6695   }
6696 
6697   assert(isTypeLegal(StoreVT));
6698   return VData;
6699 }
6700 
6701 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6702                                               SelectionDAG &DAG) const {
6703   SDLoc DL(Op);
6704   SDValue Chain = Op.getOperand(0);
6705   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6706   MachineFunction &MF = DAG.getMachineFunction();
6707 
6708   switch (IntrinsicID) {
6709   case Intrinsic::amdgcn_exp: {
6710     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6711     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6712     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
6713     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
6714 
6715     const SDValue Ops[] = {
6716       Chain,
6717       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6718       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6719       Op.getOperand(4), // src0
6720       Op.getOperand(5), // src1
6721       Op.getOperand(6), // src2
6722       Op.getOperand(7), // src3
6723       DAG.getTargetConstant(0, DL, MVT::i1), // compr
6724       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6725     };
6726 
6727     unsigned Opc = Done->isNullValue() ?
6728       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6729     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6730   }
6731   case Intrinsic::amdgcn_exp_compr: {
6732     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6733     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6734     SDValue Src0 = Op.getOperand(4);
6735     SDValue Src1 = Op.getOperand(5);
6736     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6737     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
6738 
6739     SDValue Undef = DAG.getUNDEF(MVT::f32);
6740     const SDValue Ops[] = {
6741       Chain,
6742       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6743       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6744       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
6745       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
6746       Undef, // src2
6747       Undef, // src3
6748       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6749       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6750     };
6751 
6752     unsigned Opc = Done->isNullValue() ?
6753       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6754     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6755   }
6756   case Intrinsic::amdgcn_init_exec: {
6757     return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
6758                        Op.getOperand(2));
6759   }
6760   case Intrinsic::amdgcn_init_exec_from_input: {
6761     return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
6762                        Op.getOperand(2), Op.getOperand(3));
6763   }
6764   case Intrinsic::amdgcn_s_barrier: {
6765     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6766       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6767       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6768       if (WGSize <= ST.getWavefrontSize())
6769         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6770                                           Op.getOperand(0)), 0);
6771     }
6772     return SDValue();
6773   };
6774   case Intrinsic::amdgcn_tbuffer_store: {
6775     SDValue VData = Op.getOperand(2);
6776     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6777     if (IsD16)
6778       VData = handleD16VData(VData, DAG);
6779     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6780     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6781     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6782     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6783     unsigned IdxEn = 1;
6784     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6785       IdxEn = Idx->getZExtValue() != 0;
6786     SDValue Ops[] = {
6787       Chain,
6788       VData,             // vdata
6789       Op.getOperand(3),  // rsrc
6790       Op.getOperand(4),  // vindex
6791       Op.getOperand(5),  // voffset
6792       Op.getOperand(6),  // soffset
6793       Op.getOperand(7),  // offset
6794       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6795       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6796       DAG.getConstant(IdxEn, DL, MVT::i1), // idexen
6797     };
6798     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6799                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6800     MemSDNode *M = cast<MemSDNode>(Op);
6801     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6802                                    M->getMemoryVT(), M->getMemOperand());
6803   }
6804 
6805   case Intrinsic::amdgcn_struct_tbuffer_store: {
6806     SDValue VData = Op.getOperand(2);
6807     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6808     if (IsD16)
6809       VData = handleD16VData(VData, DAG);
6810     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6811     SDValue Ops[] = {
6812       Chain,
6813       VData,             // vdata
6814       Op.getOperand(3),  // rsrc
6815       Op.getOperand(4),  // vindex
6816       Offsets.first,     // voffset
6817       Op.getOperand(6),  // soffset
6818       Offsets.second,    // offset
6819       Op.getOperand(7),  // format
6820       Op.getOperand(8),  // cachepolicy
6821       DAG.getConstant(1, DL, MVT::i1), // idexen
6822     };
6823     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6824                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6825     MemSDNode *M = cast<MemSDNode>(Op);
6826     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6827                                    M->getMemoryVT(), M->getMemOperand());
6828   }
6829 
6830   case Intrinsic::amdgcn_raw_tbuffer_store: {
6831     SDValue VData = Op.getOperand(2);
6832     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6833     if (IsD16)
6834       VData = handleD16VData(VData, DAG);
6835     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6836     SDValue Ops[] = {
6837       Chain,
6838       VData,             // vdata
6839       Op.getOperand(3),  // rsrc
6840       DAG.getConstant(0, DL, MVT::i32), // vindex
6841       Offsets.first,     // voffset
6842       Op.getOperand(5),  // soffset
6843       Offsets.second,    // offset
6844       Op.getOperand(6),  // format
6845       Op.getOperand(7),  // cachepolicy
6846       DAG.getConstant(0, DL, MVT::i1), // idexen
6847     };
6848     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6849                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6850     MemSDNode *M = cast<MemSDNode>(Op);
6851     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6852                                    M->getMemoryVT(), M->getMemOperand());
6853   }
6854 
6855   case Intrinsic::amdgcn_buffer_store:
6856   case Intrinsic::amdgcn_buffer_store_format: {
6857     SDValue VData = Op.getOperand(2);
6858     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6859     if (IsD16)
6860       VData = handleD16VData(VData, DAG);
6861     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6862     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6863     unsigned IdxEn = 1;
6864     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6865       IdxEn = Idx->getZExtValue() != 0;
6866     SDValue Ops[] = {
6867       Chain,
6868       VData,
6869       Op.getOperand(3), // rsrc
6870       Op.getOperand(4), // vindex
6871       SDValue(), // voffset -- will be set by setBufferOffsets
6872       SDValue(), // soffset -- will be set by setBufferOffsets
6873       SDValue(), // offset -- will be set by setBufferOffsets
6874       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6875       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6876     };
6877     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6878     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6879                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6880     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6881     MemSDNode *M = cast<MemSDNode>(Op);
6882 
6883     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6884     EVT VDataType = VData.getValueType().getScalarType();
6885     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6886       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6887 
6888     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6889                                    M->getMemoryVT(), M->getMemOperand());
6890   }
6891 
6892   case Intrinsic::amdgcn_raw_buffer_store:
6893   case Intrinsic::amdgcn_raw_buffer_store_format: {
6894     const bool IsFormat =
6895         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
6896 
6897     SDValue VData = Op.getOperand(2);
6898     EVT VDataVT = VData.getValueType();
6899     EVT EltType = VDataVT.getScalarType();
6900     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6901     if (IsD16)
6902       VData = handleD16VData(VData, DAG);
6903 
6904     if (!isTypeLegal(VDataVT)) {
6905       VData =
6906           DAG.getNode(ISD::BITCAST, DL,
6907                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6908     }
6909 
6910     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6911     SDValue Ops[] = {
6912       Chain,
6913       VData,
6914       Op.getOperand(3), // rsrc
6915       DAG.getConstant(0, DL, MVT::i32), // vindex
6916       Offsets.first,    // voffset
6917       Op.getOperand(5), // soffset
6918       Offsets.second,   // offset
6919       Op.getOperand(6), // cachepolicy
6920       DAG.getConstant(0, DL, MVT::i1), // idxen
6921     };
6922     unsigned Opc =
6923         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
6924     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6925     MemSDNode *M = cast<MemSDNode>(Op);
6926 
6927     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6928     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6929       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
6930 
6931     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6932                                    M->getMemoryVT(), M->getMemOperand());
6933   }
6934 
6935   case Intrinsic::amdgcn_struct_buffer_store:
6936   case Intrinsic::amdgcn_struct_buffer_store_format: {
6937     const bool IsFormat =
6938         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
6939 
6940     SDValue VData = Op.getOperand(2);
6941     EVT VDataVT = VData.getValueType();
6942     EVT EltType = VDataVT.getScalarType();
6943     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6944 
6945     if (IsD16)
6946       VData = handleD16VData(VData, DAG);
6947 
6948     if (!isTypeLegal(VDataVT)) {
6949       VData =
6950           DAG.getNode(ISD::BITCAST, DL,
6951                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6952     }
6953 
6954     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6955     SDValue Ops[] = {
6956       Chain,
6957       VData,
6958       Op.getOperand(3), // rsrc
6959       Op.getOperand(4), // vindex
6960       Offsets.first,    // voffset
6961       Op.getOperand(6), // soffset
6962       Offsets.second,   // offset
6963       Op.getOperand(7), // cachepolicy
6964       DAG.getConstant(1, DL, MVT::i1), // idxen
6965     };
6966     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6967                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6968     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6969     MemSDNode *M = cast<MemSDNode>(Op);
6970 
6971     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6972     EVT VDataType = VData.getValueType().getScalarType();
6973     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6974       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6975 
6976     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6977                                    M->getMemoryVT(), M->getMemOperand());
6978   }
6979 
6980   case Intrinsic::amdgcn_buffer_atomic_fadd: {
6981     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6982     unsigned IdxEn = 1;
6983     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6984       IdxEn = Idx->getZExtValue() != 0;
6985     SDValue Ops[] = {
6986       Chain,
6987       Op.getOperand(2), // vdata
6988       Op.getOperand(3), // rsrc
6989       Op.getOperand(4), // vindex
6990       SDValue(),        // voffset -- will be set by setBufferOffsets
6991       SDValue(),        // soffset -- will be set by setBufferOffsets
6992       SDValue(),        // offset -- will be set by setBufferOffsets
6993       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6994       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6995     };
6996     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6997     EVT VT = Op.getOperand(2).getValueType();
6998 
6999     auto *M = cast<MemSDNode>(Op);
7000     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7001                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7002 
7003     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7004                                    M->getMemOperand());
7005   }
7006 
7007   case Intrinsic::amdgcn_global_atomic_fadd: {
7008     SDValue Ops[] = {
7009       Chain,
7010       Op.getOperand(2), // ptr
7011       Op.getOperand(3)  // vdata
7012     };
7013     EVT VT = Op.getOperand(3).getValueType();
7014 
7015     auto *M = cast<MemSDNode>(Op);
7016     unsigned Opcode = VT.isVector() ? AMDGPUISD::ATOMIC_PK_FADD
7017                                     : AMDGPUISD::ATOMIC_FADD;
7018 
7019     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7020                                    M->getMemOperand());
7021   }
7022 
7023   case Intrinsic::amdgcn_end_cf:
7024     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7025                                       Op->getOperand(2), Chain), 0);
7026 
7027   default: {
7028     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7029             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7030       return lowerImage(Op, ImageDimIntr, DAG);
7031 
7032     return Op;
7033   }
7034   }
7035 }
7036 
7037 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7038 // offset (the offset that is included in bounds checking and swizzling, to be
7039 // split between the instruction's voffset and immoffset fields) and soffset
7040 // (the offset that is excluded from bounds checking and swizzling, to go in
7041 // the instruction's soffset field).  This function takes the first kind of
7042 // offset and figures out how to split it between voffset and immoffset.
7043 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7044     SDValue Offset, SelectionDAG &DAG) const {
7045   SDLoc DL(Offset);
7046   const unsigned MaxImm = 4095;
7047   SDValue N0 = Offset;
7048   ConstantSDNode *C1 = nullptr;
7049 
7050   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7051     N0 = SDValue();
7052   else if (DAG.isBaseWithConstantOffset(N0)) {
7053     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7054     N0 = N0.getOperand(0);
7055   }
7056 
7057   if (C1) {
7058     unsigned ImmOffset = C1->getZExtValue();
7059     // If the immediate value is too big for the immoffset field, put the value
7060     // and -4096 into the immoffset field so that the value that is copied/added
7061     // for the voffset field is a multiple of 4096, and it stands more chance
7062     // of being CSEd with the copy/add for another similar load/store.
7063     // However, do not do that rounding down to a multiple of 4096 if that is a
7064     // negative number, as it appears to be illegal to have a negative offset
7065     // in the vgpr, even if adding the immediate offset makes it positive.
7066     unsigned Overflow = ImmOffset & ~MaxImm;
7067     ImmOffset -= Overflow;
7068     if ((int32_t)Overflow < 0) {
7069       Overflow += ImmOffset;
7070       ImmOffset = 0;
7071     }
7072     C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32));
7073     if (Overflow) {
7074       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7075       if (!N0)
7076         N0 = OverflowVal;
7077       else {
7078         SDValue Ops[] = { N0, OverflowVal };
7079         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7080       }
7081     }
7082   }
7083   if (!N0)
7084     N0 = DAG.getConstant(0, DL, MVT::i32);
7085   if (!C1)
7086     C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32));
7087   return {N0, SDValue(C1, 0)};
7088 }
7089 
7090 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7091 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7092 // pointed to by Offsets.
7093 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7094                                         SelectionDAG &DAG, SDValue *Offsets,
7095                                         unsigned Align) const {
7096   SDLoc DL(CombinedOffset);
7097   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7098     uint32_t Imm = C->getZExtValue();
7099     uint32_t SOffset, ImmOffset;
7100     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7101       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7102       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7103       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
7104       return;
7105     }
7106   }
7107   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7108     SDValue N0 = CombinedOffset.getOperand(0);
7109     SDValue N1 = CombinedOffset.getOperand(1);
7110     uint32_t SOffset, ImmOffset;
7111     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7112     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7113                                                 Subtarget, Align)) {
7114       Offsets[0] = N0;
7115       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7116       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
7117       return;
7118     }
7119   }
7120   Offsets[0] = CombinedOffset;
7121   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7122   Offsets[2] = DAG.getConstant(0, DL, MVT::i32);
7123 }
7124 
7125 // Handle 8 bit and 16 bit buffer loads
7126 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7127                                                      EVT LoadVT, SDLoc DL,
7128                                                      ArrayRef<SDValue> Ops,
7129                                                      MemSDNode *M) const {
7130   EVT IntVT = LoadVT.changeTypeToInteger();
7131   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7132          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7133 
7134   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7135   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7136                                                Ops, IntVT,
7137                                                M->getMemOperand());
7138   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7139   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7140 
7141   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7142 }
7143 
7144 // Handle 8 bit and 16 bit buffer stores
7145 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7146                                                       EVT VDataType, SDLoc DL,
7147                                                       SDValue Ops[],
7148                                                       MemSDNode *M) const {
7149   if (VDataType == MVT::f16)
7150     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7151 
7152   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7153   Ops[1] = BufferStoreExt;
7154   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7155                                  AMDGPUISD::BUFFER_STORE_SHORT;
7156   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7157   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7158                                      M->getMemOperand());
7159 }
7160 
7161 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7162                                  ISD::LoadExtType ExtType, SDValue Op,
7163                                  const SDLoc &SL, EVT VT) {
7164   if (VT.bitsLT(Op.getValueType()))
7165     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7166 
7167   switch (ExtType) {
7168   case ISD::SEXTLOAD:
7169     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7170   case ISD::ZEXTLOAD:
7171     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7172   case ISD::EXTLOAD:
7173     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7174   case ISD::NON_EXTLOAD:
7175     return Op;
7176   }
7177 
7178   llvm_unreachable("invalid ext type");
7179 }
7180 
7181 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7182   SelectionDAG &DAG = DCI.DAG;
7183   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7184     return SDValue();
7185 
7186   // FIXME: Constant loads should all be marked invariant.
7187   unsigned AS = Ld->getAddressSpace();
7188   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7189       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7190       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7191     return SDValue();
7192 
7193   // Don't do this early, since it may interfere with adjacent load merging for
7194   // illegal types. We can avoid losing alignment information for exotic types
7195   // pre-legalize.
7196   EVT MemVT = Ld->getMemoryVT();
7197   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7198       MemVT.getSizeInBits() >= 32)
7199     return SDValue();
7200 
7201   SDLoc SL(Ld);
7202 
7203   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7204          "unexpected vector extload");
7205 
7206   // TODO: Drop only high part of range.
7207   SDValue Ptr = Ld->getBasePtr();
7208   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7209                                 MVT::i32, SL, Ld->getChain(), Ptr,
7210                                 Ld->getOffset(),
7211                                 Ld->getPointerInfo(), MVT::i32,
7212                                 Ld->getAlignment(),
7213                                 Ld->getMemOperand()->getFlags(),
7214                                 Ld->getAAInfo(),
7215                                 nullptr); // Drop ranges
7216 
7217   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7218   if (MemVT.isFloatingPoint()) {
7219     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7220            "unexpected fp extload");
7221     TruncVT = MemVT.changeTypeToInteger();
7222   }
7223 
7224   SDValue Cvt = NewLoad;
7225   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7226     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7227                       DAG.getValueType(TruncVT));
7228   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7229              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7230     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7231   } else {
7232     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7233   }
7234 
7235   EVT VT = Ld->getValueType(0);
7236   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7237 
7238   DCI.AddToWorklist(Cvt.getNode());
7239 
7240   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7241   // the appropriate extension from the 32-bit load.
7242   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7243   DCI.AddToWorklist(Cvt.getNode());
7244 
7245   // Handle conversion back to floating point if necessary.
7246   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7247 
7248   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7249 }
7250 
7251 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7252   SDLoc DL(Op);
7253   LoadSDNode *Load = cast<LoadSDNode>(Op);
7254   ISD::LoadExtType ExtType = Load->getExtensionType();
7255   EVT MemVT = Load->getMemoryVT();
7256 
7257   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7258     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7259       return SDValue();
7260 
7261     // FIXME: Copied from PPC
7262     // First, load into 32 bits, then truncate to 1 bit.
7263 
7264     SDValue Chain = Load->getChain();
7265     SDValue BasePtr = Load->getBasePtr();
7266     MachineMemOperand *MMO = Load->getMemOperand();
7267 
7268     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7269 
7270     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7271                                    BasePtr, RealMemVT, MMO);
7272 
7273     if (!MemVT.isVector()) {
7274       SDValue Ops[] = {
7275         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7276         NewLD.getValue(1)
7277       };
7278 
7279       return DAG.getMergeValues(Ops, DL);
7280     }
7281 
7282     SmallVector<SDValue, 3> Elts;
7283     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7284       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7285                                 DAG.getConstant(I, DL, MVT::i32));
7286 
7287       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7288     }
7289 
7290     SDValue Ops[] = {
7291       DAG.getBuildVector(MemVT, DL, Elts),
7292       NewLD.getValue(1)
7293     };
7294 
7295     return DAG.getMergeValues(Ops, DL);
7296   }
7297 
7298   if (!MemVT.isVector())
7299     return SDValue();
7300 
7301   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7302          "Custom lowering for non-i32 vectors hasn't been implemented.");
7303 
7304   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
7305                           *Load->getMemOperand())) {
7306     SDValue Ops[2];
7307     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7308     return DAG.getMergeValues(Ops, DL);
7309   }
7310 
7311   unsigned Alignment = Load->getAlignment();
7312   unsigned AS = Load->getAddressSpace();
7313   if (Subtarget->hasLDSMisalignedBug() &&
7314       AS == AMDGPUAS::FLAT_ADDRESS &&
7315       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7316     return SplitVectorLoad(Op, DAG);
7317   }
7318 
7319   MachineFunction &MF = DAG.getMachineFunction();
7320   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7321   // If there is a possibilty that flat instruction access scratch memory
7322   // then we need to use the same legalization rules we use for private.
7323   if (AS == AMDGPUAS::FLAT_ADDRESS)
7324     AS = MFI->hasFlatScratchInit() ?
7325          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7326 
7327   unsigned NumElements = MemVT.getVectorNumElements();
7328 
7329   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7330       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7331     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7332       if (MemVT.isPow2VectorType())
7333         return SDValue();
7334       if (NumElements == 3)
7335         return WidenVectorLoad(Op, DAG);
7336       return SplitVectorLoad(Op, DAG);
7337     }
7338     // Non-uniform loads will be selected to MUBUF instructions, so they
7339     // have the same legalization requirements as global and private
7340     // loads.
7341     //
7342   }
7343 
7344   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7345       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7346       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7347     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7348         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7349         Alignment >= 4 && NumElements < 32) {
7350       if (MemVT.isPow2VectorType())
7351         return SDValue();
7352       if (NumElements == 3)
7353         return WidenVectorLoad(Op, DAG);
7354       return SplitVectorLoad(Op, DAG);
7355     }
7356     // Non-uniform loads will be selected to MUBUF instructions, so they
7357     // have the same legalization requirements as global and private
7358     // loads.
7359     //
7360   }
7361   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7362       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7363       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7364       AS == AMDGPUAS::FLAT_ADDRESS) {
7365     if (NumElements > 4)
7366       return SplitVectorLoad(Op, DAG);
7367     // v3 loads not supported on SI.
7368     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7369       return WidenVectorLoad(Op, DAG);
7370     // v3 and v4 loads are supported for private and global memory.
7371     return SDValue();
7372   }
7373   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7374     // Depending on the setting of the private_element_size field in the
7375     // resource descriptor, we can only make private accesses up to a certain
7376     // size.
7377     switch (Subtarget->getMaxPrivateElementSize()) {
7378     case 4:
7379       return scalarizeVectorLoad(Load, DAG);
7380     case 8:
7381       if (NumElements > 2)
7382         return SplitVectorLoad(Op, DAG);
7383       return SDValue();
7384     case 16:
7385       // Same as global/flat
7386       if (NumElements > 4)
7387         return SplitVectorLoad(Op, DAG);
7388       // v3 loads not supported on SI.
7389       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7390         return WidenVectorLoad(Op, DAG);
7391       return SDValue();
7392     default:
7393       llvm_unreachable("unsupported private_element_size");
7394     }
7395   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7396     // Use ds_read_b128 if possible.
7397     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7398         MemVT.getStoreSize() == 16)
7399       return SDValue();
7400 
7401     if (NumElements > 2)
7402       return SplitVectorLoad(Op, DAG);
7403 
7404     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7405     // address is negative, then the instruction is incorrectly treated as
7406     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7407     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7408     // load later in the SILoadStoreOptimizer.
7409     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7410         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7411         Load->getAlignment() < 8) {
7412       return SplitVectorLoad(Op, DAG);
7413     }
7414   }
7415   return SDValue();
7416 }
7417 
7418 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7419   EVT VT = Op.getValueType();
7420   assert(VT.getSizeInBits() == 64);
7421 
7422   SDLoc DL(Op);
7423   SDValue Cond = Op.getOperand(0);
7424 
7425   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7426   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7427 
7428   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7429   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7430 
7431   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7432   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7433 
7434   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7435 
7436   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7437   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7438 
7439   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7440 
7441   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7442   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7443 }
7444 
7445 // Catch division cases where we can use shortcuts with rcp and rsq
7446 // instructions.
7447 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7448                                               SelectionDAG &DAG) const {
7449   SDLoc SL(Op);
7450   SDValue LHS = Op.getOperand(0);
7451   SDValue RHS = Op.getOperand(1);
7452   EVT VT = Op.getValueType();
7453   const SDNodeFlags Flags = Op->getFlags();
7454   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
7455 
7456   if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
7457     return SDValue();
7458 
7459   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7460     if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
7461       if (CLHS->isExactlyValue(1.0)) {
7462         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7463         // the CI documentation has a worst case error of 1 ulp.
7464         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7465         // use it as long as we aren't trying to use denormals.
7466         //
7467         // v_rcp_f16 and v_rsq_f16 DO support denormals.
7468 
7469         // 1.0 / sqrt(x) -> rsq(x)
7470 
7471         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7472         // error seems really high at 2^29 ULP.
7473         if (RHS.getOpcode() == ISD::FSQRT)
7474           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7475 
7476         // 1.0 / x -> rcp(x)
7477         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7478       }
7479 
7480       // Same as for 1.0, but expand the sign out of the constant.
7481       if (CLHS->isExactlyValue(-1.0)) {
7482         // -1.0 / x -> rcp (fneg x)
7483         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7484         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7485       }
7486     }
7487   }
7488 
7489   if (Unsafe) {
7490     // Turn into multiply by the reciprocal.
7491     // x / y -> x * (1.0 / y)
7492     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7493     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7494   }
7495 
7496   return SDValue();
7497 }
7498 
7499 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7500                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7501   if (GlueChain->getNumValues() <= 1) {
7502     return DAG.getNode(Opcode, SL, VT, A, B);
7503   }
7504 
7505   assert(GlueChain->getNumValues() == 3);
7506 
7507   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7508   switch (Opcode) {
7509   default: llvm_unreachable("no chain equivalent for opcode");
7510   case ISD::FMUL:
7511     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7512     break;
7513   }
7514 
7515   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7516                      GlueChain.getValue(2));
7517 }
7518 
7519 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7520                            EVT VT, SDValue A, SDValue B, SDValue C,
7521                            SDValue GlueChain) {
7522   if (GlueChain->getNumValues() <= 1) {
7523     return DAG.getNode(Opcode, SL, VT, A, B, C);
7524   }
7525 
7526   assert(GlueChain->getNumValues() == 3);
7527 
7528   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7529   switch (Opcode) {
7530   default: llvm_unreachable("no chain equivalent for opcode");
7531   case ISD::FMA:
7532     Opcode = AMDGPUISD::FMA_W_CHAIN;
7533     break;
7534   }
7535 
7536   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7537                      GlueChain.getValue(2));
7538 }
7539 
7540 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7541   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7542     return FastLowered;
7543 
7544   SDLoc SL(Op);
7545   SDValue Src0 = Op.getOperand(0);
7546   SDValue Src1 = Op.getOperand(1);
7547 
7548   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7549   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7550 
7551   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7552   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7553 
7554   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7555   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7556 
7557   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7558 }
7559 
7560 // Faster 2.5 ULP division that does not support denormals.
7561 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7562   SDLoc SL(Op);
7563   SDValue LHS = Op.getOperand(1);
7564   SDValue RHS = Op.getOperand(2);
7565 
7566   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7567 
7568   const APFloat K0Val(BitsToFloat(0x6f800000));
7569   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7570 
7571   const APFloat K1Val(BitsToFloat(0x2f800000));
7572   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7573 
7574   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7575 
7576   EVT SetCCVT =
7577     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7578 
7579   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7580 
7581   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7582 
7583   // TODO: Should this propagate fast-math-flags?
7584   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7585 
7586   // rcp does not support denormals.
7587   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7588 
7589   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7590 
7591   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7592 }
7593 
7594 // Returns immediate value for setting the F32 denorm mode when using the
7595 // S_DENORM_MODE instruction.
7596 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7597                                           const SDLoc &SL, const GCNSubtarget *ST) {
7598   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7599   int DPDenormModeDefault = ST->hasFP64Denormals()
7600                                 ? FP_DENORM_FLUSH_NONE
7601                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7602 
7603   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7604   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7605 }
7606 
7607 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7608   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7609     return FastLowered;
7610 
7611   SDLoc SL(Op);
7612   SDValue LHS = Op.getOperand(0);
7613   SDValue RHS = Op.getOperand(1);
7614 
7615   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7616 
7617   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7618 
7619   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7620                                           RHS, RHS, LHS);
7621   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7622                                         LHS, RHS, LHS);
7623 
7624   // Denominator is scaled to not be denormal, so using rcp is ok.
7625   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7626                                   DenominatorScaled);
7627   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7628                                      DenominatorScaled);
7629 
7630   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7631                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7632                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7633   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7634 
7635   if (!Subtarget->hasFP32Denormals()) {
7636     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7637 
7638     SDValue EnableDenorm;
7639     if (Subtarget->hasDenormModeInst()) {
7640       const SDValue EnableDenormValue =
7641           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7642 
7643       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7644                                  DAG.getEntryNode(), EnableDenormValue);
7645     } else {
7646       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7647                                                         SL, MVT::i32);
7648       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7649                                  DAG.getEntryNode(), EnableDenormValue,
7650                                  BitField);
7651     }
7652 
7653     SDValue Ops[3] = {
7654       NegDivScale0,
7655       EnableDenorm.getValue(0),
7656       EnableDenorm.getValue(1)
7657     };
7658 
7659     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7660   }
7661 
7662   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7663                              ApproxRcp, One, NegDivScale0);
7664 
7665   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7666                              ApproxRcp, Fma0);
7667 
7668   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7669                            Fma1, Fma1);
7670 
7671   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7672                              NumeratorScaled, Mul);
7673 
7674   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7675 
7676   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7677                              NumeratorScaled, Fma3);
7678 
7679   if (!Subtarget->hasFP32Denormals()) {
7680 
7681     SDValue DisableDenorm;
7682     if (Subtarget->hasDenormModeInst()) {
7683       const SDValue DisableDenormValue =
7684           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7685 
7686       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7687                                   Fma4.getValue(1), DisableDenormValue,
7688                                   Fma4.getValue(2));
7689     } else {
7690       const SDValue DisableDenormValue =
7691           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7692 
7693       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7694                                   Fma4.getValue(1), DisableDenormValue,
7695                                   BitField, Fma4.getValue(2));
7696     }
7697 
7698     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7699                                       DisableDenorm, DAG.getRoot());
7700     DAG.setRoot(OutputChain);
7701   }
7702 
7703   SDValue Scale = NumeratorScaled.getValue(1);
7704   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7705                              Fma4, Fma1, Fma3, Scale);
7706 
7707   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7708 }
7709 
7710 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7711   if (DAG.getTarget().Options.UnsafeFPMath)
7712     return lowerFastUnsafeFDIV(Op, DAG);
7713 
7714   SDLoc SL(Op);
7715   SDValue X = Op.getOperand(0);
7716   SDValue Y = Op.getOperand(1);
7717 
7718   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7719 
7720   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7721 
7722   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7723 
7724   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7725 
7726   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7727 
7728   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7729 
7730   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7731 
7732   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7733 
7734   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7735 
7736   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7737   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7738 
7739   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7740                              NegDivScale0, Mul, DivScale1);
7741 
7742   SDValue Scale;
7743 
7744   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7745     // Workaround a hardware bug on SI where the condition output from div_scale
7746     // is not usable.
7747 
7748     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7749 
7750     // Figure out if the scale to use for div_fmas.
7751     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7752     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7753     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7754     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7755 
7756     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7757     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7758 
7759     SDValue Scale0Hi
7760       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7761     SDValue Scale1Hi
7762       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7763 
7764     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7765     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7766     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7767   } else {
7768     Scale = DivScale1.getValue(1);
7769   }
7770 
7771   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7772                              Fma4, Fma3, Mul, Scale);
7773 
7774   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7775 }
7776 
7777 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7778   EVT VT = Op.getValueType();
7779 
7780   if (VT == MVT::f32)
7781     return LowerFDIV32(Op, DAG);
7782 
7783   if (VT == MVT::f64)
7784     return LowerFDIV64(Op, DAG);
7785 
7786   if (VT == MVT::f16)
7787     return LowerFDIV16(Op, DAG);
7788 
7789   llvm_unreachable("Unexpected type for fdiv");
7790 }
7791 
7792 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7793   SDLoc DL(Op);
7794   StoreSDNode *Store = cast<StoreSDNode>(Op);
7795   EVT VT = Store->getMemoryVT();
7796 
7797   if (VT == MVT::i1) {
7798     return DAG.getTruncStore(Store->getChain(), DL,
7799        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7800        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7801   }
7802 
7803   assert(VT.isVector() &&
7804          Store->getValue().getValueType().getScalarType() == MVT::i32);
7805 
7806   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7807                           *Store->getMemOperand())) {
7808     return expandUnalignedStore(Store, DAG);
7809   }
7810 
7811   unsigned AS = Store->getAddressSpace();
7812   if (Subtarget->hasLDSMisalignedBug() &&
7813       AS == AMDGPUAS::FLAT_ADDRESS &&
7814       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7815     return SplitVectorStore(Op, DAG);
7816   }
7817 
7818   MachineFunction &MF = DAG.getMachineFunction();
7819   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7820   // If there is a possibilty that flat instruction access scratch memory
7821   // then we need to use the same legalization rules we use for private.
7822   if (AS == AMDGPUAS::FLAT_ADDRESS)
7823     AS = MFI->hasFlatScratchInit() ?
7824          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7825 
7826   unsigned NumElements = VT.getVectorNumElements();
7827   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7828       AS == AMDGPUAS::FLAT_ADDRESS) {
7829     if (NumElements > 4)
7830       return SplitVectorStore(Op, DAG);
7831     // v3 stores not supported on SI.
7832     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7833       return SplitVectorStore(Op, DAG);
7834     return SDValue();
7835   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7836     switch (Subtarget->getMaxPrivateElementSize()) {
7837     case 4:
7838       return scalarizeVectorStore(Store, DAG);
7839     case 8:
7840       if (NumElements > 2)
7841         return SplitVectorStore(Op, DAG);
7842       return SDValue();
7843     case 16:
7844       if (NumElements > 4 || NumElements == 3)
7845         return SplitVectorStore(Op, DAG);
7846       return SDValue();
7847     default:
7848       llvm_unreachable("unsupported private_element_size");
7849     }
7850   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7851     // Use ds_write_b128 if possible.
7852     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7853         VT.getStoreSize() == 16 && NumElements != 3)
7854       return SDValue();
7855 
7856     if (NumElements > 2)
7857       return SplitVectorStore(Op, DAG);
7858 
7859     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7860     // address is negative, then the instruction is incorrectly treated as
7861     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7862     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7863     // store later in the SILoadStoreOptimizer.
7864     if (!Subtarget->hasUsableDSOffset() &&
7865         NumElements == 2 && VT.getStoreSize() == 8 &&
7866         Store->getAlignment() < 8) {
7867       return SplitVectorStore(Op, DAG);
7868     }
7869 
7870     return SDValue();
7871   } else {
7872     llvm_unreachable("unhandled address space");
7873   }
7874 }
7875 
7876 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7877   SDLoc DL(Op);
7878   EVT VT = Op.getValueType();
7879   SDValue Arg = Op.getOperand(0);
7880   SDValue TrigVal;
7881 
7882   // TODO: Should this propagate fast-math-flags?
7883 
7884   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7885 
7886   if (Subtarget->hasTrigReducedRange()) {
7887     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7888     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7889   } else {
7890     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7891   }
7892 
7893   switch (Op.getOpcode()) {
7894   case ISD::FCOS:
7895     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7896   case ISD::FSIN:
7897     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7898   default:
7899     llvm_unreachable("Wrong trig opcode");
7900   }
7901 }
7902 
7903 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7904   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7905   assert(AtomicNode->isCompareAndSwap());
7906   unsigned AS = AtomicNode->getAddressSpace();
7907 
7908   // No custom lowering required for local address space
7909   if (!isFlatGlobalAddrSpace(AS))
7910     return Op;
7911 
7912   // Non-local address space requires custom lowering for atomic compare
7913   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7914   SDLoc DL(Op);
7915   SDValue ChainIn = Op.getOperand(0);
7916   SDValue Addr = Op.getOperand(1);
7917   SDValue Old = Op.getOperand(2);
7918   SDValue New = Op.getOperand(3);
7919   EVT VT = Op.getValueType();
7920   MVT SimpleVT = VT.getSimpleVT();
7921   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7922 
7923   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
7924   SDValue Ops[] = { ChainIn, Addr, NewOld };
7925 
7926   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7927                                  Ops, VT, AtomicNode->getMemOperand());
7928 }
7929 
7930 //===----------------------------------------------------------------------===//
7931 // Custom DAG optimizations
7932 //===----------------------------------------------------------------------===//
7933 
7934 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
7935                                                      DAGCombinerInfo &DCI) const {
7936   EVT VT = N->getValueType(0);
7937   EVT ScalarVT = VT.getScalarType();
7938   if (ScalarVT != MVT::f32)
7939     return SDValue();
7940 
7941   SelectionDAG &DAG = DCI.DAG;
7942   SDLoc DL(N);
7943 
7944   SDValue Src = N->getOperand(0);
7945   EVT SrcVT = Src.getValueType();
7946 
7947   // TODO: We could try to match extracting the higher bytes, which would be
7948   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7949   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7950   // about in practice.
7951   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
7952     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7953       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7954       DCI.AddToWorklist(Cvt.getNode());
7955       return Cvt;
7956     }
7957   }
7958 
7959   return SDValue();
7960 }
7961 
7962 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7963 
7964 // This is a variant of
7965 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7966 //
7967 // The normal DAG combiner will do this, but only if the add has one use since
7968 // that would increase the number of instructions.
7969 //
7970 // This prevents us from seeing a constant offset that can be folded into a
7971 // memory instruction's addressing mode. If we know the resulting add offset of
7972 // a pointer can be folded into an addressing offset, we can replace the pointer
7973 // operand with the add of new constant offset. This eliminates one of the uses,
7974 // and may allow the remaining use to also be simplified.
7975 //
7976 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7977                                                unsigned AddrSpace,
7978                                                EVT MemVT,
7979                                                DAGCombinerInfo &DCI) const {
7980   SDValue N0 = N->getOperand(0);
7981   SDValue N1 = N->getOperand(1);
7982 
7983   // We only do this to handle cases where it's profitable when there are
7984   // multiple uses of the add, so defer to the standard combine.
7985   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
7986       N0->hasOneUse())
7987     return SDValue();
7988 
7989   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
7990   if (!CN1)
7991     return SDValue();
7992 
7993   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7994   if (!CAdd)
7995     return SDValue();
7996 
7997   // If the resulting offset is too large, we can't fold it into the addressing
7998   // mode offset.
7999   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8000   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8001 
8002   AddrMode AM;
8003   AM.HasBaseReg = true;
8004   AM.BaseOffs = Offset.getSExtValue();
8005   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8006     return SDValue();
8007 
8008   SelectionDAG &DAG = DCI.DAG;
8009   SDLoc SL(N);
8010   EVT VT = N->getValueType(0);
8011 
8012   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8013   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8014 
8015   SDNodeFlags Flags;
8016   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8017                           (N0.getOpcode() == ISD::OR ||
8018                            N0->getFlags().hasNoUnsignedWrap()));
8019 
8020   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8021 }
8022 
8023 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8024                                                   DAGCombinerInfo &DCI) const {
8025   SDValue Ptr = N->getBasePtr();
8026   SelectionDAG &DAG = DCI.DAG;
8027   SDLoc SL(N);
8028 
8029   // TODO: We could also do this for multiplies.
8030   if (Ptr.getOpcode() == ISD::SHL) {
8031     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8032                                           N->getMemoryVT(), DCI);
8033     if (NewPtr) {
8034       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8035 
8036       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8037       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8038     }
8039   }
8040 
8041   return SDValue();
8042 }
8043 
8044 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8045   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8046          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8047          (Opc == ISD::XOR && Val == 0);
8048 }
8049 
8050 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8051 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8052 // integer combine opportunities since most 64-bit operations are decomposed
8053 // this way.  TODO: We won't want this for SALU especially if it is an inline
8054 // immediate.
8055 SDValue SITargetLowering::splitBinaryBitConstantOp(
8056   DAGCombinerInfo &DCI,
8057   const SDLoc &SL,
8058   unsigned Opc, SDValue LHS,
8059   const ConstantSDNode *CRHS) const {
8060   uint64_t Val = CRHS->getZExtValue();
8061   uint32_t ValLo = Lo_32(Val);
8062   uint32_t ValHi = Hi_32(Val);
8063   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8064 
8065     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8066          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8067         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8068     // If we need to materialize a 64-bit immediate, it will be split up later
8069     // anyway. Avoid creating the harder to understand 64-bit immediate
8070     // materialization.
8071     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8072   }
8073 
8074   return SDValue();
8075 }
8076 
8077 // Returns true if argument is a boolean value which is not serialized into
8078 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8079 static bool isBoolSGPR(SDValue V) {
8080   if (V.getValueType() != MVT::i1)
8081     return false;
8082   switch (V.getOpcode()) {
8083   default: break;
8084   case ISD::SETCC:
8085   case ISD::AND:
8086   case ISD::OR:
8087   case ISD::XOR:
8088   case AMDGPUISD::FP_CLASS:
8089     return true;
8090   }
8091   return false;
8092 }
8093 
8094 // If a constant has all zeroes or all ones within each byte return it.
8095 // Otherwise return 0.
8096 static uint32_t getConstantPermuteMask(uint32_t C) {
8097   // 0xff for any zero byte in the mask
8098   uint32_t ZeroByteMask = 0;
8099   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8100   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8101   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8102   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8103   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8104   if ((NonZeroByteMask & C) != NonZeroByteMask)
8105     return 0; // Partial bytes selected.
8106   return C;
8107 }
8108 
8109 // Check if a node selects whole bytes from its operand 0 starting at a byte
8110 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8111 // or -1 if not succeeded.
8112 // Note byte select encoding:
8113 // value 0-3 selects corresponding source byte;
8114 // value 0xc selects zero;
8115 // value 0xff selects 0xff.
8116 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8117   assert(V.getValueSizeInBits() == 32);
8118 
8119   if (V.getNumOperands() != 2)
8120     return ~0;
8121 
8122   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8123   if (!N1)
8124     return ~0;
8125 
8126   uint32_t C = N1->getZExtValue();
8127 
8128   switch (V.getOpcode()) {
8129   default:
8130     break;
8131   case ISD::AND:
8132     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8133       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8134     }
8135     break;
8136 
8137   case ISD::OR:
8138     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8139       return (0x03020100 & ~ConstMask) | ConstMask;
8140     }
8141     break;
8142 
8143   case ISD::SHL:
8144     if (C % 8)
8145       return ~0;
8146 
8147     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8148 
8149   case ISD::SRL:
8150     if (C % 8)
8151       return ~0;
8152 
8153     return uint32_t(0x0c0c0c0c03020100ull >> C);
8154   }
8155 
8156   return ~0;
8157 }
8158 
8159 SDValue SITargetLowering::performAndCombine(SDNode *N,
8160                                             DAGCombinerInfo &DCI) const {
8161   if (DCI.isBeforeLegalize())
8162     return SDValue();
8163 
8164   SelectionDAG &DAG = DCI.DAG;
8165   EVT VT = N->getValueType(0);
8166   SDValue LHS = N->getOperand(0);
8167   SDValue RHS = N->getOperand(1);
8168 
8169 
8170   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8171   if (VT == MVT::i64 && CRHS) {
8172     if (SDValue Split
8173         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8174       return Split;
8175   }
8176 
8177   if (CRHS && VT == MVT::i32) {
8178     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8179     // nb = number of trailing zeroes in mask
8180     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8181     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8182     uint64_t Mask = CRHS->getZExtValue();
8183     unsigned Bits = countPopulation(Mask);
8184     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8185         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8186       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8187         unsigned Shift = CShift->getZExtValue();
8188         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8189         unsigned Offset = NB + Shift;
8190         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8191           SDLoc SL(N);
8192           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8193                                     LHS->getOperand(0),
8194                                     DAG.getConstant(Offset, SL, MVT::i32),
8195                                     DAG.getConstant(Bits, SL, MVT::i32));
8196           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8197           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8198                                     DAG.getValueType(NarrowVT));
8199           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8200                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8201           return Shl;
8202         }
8203       }
8204     }
8205 
8206     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8207     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8208         isa<ConstantSDNode>(LHS.getOperand(2))) {
8209       uint32_t Sel = getConstantPermuteMask(Mask);
8210       if (!Sel)
8211         return SDValue();
8212 
8213       // Select 0xc for all zero bytes
8214       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8215       SDLoc DL(N);
8216       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8217                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8218     }
8219   }
8220 
8221   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8222   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8223   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8224     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8225     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8226 
8227     SDValue X = LHS.getOperand(0);
8228     SDValue Y = RHS.getOperand(0);
8229     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8230       return SDValue();
8231 
8232     if (LCC == ISD::SETO) {
8233       if (X != LHS.getOperand(1))
8234         return SDValue();
8235 
8236       if (RCC == ISD::SETUNE) {
8237         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8238         if (!C1 || !C1->isInfinity() || C1->isNegative())
8239           return SDValue();
8240 
8241         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8242                               SIInstrFlags::N_SUBNORMAL |
8243                               SIInstrFlags::N_ZERO |
8244                               SIInstrFlags::P_ZERO |
8245                               SIInstrFlags::P_SUBNORMAL |
8246                               SIInstrFlags::P_NORMAL;
8247 
8248         static_assert(((~(SIInstrFlags::S_NAN |
8249                           SIInstrFlags::Q_NAN |
8250                           SIInstrFlags::N_INFINITY |
8251                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8252                       "mask not equal");
8253 
8254         SDLoc DL(N);
8255         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8256                            X, DAG.getConstant(Mask, DL, MVT::i32));
8257       }
8258     }
8259   }
8260 
8261   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8262     std::swap(LHS, RHS);
8263 
8264   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8265       RHS.hasOneUse()) {
8266     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8267     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8268     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8269     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8270     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8271         (RHS.getOperand(0) == LHS.getOperand(0) &&
8272          LHS.getOperand(0) == LHS.getOperand(1))) {
8273       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8274       unsigned NewMask = LCC == ISD::SETO ?
8275         Mask->getZExtValue() & ~OrdMask :
8276         Mask->getZExtValue() & OrdMask;
8277 
8278       SDLoc DL(N);
8279       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8280                          DAG.getConstant(NewMask, DL, MVT::i32));
8281     }
8282   }
8283 
8284   if (VT == MVT::i32 &&
8285       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8286     // and x, (sext cc from i1) => select cc, x, 0
8287     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8288       std::swap(LHS, RHS);
8289     if (isBoolSGPR(RHS.getOperand(0)))
8290       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8291                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8292   }
8293 
8294   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8295   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8296   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8297       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8298     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8299     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8300     if (LHSMask != ~0u && RHSMask != ~0u) {
8301       // Canonicalize the expression in an attempt to have fewer unique masks
8302       // and therefore fewer registers used to hold the masks.
8303       if (LHSMask > RHSMask) {
8304         std::swap(LHSMask, RHSMask);
8305         std::swap(LHS, RHS);
8306       }
8307 
8308       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8309       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8310       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8311       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8312 
8313       // Check of we need to combine values from two sources within a byte.
8314       if (!(LHSUsedLanes & RHSUsedLanes) &&
8315           // If we select high and lower word keep it for SDWA.
8316           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8317           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8318         // Each byte in each mask is either selector mask 0-3, or has higher
8319         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8320         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8321         // mask which is not 0xff wins. By anding both masks we have a correct
8322         // result except that 0x0c shall be corrected to give 0x0c only.
8323         uint32_t Mask = LHSMask & RHSMask;
8324         for (unsigned I = 0; I < 32; I += 8) {
8325           uint32_t ByteSel = 0xff << I;
8326           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8327             Mask &= (0x0c << I) & 0xffffffff;
8328         }
8329 
8330         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8331         // or 0x0c.
8332         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8333         SDLoc DL(N);
8334 
8335         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8336                            LHS.getOperand(0), RHS.getOperand(0),
8337                            DAG.getConstant(Sel, DL, MVT::i32));
8338       }
8339     }
8340   }
8341 
8342   return SDValue();
8343 }
8344 
8345 SDValue SITargetLowering::performOrCombine(SDNode *N,
8346                                            DAGCombinerInfo &DCI) const {
8347   SelectionDAG &DAG = DCI.DAG;
8348   SDValue LHS = N->getOperand(0);
8349   SDValue RHS = N->getOperand(1);
8350 
8351   EVT VT = N->getValueType(0);
8352   if (VT == MVT::i1) {
8353     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8354     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8355         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8356       SDValue Src = LHS.getOperand(0);
8357       if (Src != RHS.getOperand(0))
8358         return SDValue();
8359 
8360       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8361       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8362       if (!CLHS || !CRHS)
8363         return SDValue();
8364 
8365       // Only 10 bits are used.
8366       static const uint32_t MaxMask = 0x3ff;
8367 
8368       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8369       SDLoc DL(N);
8370       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8371                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8372     }
8373 
8374     return SDValue();
8375   }
8376 
8377   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8378   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8379       LHS.getOpcode() == AMDGPUISD::PERM &&
8380       isa<ConstantSDNode>(LHS.getOperand(2))) {
8381     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8382     if (!Sel)
8383       return SDValue();
8384 
8385     Sel |= LHS.getConstantOperandVal(2);
8386     SDLoc DL(N);
8387     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8388                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8389   }
8390 
8391   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8392   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8393   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8394       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8395     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8396     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8397     if (LHSMask != ~0u && RHSMask != ~0u) {
8398       // Canonicalize the expression in an attempt to have fewer unique masks
8399       // and therefore fewer registers used to hold the masks.
8400       if (LHSMask > RHSMask) {
8401         std::swap(LHSMask, RHSMask);
8402         std::swap(LHS, RHS);
8403       }
8404 
8405       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8406       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8407       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8408       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8409 
8410       // Check of we need to combine values from two sources within a byte.
8411       if (!(LHSUsedLanes & RHSUsedLanes) &&
8412           // If we select high and lower word keep it for SDWA.
8413           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8414           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8415         // Kill zero bytes selected by other mask. Zero value is 0xc.
8416         LHSMask &= ~RHSUsedLanes;
8417         RHSMask &= ~LHSUsedLanes;
8418         // Add 4 to each active LHS lane
8419         LHSMask |= LHSUsedLanes & 0x04040404;
8420         // Combine masks
8421         uint32_t Sel = LHSMask | RHSMask;
8422         SDLoc DL(N);
8423 
8424         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8425                            LHS.getOperand(0), RHS.getOperand(0),
8426                            DAG.getConstant(Sel, DL, MVT::i32));
8427       }
8428     }
8429   }
8430 
8431   if (VT != MVT::i64)
8432     return SDValue();
8433 
8434   // TODO: This could be a generic combine with a predicate for extracting the
8435   // high half of an integer being free.
8436 
8437   // (or i64:x, (zero_extend i32:y)) ->
8438   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8439   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8440       RHS.getOpcode() != ISD::ZERO_EXTEND)
8441     std::swap(LHS, RHS);
8442 
8443   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8444     SDValue ExtSrc = RHS.getOperand(0);
8445     EVT SrcVT = ExtSrc.getValueType();
8446     if (SrcVT == MVT::i32) {
8447       SDLoc SL(N);
8448       SDValue LowLHS, HiBits;
8449       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8450       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8451 
8452       DCI.AddToWorklist(LowOr.getNode());
8453       DCI.AddToWorklist(HiBits.getNode());
8454 
8455       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8456                                 LowOr, HiBits);
8457       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8458     }
8459   }
8460 
8461   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8462   if (CRHS) {
8463     if (SDValue Split
8464           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8465       return Split;
8466   }
8467 
8468   return SDValue();
8469 }
8470 
8471 SDValue SITargetLowering::performXorCombine(SDNode *N,
8472                                             DAGCombinerInfo &DCI) const {
8473   EVT VT = N->getValueType(0);
8474   if (VT != MVT::i64)
8475     return SDValue();
8476 
8477   SDValue LHS = N->getOperand(0);
8478   SDValue RHS = N->getOperand(1);
8479 
8480   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8481   if (CRHS) {
8482     if (SDValue Split
8483           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8484       return Split;
8485   }
8486 
8487   return SDValue();
8488 }
8489 
8490 // Instructions that will be lowered with a final instruction that zeros the
8491 // high result bits.
8492 // XXX - probably only need to list legal operations.
8493 static bool fp16SrcZerosHighBits(unsigned Opc) {
8494   switch (Opc) {
8495   case ISD::FADD:
8496   case ISD::FSUB:
8497   case ISD::FMUL:
8498   case ISD::FDIV:
8499   case ISD::FREM:
8500   case ISD::FMA:
8501   case ISD::FMAD:
8502   case ISD::FCANONICALIZE:
8503   case ISD::FP_ROUND:
8504   case ISD::UINT_TO_FP:
8505   case ISD::SINT_TO_FP:
8506   case ISD::FABS:
8507     // Fabs is lowered to a bit operation, but it's an and which will clear the
8508     // high bits anyway.
8509   case ISD::FSQRT:
8510   case ISD::FSIN:
8511   case ISD::FCOS:
8512   case ISD::FPOWI:
8513   case ISD::FPOW:
8514   case ISD::FLOG:
8515   case ISD::FLOG2:
8516   case ISD::FLOG10:
8517   case ISD::FEXP:
8518   case ISD::FEXP2:
8519   case ISD::FCEIL:
8520   case ISD::FTRUNC:
8521   case ISD::FRINT:
8522   case ISD::FNEARBYINT:
8523   case ISD::FROUND:
8524   case ISD::FFLOOR:
8525   case ISD::FMINNUM:
8526   case ISD::FMAXNUM:
8527   case AMDGPUISD::FRACT:
8528   case AMDGPUISD::CLAMP:
8529   case AMDGPUISD::COS_HW:
8530   case AMDGPUISD::SIN_HW:
8531   case AMDGPUISD::FMIN3:
8532   case AMDGPUISD::FMAX3:
8533   case AMDGPUISD::FMED3:
8534   case AMDGPUISD::FMAD_FTZ:
8535   case AMDGPUISD::RCP:
8536   case AMDGPUISD::RSQ:
8537   case AMDGPUISD::RCP_IFLAG:
8538   case AMDGPUISD::LDEXP:
8539     return true;
8540   default:
8541     // fcopysign, select and others may be lowered to 32-bit bit operations
8542     // which don't zero the high bits.
8543     return false;
8544   }
8545 }
8546 
8547 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8548                                                    DAGCombinerInfo &DCI) const {
8549   if (!Subtarget->has16BitInsts() ||
8550       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8551     return SDValue();
8552 
8553   EVT VT = N->getValueType(0);
8554   if (VT != MVT::i32)
8555     return SDValue();
8556 
8557   SDValue Src = N->getOperand(0);
8558   if (Src.getValueType() != MVT::i16)
8559     return SDValue();
8560 
8561   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8562   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8563   if (Src.getOpcode() == ISD::BITCAST) {
8564     SDValue BCSrc = Src.getOperand(0);
8565     if (BCSrc.getValueType() == MVT::f16 &&
8566         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8567       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8568   }
8569 
8570   return SDValue();
8571 }
8572 
8573 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8574                                                         DAGCombinerInfo &DCI)
8575                                                         const {
8576   SDValue Src = N->getOperand(0);
8577   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8578 
8579   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8580       VTSign->getVT() == MVT::i8) ||
8581       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8582       VTSign->getVT() == MVT::i16)) &&
8583       Src.hasOneUse()) {
8584     auto *M = cast<MemSDNode>(Src);
8585     SDValue Ops[] = {
8586       Src.getOperand(0), // Chain
8587       Src.getOperand(1), // rsrc
8588       Src.getOperand(2), // vindex
8589       Src.getOperand(3), // voffset
8590       Src.getOperand(4), // soffset
8591       Src.getOperand(5), // offset
8592       Src.getOperand(6),
8593       Src.getOperand(7)
8594     };
8595     // replace with BUFFER_LOAD_BYTE/SHORT
8596     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8597                                          Src.getOperand(0).getValueType());
8598     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8599                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8600     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8601                                                           ResList,
8602                                                           Ops, M->getMemoryVT(),
8603                                                           M->getMemOperand());
8604     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8605                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8606   }
8607   return SDValue();
8608 }
8609 
8610 SDValue SITargetLowering::performClassCombine(SDNode *N,
8611                                               DAGCombinerInfo &DCI) const {
8612   SelectionDAG &DAG = DCI.DAG;
8613   SDValue Mask = N->getOperand(1);
8614 
8615   // fp_class x, 0 -> false
8616   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8617     if (CMask->isNullValue())
8618       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8619   }
8620 
8621   if (N->getOperand(0).isUndef())
8622     return DAG.getUNDEF(MVT::i1);
8623 
8624   return SDValue();
8625 }
8626 
8627 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8628                                             DAGCombinerInfo &DCI) const {
8629   EVT VT = N->getValueType(0);
8630   SDValue N0 = N->getOperand(0);
8631 
8632   if (N0.isUndef())
8633     return N0;
8634 
8635   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8636                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8637     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8638                            N->getFlags());
8639   }
8640 
8641   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8642 }
8643 
8644 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8645                                        unsigned MaxDepth) const {
8646   unsigned Opcode = Op.getOpcode();
8647   if (Opcode == ISD::FCANONICALIZE)
8648     return true;
8649 
8650   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8651     auto F = CFP->getValueAPF();
8652     if (F.isNaN() && F.isSignaling())
8653       return false;
8654     return !F.isDenormal() || denormalsEnabledForType(Op.getValueType());
8655   }
8656 
8657   // If source is a result of another standard FP operation it is already in
8658   // canonical form.
8659   if (MaxDepth == 0)
8660     return false;
8661 
8662   switch (Opcode) {
8663   // These will flush denorms if required.
8664   case ISD::FADD:
8665   case ISD::FSUB:
8666   case ISD::FMUL:
8667   case ISD::FCEIL:
8668   case ISD::FFLOOR:
8669   case ISD::FMA:
8670   case ISD::FMAD:
8671   case ISD::FSQRT:
8672   case ISD::FDIV:
8673   case ISD::FREM:
8674   case ISD::FP_ROUND:
8675   case ISD::FP_EXTEND:
8676   case AMDGPUISD::FMUL_LEGACY:
8677   case AMDGPUISD::FMAD_FTZ:
8678   case AMDGPUISD::RCP:
8679   case AMDGPUISD::RSQ:
8680   case AMDGPUISD::RSQ_CLAMP:
8681   case AMDGPUISD::RCP_LEGACY:
8682   case AMDGPUISD::RSQ_LEGACY:
8683   case AMDGPUISD::RCP_IFLAG:
8684   case AMDGPUISD::TRIG_PREOP:
8685   case AMDGPUISD::DIV_SCALE:
8686   case AMDGPUISD::DIV_FMAS:
8687   case AMDGPUISD::DIV_FIXUP:
8688   case AMDGPUISD::FRACT:
8689   case AMDGPUISD::LDEXP:
8690   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8691   case AMDGPUISD::CVT_F32_UBYTE0:
8692   case AMDGPUISD::CVT_F32_UBYTE1:
8693   case AMDGPUISD::CVT_F32_UBYTE2:
8694   case AMDGPUISD::CVT_F32_UBYTE3:
8695     return true;
8696 
8697   // It can/will be lowered or combined as a bit operation.
8698   // Need to check their input recursively to handle.
8699   case ISD::FNEG:
8700   case ISD::FABS:
8701   case ISD::FCOPYSIGN:
8702     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8703 
8704   case ISD::FSIN:
8705   case ISD::FCOS:
8706   case ISD::FSINCOS:
8707     return Op.getValueType().getScalarType() != MVT::f16;
8708 
8709   case ISD::FMINNUM:
8710   case ISD::FMAXNUM:
8711   case ISD::FMINNUM_IEEE:
8712   case ISD::FMAXNUM_IEEE:
8713   case AMDGPUISD::CLAMP:
8714   case AMDGPUISD::FMED3:
8715   case AMDGPUISD::FMAX3:
8716   case AMDGPUISD::FMIN3: {
8717     // FIXME: Shouldn't treat the generic operations different based these.
8718     // However, we aren't really required to flush the result from
8719     // minnum/maxnum..
8720 
8721     // snans will be quieted, so we only need to worry about denormals.
8722     if (Subtarget->supportsMinMaxDenormModes() ||
8723         denormalsEnabledForType(Op.getValueType()))
8724       return true;
8725 
8726     // Flushing may be required.
8727     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8728     // targets need to check their input recursively.
8729 
8730     // FIXME: Does this apply with clamp? It's implemented with max.
8731     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8732       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8733         return false;
8734     }
8735 
8736     return true;
8737   }
8738   case ISD::SELECT: {
8739     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8740            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8741   }
8742   case ISD::BUILD_VECTOR: {
8743     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8744       SDValue SrcOp = Op.getOperand(i);
8745       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8746         return false;
8747     }
8748 
8749     return true;
8750   }
8751   case ISD::EXTRACT_VECTOR_ELT:
8752   case ISD::EXTRACT_SUBVECTOR: {
8753     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8754   }
8755   case ISD::INSERT_VECTOR_ELT: {
8756     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8757            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8758   }
8759   case ISD::UNDEF:
8760     // Could be anything.
8761     return false;
8762 
8763   case ISD::BITCAST: {
8764     // Hack round the mess we make when legalizing extract_vector_elt
8765     SDValue Src = Op.getOperand(0);
8766     if (Src.getValueType() == MVT::i16 &&
8767         Src.getOpcode() == ISD::TRUNCATE) {
8768       SDValue TruncSrc = Src.getOperand(0);
8769       if (TruncSrc.getValueType() == MVT::i32 &&
8770           TruncSrc.getOpcode() == ISD::BITCAST &&
8771           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8772         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8773       }
8774     }
8775 
8776     return false;
8777   }
8778   case ISD::INTRINSIC_WO_CHAIN: {
8779     unsigned IntrinsicID
8780       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8781     // TODO: Handle more intrinsics
8782     switch (IntrinsicID) {
8783     case Intrinsic::amdgcn_cvt_pkrtz:
8784     case Intrinsic::amdgcn_cubeid:
8785     case Intrinsic::amdgcn_frexp_mant:
8786     case Intrinsic::amdgcn_fdot2:
8787       return true;
8788     default:
8789       break;
8790     }
8791 
8792     LLVM_FALLTHROUGH;
8793   }
8794   default:
8795     return denormalsEnabledForType(Op.getValueType()) &&
8796            DAG.isKnownNeverSNaN(Op);
8797   }
8798 
8799   llvm_unreachable("invalid operation");
8800 }
8801 
8802 // Constant fold canonicalize.
8803 SDValue SITargetLowering::getCanonicalConstantFP(
8804   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8805   // Flush denormals to 0 if not enabled.
8806   if (C.isDenormal() && !denormalsEnabledForType(VT))
8807     return DAG.getConstantFP(0.0, SL, VT);
8808 
8809   if (C.isNaN()) {
8810     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8811     if (C.isSignaling()) {
8812       // Quiet a signaling NaN.
8813       // FIXME: Is this supposed to preserve payload bits?
8814       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8815     }
8816 
8817     // Make sure it is the canonical NaN bitpattern.
8818     //
8819     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8820     // immediate?
8821     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8822       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8823   }
8824 
8825   // Already canonical.
8826   return DAG.getConstantFP(C, SL, VT);
8827 }
8828 
8829 static bool vectorEltWillFoldAway(SDValue Op) {
8830   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8831 }
8832 
8833 SDValue SITargetLowering::performFCanonicalizeCombine(
8834   SDNode *N,
8835   DAGCombinerInfo &DCI) const {
8836   SelectionDAG &DAG = DCI.DAG;
8837   SDValue N0 = N->getOperand(0);
8838   EVT VT = N->getValueType(0);
8839 
8840   // fcanonicalize undef -> qnan
8841   if (N0.isUndef()) {
8842     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8843     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8844   }
8845 
8846   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8847     EVT VT = N->getValueType(0);
8848     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8849   }
8850 
8851   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8852   //                                                   (fcanonicalize k)
8853   //
8854   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8855 
8856   // TODO: This could be better with wider vectors that will be split to v2f16,
8857   // and to consider uses since there aren't that many packed operations.
8858   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8859       isTypeLegal(MVT::v2f16)) {
8860     SDLoc SL(N);
8861     SDValue NewElts[2];
8862     SDValue Lo = N0.getOperand(0);
8863     SDValue Hi = N0.getOperand(1);
8864     EVT EltVT = Lo.getValueType();
8865 
8866     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8867       for (unsigned I = 0; I != 2; ++I) {
8868         SDValue Op = N0.getOperand(I);
8869         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8870           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8871                                               CFP->getValueAPF());
8872         } else if (Op.isUndef()) {
8873           // Handled below based on what the other operand is.
8874           NewElts[I] = Op;
8875         } else {
8876           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8877         }
8878       }
8879 
8880       // If one half is undef, and one is constant, perfer a splat vector rather
8881       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8882       // cheaper to use and may be free with a packed operation.
8883       if (NewElts[0].isUndef()) {
8884         if (isa<ConstantFPSDNode>(NewElts[1]))
8885           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8886             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8887       }
8888 
8889       if (NewElts[1].isUndef()) {
8890         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8891           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8892       }
8893 
8894       return DAG.getBuildVector(VT, SL, NewElts);
8895     }
8896   }
8897 
8898   unsigned SrcOpc = N0.getOpcode();
8899 
8900   // If it's free to do so, push canonicalizes further up the source, which may
8901   // find a canonical source.
8902   //
8903   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8904   // sNaNs.
8905   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8906     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8907     if (CRHS && N0.hasOneUse()) {
8908       SDLoc SL(N);
8909       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8910                                    N0.getOperand(0));
8911       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8912       DCI.AddToWorklist(Canon0.getNode());
8913 
8914       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8915     }
8916   }
8917 
8918   return isCanonicalized(DAG, N0) ? N0 : SDValue();
8919 }
8920 
8921 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
8922   switch (Opc) {
8923   case ISD::FMAXNUM:
8924   case ISD::FMAXNUM_IEEE:
8925     return AMDGPUISD::FMAX3;
8926   case ISD::SMAX:
8927     return AMDGPUISD::SMAX3;
8928   case ISD::UMAX:
8929     return AMDGPUISD::UMAX3;
8930   case ISD::FMINNUM:
8931   case ISD::FMINNUM_IEEE:
8932     return AMDGPUISD::FMIN3;
8933   case ISD::SMIN:
8934     return AMDGPUISD::SMIN3;
8935   case ISD::UMIN:
8936     return AMDGPUISD::UMIN3;
8937   default:
8938     llvm_unreachable("Not a min/max opcode");
8939   }
8940 }
8941 
8942 SDValue SITargetLowering::performIntMed3ImmCombine(
8943   SelectionDAG &DAG, const SDLoc &SL,
8944   SDValue Op0, SDValue Op1, bool Signed) const {
8945   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8946   if (!K1)
8947     return SDValue();
8948 
8949   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8950   if (!K0)
8951     return SDValue();
8952 
8953   if (Signed) {
8954     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8955       return SDValue();
8956   } else {
8957     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8958       return SDValue();
8959   }
8960 
8961   EVT VT = K0->getValueType(0);
8962   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8963   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8964     return DAG.getNode(Med3Opc, SL, VT,
8965                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8966   }
8967 
8968   // If there isn't a 16-bit med3 operation, convert to 32-bit.
8969   MVT NVT = MVT::i32;
8970   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8971 
8972   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8973   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8974   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
8975 
8976   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8977   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
8978 }
8979 
8980 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8981   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8982     return C;
8983 
8984   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8985     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
8986       return C;
8987   }
8988 
8989   return nullptr;
8990 }
8991 
8992 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
8993                                                   const SDLoc &SL,
8994                                                   SDValue Op0,
8995                                                   SDValue Op1) const {
8996   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
8997   if (!K1)
8998     return SDValue();
8999 
9000   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9001   if (!K0)
9002     return SDValue();
9003 
9004   // Ordered >= (although NaN inputs should have folded away by now).
9005   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
9006   if (Cmp == APFloat::cmpGreaterThan)
9007     return SDValue();
9008 
9009   const MachineFunction &MF = DAG.getMachineFunction();
9010   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9011 
9012   // TODO: Check IEEE bit enabled?
9013   EVT VT = Op0.getValueType();
9014   if (Info->getMode().DX10Clamp) {
9015     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9016     // hardware fmed3 behavior converting to a min.
9017     // FIXME: Should this be allowing -0.0?
9018     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9019       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9020   }
9021 
9022   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9023   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9024     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9025     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9026     // then give the other result, which is different from med3 with a NaN
9027     // input.
9028     SDValue Var = Op0.getOperand(0);
9029     if (!DAG.isKnownNeverSNaN(Var))
9030       return SDValue();
9031 
9032     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9033 
9034     if ((!K0->hasOneUse() ||
9035          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9036         (!K1->hasOneUse() ||
9037          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9038       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9039                          Var, SDValue(K0, 0), SDValue(K1, 0));
9040     }
9041   }
9042 
9043   return SDValue();
9044 }
9045 
9046 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9047                                                DAGCombinerInfo &DCI) const {
9048   SelectionDAG &DAG = DCI.DAG;
9049 
9050   EVT VT = N->getValueType(0);
9051   unsigned Opc = N->getOpcode();
9052   SDValue Op0 = N->getOperand(0);
9053   SDValue Op1 = N->getOperand(1);
9054 
9055   // Only do this if the inner op has one use since this will just increases
9056   // register pressure for no benefit.
9057 
9058   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9059       !VT.isVector() &&
9060       (VT == MVT::i32 || VT == MVT::f32 ||
9061        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9062     // max(max(a, b), c) -> max3(a, b, c)
9063     // min(min(a, b), c) -> min3(a, b, c)
9064     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9065       SDLoc DL(N);
9066       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9067                          DL,
9068                          N->getValueType(0),
9069                          Op0.getOperand(0),
9070                          Op0.getOperand(1),
9071                          Op1);
9072     }
9073 
9074     // Try commuted.
9075     // max(a, max(b, c)) -> max3(a, b, c)
9076     // min(a, min(b, c)) -> min3(a, b, c)
9077     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9078       SDLoc DL(N);
9079       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9080                          DL,
9081                          N->getValueType(0),
9082                          Op0,
9083                          Op1.getOperand(0),
9084                          Op1.getOperand(1));
9085     }
9086   }
9087 
9088   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9089   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9090     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9091       return Med3;
9092   }
9093 
9094   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9095     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9096       return Med3;
9097   }
9098 
9099   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9100   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9101        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9102        (Opc == AMDGPUISD::FMIN_LEGACY &&
9103         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9104       (VT == MVT::f32 || VT == MVT::f64 ||
9105        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9106        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9107       Op0.hasOneUse()) {
9108     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9109       return Res;
9110   }
9111 
9112   return SDValue();
9113 }
9114 
9115 static bool isClampZeroToOne(SDValue A, SDValue B) {
9116   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9117     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9118       // FIXME: Should this be allowing -0.0?
9119       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9120              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9121     }
9122   }
9123 
9124   return false;
9125 }
9126 
9127 // FIXME: Should only worry about snans for version with chain.
9128 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9129                                               DAGCombinerInfo &DCI) const {
9130   EVT VT = N->getValueType(0);
9131   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9132   // NaNs. With a NaN input, the order of the operands may change the result.
9133 
9134   SelectionDAG &DAG = DCI.DAG;
9135   SDLoc SL(N);
9136 
9137   SDValue Src0 = N->getOperand(0);
9138   SDValue Src1 = N->getOperand(1);
9139   SDValue Src2 = N->getOperand(2);
9140 
9141   if (isClampZeroToOne(Src0, Src1)) {
9142     // const_a, const_b, x -> clamp is safe in all cases including signaling
9143     // nans.
9144     // FIXME: Should this be allowing -0.0?
9145     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9146   }
9147 
9148   const MachineFunction &MF = DAG.getMachineFunction();
9149   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9150 
9151   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9152   // handling no dx10-clamp?
9153   if (Info->getMode().DX10Clamp) {
9154     // If NaNs is clamped to 0, we are free to reorder the inputs.
9155 
9156     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9157       std::swap(Src0, Src1);
9158 
9159     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9160       std::swap(Src1, Src2);
9161 
9162     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9163       std::swap(Src0, Src1);
9164 
9165     if (isClampZeroToOne(Src1, Src2))
9166       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9167   }
9168 
9169   return SDValue();
9170 }
9171 
9172 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9173                                                  DAGCombinerInfo &DCI) const {
9174   SDValue Src0 = N->getOperand(0);
9175   SDValue Src1 = N->getOperand(1);
9176   if (Src0.isUndef() && Src1.isUndef())
9177     return DCI.DAG.getUNDEF(N->getValueType(0));
9178   return SDValue();
9179 }
9180 
9181 SDValue SITargetLowering::performExtractVectorEltCombine(
9182   SDNode *N, DAGCombinerInfo &DCI) const {
9183   SDValue Vec = N->getOperand(0);
9184   SelectionDAG &DAG = DCI.DAG;
9185 
9186   EVT VecVT = Vec.getValueType();
9187   EVT EltVT = VecVT.getVectorElementType();
9188 
9189   if ((Vec.getOpcode() == ISD::FNEG ||
9190        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9191     SDLoc SL(N);
9192     EVT EltVT = N->getValueType(0);
9193     SDValue Idx = N->getOperand(1);
9194     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9195                               Vec.getOperand(0), Idx);
9196     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9197   }
9198 
9199   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9200   //    =>
9201   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9202   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9203   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9204   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9205     SDLoc SL(N);
9206     EVT EltVT = N->getValueType(0);
9207     SDValue Idx = N->getOperand(1);
9208     unsigned Opc = Vec.getOpcode();
9209 
9210     switch(Opc) {
9211     default:
9212       break;
9213       // TODO: Support other binary operations.
9214     case ISD::FADD:
9215     case ISD::FSUB:
9216     case ISD::FMUL:
9217     case ISD::ADD:
9218     case ISD::UMIN:
9219     case ISD::UMAX:
9220     case ISD::SMIN:
9221     case ISD::SMAX:
9222     case ISD::FMAXNUM:
9223     case ISD::FMINNUM:
9224     case ISD::FMAXNUM_IEEE:
9225     case ISD::FMINNUM_IEEE: {
9226       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9227                                  Vec.getOperand(0), Idx);
9228       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9229                                  Vec.getOperand(1), Idx);
9230 
9231       DCI.AddToWorklist(Elt0.getNode());
9232       DCI.AddToWorklist(Elt1.getNode());
9233       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9234     }
9235     }
9236   }
9237 
9238   unsigned VecSize = VecVT.getSizeInBits();
9239   unsigned EltSize = EltVT.getSizeInBits();
9240 
9241   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9242   // This elminates non-constant index and subsequent movrel or scratch access.
9243   // Sub-dword vectors of size 2 dword or less have better implementation.
9244   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9245   // instructions.
9246   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9247       !isa<ConstantSDNode>(N->getOperand(1))) {
9248     SDLoc SL(N);
9249     SDValue Idx = N->getOperand(1);
9250     EVT IdxVT = Idx.getValueType();
9251     SDValue V;
9252     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9253       SDValue IC = DAG.getConstant(I, SL, IdxVT);
9254       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9255       if (I == 0)
9256         V = Elt;
9257       else
9258         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9259     }
9260     return V;
9261   }
9262 
9263   if (!DCI.isBeforeLegalize())
9264     return SDValue();
9265 
9266   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9267   // elements. This exposes more load reduction opportunities by replacing
9268   // multiple small extract_vector_elements with a single 32-bit extract.
9269   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9270   if (isa<MemSDNode>(Vec) &&
9271       EltSize <= 16 &&
9272       EltVT.isByteSized() &&
9273       VecSize > 32 &&
9274       VecSize % 32 == 0 &&
9275       Idx) {
9276     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9277 
9278     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9279     unsigned EltIdx = BitIndex / 32;
9280     unsigned LeftoverBitIdx = BitIndex % 32;
9281     SDLoc SL(N);
9282 
9283     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9284     DCI.AddToWorklist(Cast.getNode());
9285 
9286     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9287                               DAG.getConstant(EltIdx, SL, MVT::i32));
9288     DCI.AddToWorklist(Elt.getNode());
9289     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9290                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9291     DCI.AddToWorklist(Srl.getNode());
9292 
9293     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9294     DCI.AddToWorklist(Trunc.getNode());
9295     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9296   }
9297 
9298   return SDValue();
9299 }
9300 
9301 SDValue
9302 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9303                                                 DAGCombinerInfo &DCI) const {
9304   SDValue Vec = N->getOperand(0);
9305   SDValue Idx = N->getOperand(2);
9306   EVT VecVT = Vec.getValueType();
9307   EVT EltVT = VecVT.getVectorElementType();
9308   unsigned VecSize = VecVT.getSizeInBits();
9309   unsigned EltSize = EltVT.getSizeInBits();
9310 
9311   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9312   // => BUILD_VECTOR n x select (e, const-idx)
9313   // This elminates non-constant index and subsequent movrel or scratch access.
9314   // Sub-dword vectors of size 2 dword or less have better implementation.
9315   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9316   // instructions.
9317   if (isa<ConstantSDNode>(Idx) ||
9318       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9319     return SDValue();
9320 
9321   SelectionDAG &DAG = DCI.DAG;
9322   SDLoc SL(N);
9323   SDValue Ins = N->getOperand(1);
9324   EVT IdxVT = Idx.getValueType();
9325 
9326   SmallVector<SDValue, 16> Ops;
9327   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9328     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9329     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9330     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9331     Ops.push_back(V);
9332   }
9333 
9334   return DAG.getBuildVector(VecVT, SL, Ops);
9335 }
9336 
9337 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9338                                           const SDNode *N0,
9339                                           const SDNode *N1) const {
9340   EVT VT = N0->getValueType(0);
9341 
9342   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9343   // support denormals ever.
9344   if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
9345        (VT == MVT::f16 && !Subtarget->hasFP16Denormals() &&
9346         getSubtarget()->hasMadF16())) &&
9347        isOperationLegal(ISD::FMAD, VT))
9348     return ISD::FMAD;
9349 
9350   const TargetOptions &Options = DAG.getTarget().Options;
9351   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9352        (N0->getFlags().hasAllowContract() &&
9353         N1->getFlags().hasAllowContract())) &&
9354       isFMAFasterThanFMulAndFAdd(VT)) {
9355     return ISD::FMA;
9356   }
9357 
9358   return 0;
9359 }
9360 
9361 // For a reassociatable opcode perform:
9362 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9363 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9364                                                SelectionDAG &DAG) const {
9365   EVT VT = N->getValueType(0);
9366   if (VT != MVT::i32 && VT != MVT::i64)
9367     return SDValue();
9368 
9369   unsigned Opc = N->getOpcode();
9370   SDValue Op0 = N->getOperand(0);
9371   SDValue Op1 = N->getOperand(1);
9372 
9373   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9374     return SDValue();
9375 
9376   if (Op0->isDivergent())
9377     std::swap(Op0, Op1);
9378 
9379   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9380     return SDValue();
9381 
9382   SDValue Op2 = Op1.getOperand(1);
9383   Op1 = Op1.getOperand(0);
9384   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9385     return SDValue();
9386 
9387   if (Op1->isDivergent())
9388     std::swap(Op1, Op2);
9389 
9390   // If either operand is constant this will conflict with
9391   // DAGCombiner::ReassociateOps().
9392   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9393       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9394     return SDValue();
9395 
9396   SDLoc SL(N);
9397   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9398   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9399 }
9400 
9401 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9402                            EVT VT,
9403                            SDValue N0, SDValue N1, SDValue N2,
9404                            bool Signed) {
9405   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9406   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9407   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9408   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9409 }
9410 
9411 SDValue SITargetLowering::performAddCombine(SDNode *N,
9412                                             DAGCombinerInfo &DCI) const {
9413   SelectionDAG &DAG = DCI.DAG;
9414   EVT VT = N->getValueType(0);
9415   SDLoc SL(N);
9416   SDValue LHS = N->getOperand(0);
9417   SDValue RHS = N->getOperand(1);
9418 
9419   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9420       && Subtarget->hasMad64_32() &&
9421       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9422       VT.getScalarSizeInBits() <= 64) {
9423     if (LHS.getOpcode() != ISD::MUL)
9424       std::swap(LHS, RHS);
9425 
9426     SDValue MulLHS = LHS.getOperand(0);
9427     SDValue MulRHS = LHS.getOperand(1);
9428     SDValue AddRHS = RHS;
9429 
9430     // TODO: Maybe restrict if SGPR inputs.
9431     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9432         numBitsUnsigned(MulRHS, DAG) <= 32) {
9433       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9434       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9435       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9436       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9437     }
9438 
9439     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9440       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9441       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9442       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9443       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9444     }
9445 
9446     return SDValue();
9447   }
9448 
9449   if (SDValue V = reassociateScalarOps(N, DAG)) {
9450     return V;
9451   }
9452 
9453   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9454     return SDValue();
9455 
9456   // add x, zext (setcc) => addcarry x, 0, setcc
9457   // add x, sext (setcc) => subcarry x, 0, setcc
9458   unsigned Opc = LHS.getOpcode();
9459   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9460       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9461     std::swap(RHS, LHS);
9462 
9463   Opc = RHS.getOpcode();
9464   switch (Opc) {
9465   default: break;
9466   case ISD::ZERO_EXTEND:
9467   case ISD::SIGN_EXTEND:
9468   case ISD::ANY_EXTEND: {
9469     auto Cond = RHS.getOperand(0);
9470     if (!isBoolSGPR(Cond))
9471       break;
9472     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9473     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9474     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9475     return DAG.getNode(Opc, SL, VTList, Args);
9476   }
9477   case ISD::ADDCARRY: {
9478     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9479     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9480     if (!C || C->getZExtValue() != 0) break;
9481     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9482     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9483   }
9484   }
9485   return SDValue();
9486 }
9487 
9488 SDValue SITargetLowering::performSubCombine(SDNode *N,
9489                                             DAGCombinerInfo &DCI) const {
9490   SelectionDAG &DAG = DCI.DAG;
9491   EVT VT = N->getValueType(0);
9492 
9493   if (VT != MVT::i32)
9494     return SDValue();
9495 
9496   SDLoc SL(N);
9497   SDValue LHS = N->getOperand(0);
9498   SDValue RHS = N->getOperand(1);
9499 
9500   if (LHS.getOpcode() == ISD::SUBCARRY) {
9501     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9502     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9503     if (!C || !C->isNullValue())
9504       return SDValue();
9505     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9506     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9507   }
9508   return SDValue();
9509 }
9510 
9511 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9512   DAGCombinerInfo &DCI) const {
9513 
9514   if (N->getValueType(0) != MVT::i32)
9515     return SDValue();
9516 
9517   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9518   if (!C || C->getZExtValue() != 0)
9519     return SDValue();
9520 
9521   SelectionDAG &DAG = DCI.DAG;
9522   SDValue LHS = N->getOperand(0);
9523 
9524   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9525   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9526   unsigned LHSOpc = LHS.getOpcode();
9527   unsigned Opc = N->getOpcode();
9528   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9529       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9530     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9531     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9532   }
9533   return SDValue();
9534 }
9535 
9536 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9537                                              DAGCombinerInfo &DCI) const {
9538   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9539     return SDValue();
9540 
9541   SelectionDAG &DAG = DCI.DAG;
9542   EVT VT = N->getValueType(0);
9543 
9544   SDLoc SL(N);
9545   SDValue LHS = N->getOperand(0);
9546   SDValue RHS = N->getOperand(1);
9547 
9548   // These should really be instruction patterns, but writing patterns with
9549   // source modiifiers is a pain.
9550 
9551   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9552   if (LHS.getOpcode() == ISD::FADD) {
9553     SDValue A = LHS.getOperand(0);
9554     if (A == LHS.getOperand(1)) {
9555       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9556       if (FusedOp != 0) {
9557         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9558         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9559       }
9560     }
9561   }
9562 
9563   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9564   if (RHS.getOpcode() == ISD::FADD) {
9565     SDValue A = RHS.getOperand(0);
9566     if (A == RHS.getOperand(1)) {
9567       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9568       if (FusedOp != 0) {
9569         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9570         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9571       }
9572     }
9573   }
9574 
9575   return SDValue();
9576 }
9577 
9578 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9579                                              DAGCombinerInfo &DCI) const {
9580   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9581     return SDValue();
9582 
9583   SelectionDAG &DAG = DCI.DAG;
9584   SDLoc SL(N);
9585   EVT VT = N->getValueType(0);
9586   assert(!VT.isVector());
9587 
9588   // Try to get the fneg to fold into the source modifier. This undoes generic
9589   // DAG combines and folds them into the mad.
9590   //
9591   // Only do this if we are not trying to support denormals. v_mad_f32 does
9592   // not support denormals ever.
9593   SDValue LHS = N->getOperand(0);
9594   SDValue RHS = N->getOperand(1);
9595   if (LHS.getOpcode() == ISD::FADD) {
9596     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9597     SDValue A = LHS.getOperand(0);
9598     if (A == LHS.getOperand(1)) {
9599       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9600       if (FusedOp != 0){
9601         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9602         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9603 
9604         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9605       }
9606     }
9607   }
9608 
9609   if (RHS.getOpcode() == ISD::FADD) {
9610     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9611 
9612     SDValue A = RHS.getOperand(0);
9613     if (A == RHS.getOperand(1)) {
9614       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9615       if (FusedOp != 0){
9616         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9617         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9618       }
9619     }
9620   }
9621 
9622   return SDValue();
9623 }
9624 
9625 SDValue SITargetLowering::performFMACombine(SDNode *N,
9626                                             DAGCombinerInfo &DCI) const {
9627   SelectionDAG &DAG = DCI.DAG;
9628   EVT VT = N->getValueType(0);
9629   SDLoc SL(N);
9630 
9631   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9632     return SDValue();
9633 
9634   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9635   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9636   SDValue Op1 = N->getOperand(0);
9637   SDValue Op2 = N->getOperand(1);
9638   SDValue FMA = N->getOperand(2);
9639 
9640   if (FMA.getOpcode() != ISD::FMA ||
9641       Op1.getOpcode() != ISD::FP_EXTEND ||
9642       Op2.getOpcode() != ISD::FP_EXTEND)
9643     return SDValue();
9644 
9645   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9646   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9647   // is sufficient to allow generaing fdot2.
9648   const TargetOptions &Options = DAG.getTarget().Options;
9649   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9650       (N->getFlags().hasAllowContract() &&
9651        FMA->getFlags().hasAllowContract())) {
9652     Op1 = Op1.getOperand(0);
9653     Op2 = Op2.getOperand(0);
9654     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9655         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9656       return SDValue();
9657 
9658     SDValue Vec1 = Op1.getOperand(0);
9659     SDValue Idx1 = Op1.getOperand(1);
9660     SDValue Vec2 = Op2.getOperand(0);
9661 
9662     SDValue FMAOp1 = FMA.getOperand(0);
9663     SDValue FMAOp2 = FMA.getOperand(1);
9664     SDValue FMAAcc = FMA.getOperand(2);
9665 
9666     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9667         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9668       return SDValue();
9669 
9670     FMAOp1 = FMAOp1.getOperand(0);
9671     FMAOp2 = FMAOp2.getOperand(0);
9672     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9673         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9674       return SDValue();
9675 
9676     SDValue Vec3 = FMAOp1.getOperand(0);
9677     SDValue Vec4 = FMAOp2.getOperand(0);
9678     SDValue Idx2 = FMAOp1.getOperand(1);
9679 
9680     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9681         // Idx1 and Idx2 cannot be the same.
9682         Idx1 == Idx2)
9683       return SDValue();
9684 
9685     if (Vec1 == Vec2 || Vec3 == Vec4)
9686       return SDValue();
9687 
9688     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9689       return SDValue();
9690 
9691     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9692         (Vec1 == Vec4 && Vec2 == Vec3)) {
9693       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9694                          DAG.getTargetConstant(0, SL, MVT::i1));
9695     }
9696   }
9697   return SDValue();
9698 }
9699 
9700 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9701                                               DAGCombinerInfo &DCI) const {
9702   SelectionDAG &DAG = DCI.DAG;
9703   SDLoc SL(N);
9704 
9705   SDValue LHS = N->getOperand(0);
9706   SDValue RHS = N->getOperand(1);
9707   EVT VT = LHS.getValueType();
9708   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9709 
9710   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9711   if (!CRHS) {
9712     CRHS = dyn_cast<ConstantSDNode>(LHS);
9713     if (CRHS) {
9714       std::swap(LHS, RHS);
9715       CC = getSetCCSwappedOperands(CC);
9716     }
9717   }
9718 
9719   if (CRHS) {
9720     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9721         isBoolSGPR(LHS.getOperand(0))) {
9722       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9723       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9724       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9725       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9726       if ((CRHS->isAllOnesValue() &&
9727            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9728           (CRHS->isNullValue() &&
9729            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9730         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9731                            DAG.getConstant(-1, SL, MVT::i1));
9732       if ((CRHS->isAllOnesValue() &&
9733            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9734           (CRHS->isNullValue() &&
9735            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9736         return LHS.getOperand(0);
9737     }
9738 
9739     uint64_t CRHSVal = CRHS->getZExtValue();
9740     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9741         LHS.getOpcode() == ISD::SELECT &&
9742         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9743         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9744         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9745         isBoolSGPR(LHS.getOperand(0))) {
9746       // Given CT != FT:
9747       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9748       // setcc (select cc, CT, CF), CF, ne => cc
9749       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9750       // setcc (select cc, CT, CF), CT, eq => cc
9751       uint64_t CT = LHS.getConstantOperandVal(1);
9752       uint64_t CF = LHS.getConstantOperandVal(2);
9753 
9754       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9755           (CT == CRHSVal && CC == ISD::SETNE))
9756         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9757                            DAG.getConstant(-1, SL, MVT::i1));
9758       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9759           (CT == CRHSVal && CC == ISD::SETEQ))
9760         return LHS.getOperand(0);
9761     }
9762   }
9763 
9764   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9765                                            VT != MVT::f16))
9766     return SDValue();
9767 
9768   // Match isinf/isfinite pattern
9769   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9770   // (fcmp one (fabs x), inf) -> (fp_class x,
9771   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9772   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9773     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9774     if (!CRHS)
9775       return SDValue();
9776 
9777     const APFloat &APF = CRHS->getValueAPF();
9778     if (APF.isInfinity() && !APF.isNegative()) {
9779       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9780                                  SIInstrFlags::N_INFINITY;
9781       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9782                                     SIInstrFlags::P_ZERO |
9783                                     SIInstrFlags::N_NORMAL |
9784                                     SIInstrFlags::P_NORMAL |
9785                                     SIInstrFlags::N_SUBNORMAL |
9786                                     SIInstrFlags::P_SUBNORMAL;
9787       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9788       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9789                          DAG.getConstant(Mask, SL, MVT::i32));
9790     }
9791   }
9792 
9793   return SDValue();
9794 }
9795 
9796 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9797                                                      DAGCombinerInfo &DCI) const {
9798   SelectionDAG &DAG = DCI.DAG;
9799   SDLoc SL(N);
9800   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9801 
9802   SDValue Src = N->getOperand(0);
9803   SDValue Srl = N->getOperand(0);
9804   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9805     Srl = Srl.getOperand(0);
9806 
9807   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9808   if (Srl.getOpcode() == ISD::SRL) {
9809     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9810     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9811     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9812 
9813     if (const ConstantSDNode *C =
9814         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9815       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9816                                EVT(MVT::i32));
9817 
9818       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9819       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9820         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9821                            MVT::f32, Srl);
9822       }
9823     }
9824   }
9825 
9826   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9827 
9828   KnownBits Known;
9829   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9830                                         !DCI.isBeforeLegalizeOps());
9831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9832   if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
9833     DCI.CommitTargetLoweringOpt(TLO);
9834   }
9835 
9836   return SDValue();
9837 }
9838 
9839 SDValue SITargetLowering::performClampCombine(SDNode *N,
9840                                               DAGCombinerInfo &DCI) const {
9841   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9842   if (!CSrc)
9843     return SDValue();
9844 
9845   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9846   const APFloat &F = CSrc->getValueAPF();
9847   APFloat Zero = APFloat::getZero(F.getSemantics());
9848   APFloat::cmpResult Cmp0 = F.compare(Zero);
9849   if (Cmp0 == APFloat::cmpLessThan ||
9850       (Cmp0 == APFloat::cmpUnordered &&
9851        MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9852     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9853   }
9854 
9855   APFloat One(F.getSemantics(), "1.0");
9856   APFloat::cmpResult Cmp1 = F.compare(One);
9857   if (Cmp1 == APFloat::cmpGreaterThan)
9858     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9859 
9860   return SDValue(CSrc, 0);
9861 }
9862 
9863 
9864 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9865                                             DAGCombinerInfo &DCI) const {
9866   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9867     return SDValue();
9868   switch (N->getOpcode()) {
9869   default:
9870     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9871   case ISD::ADD:
9872     return performAddCombine(N, DCI);
9873   case ISD::SUB:
9874     return performSubCombine(N, DCI);
9875   case ISD::ADDCARRY:
9876   case ISD::SUBCARRY:
9877     return performAddCarrySubCarryCombine(N, DCI);
9878   case ISD::FADD:
9879     return performFAddCombine(N, DCI);
9880   case ISD::FSUB:
9881     return performFSubCombine(N, DCI);
9882   case ISD::SETCC:
9883     return performSetCCCombine(N, DCI);
9884   case ISD::FMAXNUM:
9885   case ISD::FMINNUM:
9886   case ISD::FMAXNUM_IEEE:
9887   case ISD::FMINNUM_IEEE:
9888   case ISD::SMAX:
9889   case ISD::SMIN:
9890   case ISD::UMAX:
9891   case ISD::UMIN:
9892   case AMDGPUISD::FMIN_LEGACY:
9893   case AMDGPUISD::FMAX_LEGACY:
9894     return performMinMaxCombine(N, DCI);
9895   case ISD::FMA:
9896     return performFMACombine(N, DCI);
9897   case ISD::LOAD: {
9898     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9899       return Widended;
9900     LLVM_FALLTHROUGH;
9901   }
9902   case ISD::STORE:
9903   case ISD::ATOMIC_LOAD:
9904   case ISD::ATOMIC_STORE:
9905   case ISD::ATOMIC_CMP_SWAP:
9906   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9907   case ISD::ATOMIC_SWAP:
9908   case ISD::ATOMIC_LOAD_ADD:
9909   case ISD::ATOMIC_LOAD_SUB:
9910   case ISD::ATOMIC_LOAD_AND:
9911   case ISD::ATOMIC_LOAD_OR:
9912   case ISD::ATOMIC_LOAD_XOR:
9913   case ISD::ATOMIC_LOAD_NAND:
9914   case ISD::ATOMIC_LOAD_MIN:
9915   case ISD::ATOMIC_LOAD_MAX:
9916   case ISD::ATOMIC_LOAD_UMIN:
9917   case ISD::ATOMIC_LOAD_UMAX:
9918   case ISD::ATOMIC_LOAD_FADD:
9919   case AMDGPUISD::ATOMIC_INC:
9920   case AMDGPUISD::ATOMIC_DEC:
9921   case AMDGPUISD::ATOMIC_LOAD_FMIN:
9922   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
9923     if (DCI.isBeforeLegalize())
9924       break;
9925     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
9926   case ISD::AND:
9927     return performAndCombine(N, DCI);
9928   case ISD::OR:
9929     return performOrCombine(N, DCI);
9930   case ISD::XOR:
9931     return performXorCombine(N, DCI);
9932   case ISD::ZERO_EXTEND:
9933     return performZeroExtendCombine(N, DCI);
9934   case ISD::SIGN_EXTEND_INREG:
9935     return performSignExtendInRegCombine(N , DCI);
9936   case AMDGPUISD::FP_CLASS:
9937     return performClassCombine(N, DCI);
9938   case ISD::FCANONICALIZE:
9939     return performFCanonicalizeCombine(N, DCI);
9940   case AMDGPUISD::RCP:
9941     return performRcpCombine(N, DCI);
9942   case AMDGPUISD::FRACT:
9943   case AMDGPUISD::RSQ:
9944   case AMDGPUISD::RCP_LEGACY:
9945   case AMDGPUISD::RSQ_LEGACY:
9946   case AMDGPUISD::RCP_IFLAG:
9947   case AMDGPUISD::RSQ_CLAMP:
9948   case AMDGPUISD::LDEXP: {
9949     SDValue Src = N->getOperand(0);
9950     if (Src.isUndef())
9951       return Src;
9952     break;
9953   }
9954   case ISD::SINT_TO_FP:
9955   case ISD::UINT_TO_FP:
9956     return performUCharToFloatCombine(N, DCI);
9957   case AMDGPUISD::CVT_F32_UBYTE0:
9958   case AMDGPUISD::CVT_F32_UBYTE1:
9959   case AMDGPUISD::CVT_F32_UBYTE2:
9960   case AMDGPUISD::CVT_F32_UBYTE3:
9961     return performCvtF32UByteNCombine(N, DCI);
9962   case AMDGPUISD::FMED3:
9963     return performFMed3Combine(N, DCI);
9964   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9965     return performCvtPkRTZCombine(N, DCI);
9966   case AMDGPUISD::CLAMP:
9967     return performClampCombine(N, DCI);
9968   case ISD::SCALAR_TO_VECTOR: {
9969     SelectionDAG &DAG = DCI.DAG;
9970     EVT VT = N->getValueType(0);
9971 
9972     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
9973     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
9974       SDLoc SL(N);
9975       SDValue Src = N->getOperand(0);
9976       EVT EltVT = Src.getValueType();
9977       if (EltVT == MVT::f16)
9978         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
9979 
9980       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
9981       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
9982     }
9983 
9984     break;
9985   }
9986   case ISD::EXTRACT_VECTOR_ELT:
9987     return performExtractVectorEltCombine(N, DCI);
9988   case ISD::INSERT_VECTOR_ELT:
9989     return performInsertVectorEltCombine(N, DCI);
9990   }
9991   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9992 }
9993 
9994 /// Helper function for adjustWritemask
9995 static unsigned SubIdx2Lane(unsigned Idx) {
9996   switch (Idx) {
9997   default: return 0;
9998   case AMDGPU::sub0: return 0;
9999   case AMDGPU::sub1: return 1;
10000   case AMDGPU::sub2: return 2;
10001   case AMDGPU::sub3: return 3;
10002   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10003   }
10004 }
10005 
10006 /// Adjust the writemask of MIMG instructions
10007 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10008                                           SelectionDAG &DAG) const {
10009   unsigned Opcode = Node->getMachineOpcode();
10010 
10011   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10012   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10013   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10014     return Node; // not implemented for D16
10015 
10016   SDNode *Users[5] = { nullptr };
10017   unsigned Lane = 0;
10018   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10019   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10020   unsigned NewDmask = 0;
10021   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10022   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10023   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10024                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10025   unsigned TFCLane = 0;
10026   bool HasChain = Node->getNumValues() > 1;
10027 
10028   if (OldDmask == 0) {
10029     // These are folded out, but on the chance it happens don't assert.
10030     return Node;
10031   }
10032 
10033   unsigned OldBitsSet = countPopulation(OldDmask);
10034   // Work out which is the TFE/LWE lane if that is enabled.
10035   if (UsesTFC) {
10036     TFCLane = OldBitsSet;
10037   }
10038 
10039   // Try to figure out the used register components
10040   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10041        I != E; ++I) {
10042 
10043     // Don't look at users of the chain.
10044     if (I.getUse().getResNo() != 0)
10045       continue;
10046 
10047     // Abort if we can't understand the usage
10048     if (!I->isMachineOpcode() ||
10049         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10050       return Node;
10051 
10052     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10053     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10054     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10055     // set, etc.
10056     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10057 
10058     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10059     if (UsesTFC && Lane == TFCLane) {
10060       Users[Lane] = *I;
10061     } else {
10062       // Set which texture component corresponds to the lane.
10063       unsigned Comp;
10064       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10065         Comp = countTrailingZeros(Dmask);
10066         Dmask &= ~(1 << Comp);
10067       }
10068 
10069       // Abort if we have more than one user per component.
10070       if (Users[Lane])
10071         return Node;
10072 
10073       Users[Lane] = *I;
10074       NewDmask |= 1 << Comp;
10075     }
10076   }
10077 
10078   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10079   bool NoChannels = !NewDmask;
10080   if (NoChannels) {
10081     if (!UsesTFC) {
10082       // No uses of the result and not using TFC. Then do nothing.
10083       return Node;
10084     }
10085     // If the original dmask has one channel - then nothing to do
10086     if (OldBitsSet == 1)
10087       return Node;
10088     // Use an arbitrary dmask - required for the instruction to work
10089     NewDmask = 1;
10090   }
10091   // Abort if there's no change
10092   if (NewDmask == OldDmask)
10093     return Node;
10094 
10095   unsigned BitsSet = countPopulation(NewDmask);
10096 
10097   // Check for TFE or LWE - increase the number of channels by one to account
10098   // for the extra return value
10099   // This will need adjustment for D16 if this is also included in
10100   // adjustWriteMask (this function) but at present D16 are excluded.
10101   unsigned NewChannels = BitsSet + UsesTFC;
10102 
10103   int NewOpcode =
10104       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10105   assert(NewOpcode != -1 &&
10106          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10107          "failed to find equivalent MIMG op");
10108 
10109   // Adjust the writemask in the node
10110   SmallVector<SDValue, 12> Ops;
10111   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10112   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10113   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10114 
10115   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10116 
10117   MVT ResultVT = NewChannels == 1 ?
10118     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10119                            NewChannels == 5 ? 8 : NewChannels);
10120   SDVTList NewVTList = HasChain ?
10121     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10122 
10123 
10124   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10125                                               NewVTList, Ops);
10126 
10127   if (HasChain) {
10128     // Update chain.
10129     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10130     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10131   }
10132 
10133   if (NewChannels == 1) {
10134     assert(Node->hasNUsesOfValue(1, 0));
10135     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10136                                       SDLoc(Node), Users[Lane]->getValueType(0),
10137                                       SDValue(NewNode, 0));
10138     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10139     return nullptr;
10140   }
10141 
10142   // Update the users of the node with the new indices
10143   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10144     SDNode *User = Users[i];
10145     if (!User) {
10146       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10147       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10148       if (i || !NoChannels)
10149         continue;
10150     } else {
10151       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10152       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10153     }
10154 
10155     switch (Idx) {
10156     default: break;
10157     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10158     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10159     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10160     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10161     }
10162   }
10163 
10164   DAG.RemoveDeadNode(Node);
10165   return nullptr;
10166 }
10167 
10168 static bool isFrameIndexOp(SDValue Op) {
10169   if (Op.getOpcode() == ISD::AssertZext)
10170     Op = Op.getOperand(0);
10171 
10172   return isa<FrameIndexSDNode>(Op);
10173 }
10174 
10175 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10176 /// with frame index operands.
10177 /// LLVM assumes that inputs are to these instructions are registers.
10178 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10179                                                         SelectionDAG &DAG) const {
10180   if (Node->getOpcode() == ISD::CopyToReg) {
10181     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10182     SDValue SrcVal = Node->getOperand(2);
10183 
10184     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10185     // to try understanding copies to physical registers.
10186     if (SrcVal.getValueType() == MVT::i1 &&
10187         Register::isPhysicalRegister(DestReg->getReg())) {
10188       SDLoc SL(Node);
10189       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10190       SDValue VReg = DAG.getRegister(
10191         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10192 
10193       SDNode *Glued = Node->getGluedNode();
10194       SDValue ToVReg
10195         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10196                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10197       SDValue ToResultReg
10198         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10199                            VReg, ToVReg.getValue(1));
10200       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10201       DAG.RemoveDeadNode(Node);
10202       return ToResultReg.getNode();
10203     }
10204   }
10205 
10206   SmallVector<SDValue, 8> Ops;
10207   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10208     if (!isFrameIndexOp(Node->getOperand(i))) {
10209       Ops.push_back(Node->getOperand(i));
10210       continue;
10211     }
10212 
10213     SDLoc DL(Node);
10214     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10215                                      Node->getOperand(i).getValueType(),
10216                                      Node->getOperand(i)), 0));
10217   }
10218 
10219   return DAG.UpdateNodeOperands(Node, Ops);
10220 }
10221 
10222 /// Fold the instructions after selecting them.
10223 /// Returns null if users were already updated.
10224 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10225                                           SelectionDAG &DAG) const {
10226   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10227   unsigned Opcode = Node->getMachineOpcode();
10228 
10229   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10230       !TII->isGather4(Opcode)) {
10231     return adjustWritemask(Node, DAG);
10232   }
10233 
10234   if (Opcode == AMDGPU::INSERT_SUBREG ||
10235       Opcode == AMDGPU::REG_SEQUENCE) {
10236     legalizeTargetIndependentNode(Node, DAG);
10237     return Node;
10238   }
10239 
10240   switch (Opcode) {
10241   case AMDGPU::V_DIV_SCALE_F32:
10242   case AMDGPU::V_DIV_SCALE_F64: {
10243     // Satisfy the operand register constraint when one of the inputs is
10244     // undefined. Ordinarily each undef value will have its own implicit_def of
10245     // a vreg, so force these to use a single register.
10246     SDValue Src0 = Node->getOperand(0);
10247     SDValue Src1 = Node->getOperand(1);
10248     SDValue Src2 = Node->getOperand(2);
10249 
10250     if ((Src0.isMachineOpcode() &&
10251          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10252         (Src0 == Src1 || Src0 == Src2))
10253       break;
10254 
10255     MVT VT = Src0.getValueType().getSimpleVT();
10256     const TargetRegisterClass *RC =
10257         getRegClassFor(VT, Src0.getNode()->isDivergent());
10258 
10259     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10260     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10261 
10262     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10263                                       UndefReg, Src0, SDValue());
10264 
10265     // src0 must be the same register as src1 or src2, even if the value is
10266     // undefined, so make sure we don't violate this constraint.
10267     if (Src0.isMachineOpcode() &&
10268         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10269       if (Src1.isMachineOpcode() &&
10270           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10271         Src0 = Src1;
10272       else if (Src2.isMachineOpcode() &&
10273                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10274         Src0 = Src2;
10275       else {
10276         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10277         Src0 = UndefReg;
10278         Src1 = UndefReg;
10279       }
10280     } else
10281       break;
10282 
10283     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10284     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10285       Ops.push_back(Node->getOperand(I));
10286 
10287     Ops.push_back(ImpDef.getValue(1));
10288     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10289   }
10290   case AMDGPU::V_PERMLANE16_B32:
10291   case AMDGPU::V_PERMLANEX16_B32: {
10292     ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0));
10293     ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2));
10294     if (!FI->getZExtValue() && !BC->getZExtValue())
10295       break;
10296     SDValue VDstIn = Node->getOperand(6);
10297     if (VDstIn.isMachineOpcode()
10298         && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)
10299       break;
10300     MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
10301                                                SDLoc(Node), MVT::i32);
10302     SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1),
10303                                     SDValue(BC, 0), Node->getOperand(3),
10304                                     Node->getOperand(4), Node->getOperand(5),
10305                                     SDValue(ImpDef, 0), Node->getOperand(7) };
10306     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10307   }
10308   default:
10309     break;
10310   }
10311 
10312   return Node;
10313 }
10314 
10315 /// Assign the register class depending on the number of
10316 /// bits set in the writemask
10317 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10318                                                      SDNode *Node) const {
10319   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10320 
10321   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10322 
10323   if (TII->isVOP3(MI.getOpcode())) {
10324     // Make sure constant bus requirements are respected.
10325     TII->legalizeOperandsVOP3(MRI, MI);
10326 
10327     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10328     // This saves a chain-copy of registers and better ballance register
10329     // use between vgpr and agpr as agpr tuples tend to be big.
10330     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10331       unsigned Opc = MI.getOpcode();
10332       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10333       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10334                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10335         if (I == -1)
10336           break;
10337         MachineOperand &Op = MI.getOperand(I);
10338         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10339              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10340             !Register::isVirtualRegister(Op.getReg()) ||
10341             !TRI->isAGPR(MRI, Op.getReg()))
10342           continue;
10343         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10344         if (!Src || !Src->isCopy() ||
10345             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10346           continue;
10347         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10348         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10349         // All uses of agpr64 and agpr32 can also accept vgpr except for
10350         // v_accvgpr_read, but we do not produce agpr reads during selection,
10351         // so no use checks are needed.
10352         MRI.setRegClass(Op.getReg(), NewRC);
10353       }
10354     }
10355 
10356     return;
10357   }
10358 
10359   // Replace unused atomics with the no return version.
10360   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10361   if (NoRetAtomicOp != -1) {
10362     if (!Node->hasAnyUseOfValue(0)) {
10363       MI.setDesc(TII->get(NoRetAtomicOp));
10364       MI.RemoveOperand(0);
10365       return;
10366     }
10367 
10368     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10369     // instruction, because the return type of these instructions is a vec2 of
10370     // the memory type, so it can be tied to the input operand.
10371     // This means these instructions always have a use, so we need to add a
10372     // special case to check if the atomic has only one extract_subreg use,
10373     // which itself has no uses.
10374     if ((Node->hasNUsesOfValue(1, 0) &&
10375          Node->use_begin()->isMachineOpcode() &&
10376          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10377          !Node->use_begin()->hasAnyUseOfValue(0))) {
10378       unsigned Def = MI.getOperand(0).getReg();
10379 
10380       // Change this into a noret atomic.
10381       MI.setDesc(TII->get(NoRetAtomicOp));
10382       MI.RemoveOperand(0);
10383 
10384       // If we only remove the def operand from the atomic instruction, the
10385       // extract_subreg will be left with a use of a vreg without a def.
10386       // So we need to insert an implicit_def to avoid machine verifier
10387       // errors.
10388       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10389               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10390     }
10391     return;
10392   }
10393 }
10394 
10395 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10396                               uint64_t Val) {
10397   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10398   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10399 }
10400 
10401 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10402                                                 const SDLoc &DL,
10403                                                 SDValue Ptr) const {
10404   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10405 
10406   // Build the half of the subregister with the constants before building the
10407   // full 128-bit register. If we are building multiple resource descriptors,
10408   // this will allow CSEing of the 2-component register.
10409   const SDValue Ops0[] = {
10410     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10411     buildSMovImm32(DAG, DL, 0),
10412     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10413     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10414     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10415   };
10416 
10417   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10418                                                 MVT::v2i32, Ops0), 0);
10419 
10420   // Combine the constants and the pointer.
10421   const SDValue Ops1[] = {
10422     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
10423     Ptr,
10424     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10425     SubRegHi,
10426     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10427   };
10428 
10429   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10430 }
10431 
10432 /// Return a resource descriptor with the 'Add TID' bit enabled
10433 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10434 ///        of the resource descriptor) to create an offset, which is added to
10435 ///        the resource pointer.
10436 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10437                                            SDValue Ptr, uint32_t RsrcDword1,
10438                                            uint64_t RsrcDword2And3) const {
10439   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10440   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10441   if (RsrcDword1) {
10442     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10443                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10444                     0);
10445   }
10446 
10447   SDValue DataLo = buildSMovImm32(DAG, DL,
10448                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10449   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10450 
10451   const SDValue Ops[] = {
10452     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
10453     PtrLo,
10454     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10455     PtrHi,
10456     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10457     DataLo,
10458     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10459     DataHi,
10460     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10461   };
10462 
10463   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10464 }
10465 
10466 //===----------------------------------------------------------------------===//
10467 //                         SI Inline Assembly Support
10468 //===----------------------------------------------------------------------===//
10469 
10470 std::pair<unsigned, const TargetRegisterClass *>
10471 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10472                                                StringRef Constraint,
10473                                                MVT VT) const {
10474   const TargetRegisterClass *RC = nullptr;
10475   if (Constraint.size() == 1) {
10476     switch (Constraint[0]) {
10477     default:
10478       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10479     case 's':
10480     case 'r':
10481       switch (VT.getSizeInBits()) {
10482       default:
10483         return std::make_pair(0U, nullptr);
10484       case 32:
10485       case 16:
10486         RC = &AMDGPU::SReg_32_XM0RegClass;
10487         break;
10488       case 64:
10489         RC = &AMDGPU::SGPR_64RegClass;
10490         break;
10491       case 96:
10492         RC = &AMDGPU::SReg_96RegClass;
10493         break;
10494       case 128:
10495         RC = &AMDGPU::SReg_128RegClass;
10496         break;
10497       case 160:
10498         RC = &AMDGPU::SReg_160RegClass;
10499         break;
10500       case 256:
10501         RC = &AMDGPU::SReg_256RegClass;
10502         break;
10503       case 512:
10504         RC = &AMDGPU::SReg_512RegClass;
10505         break;
10506       }
10507       break;
10508     case 'v':
10509       switch (VT.getSizeInBits()) {
10510       default:
10511         return std::make_pair(0U, nullptr);
10512       case 32:
10513       case 16:
10514         RC = &AMDGPU::VGPR_32RegClass;
10515         break;
10516       case 64:
10517         RC = &AMDGPU::VReg_64RegClass;
10518         break;
10519       case 96:
10520         RC = &AMDGPU::VReg_96RegClass;
10521         break;
10522       case 128:
10523         RC = &AMDGPU::VReg_128RegClass;
10524         break;
10525       case 160:
10526         RC = &AMDGPU::VReg_160RegClass;
10527         break;
10528       case 256:
10529         RC = &AMDGPU::VReg_256RegClass;
10530         break;
10531       case 512:
10532         RC = &AMDGPU::VReg_512RegClass;
10533         break;
10534       }
10535       break;
10536     case 'a':
10537       if (!Subtarget->hasMAIInsts())
10538         break;
10539       switch (VT.getSizeInBits()) {
10540       default:
10541         return std::make_pair(0U, nullptr);
10542       case 32:
10543       case 16:
10544         RC = &AMDGPU::AGPR_32RegClass;
10545         break;
10546       case 64:
10547         RC = &AMDGPU::AReg_64RegClass;
10548         break;
10549       case 128:
10550         RC = &AMDGPU::AReg_128RegClass;
10551         break;
10552       case 512:
10553         RC = &AMDGPU::AReg_512RegClass;
10554         break;
10555       case 1024:
10556         RC = &AMDGPU::AReg_1024RegClass;
10557         // v32 types are not legal but we support them here.
10558         return std::make_pair(0U, RC);
10559       }
10560       break;
10561     }
10562     // We actually support i128, i16 and f16 as inline parameters
10563     // even if they are not reported as legal
10564     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10565                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10566       return std::make_pair(0U, RC);
10567   }
10568 
10569   if (Constraint.size() > 1) {
10570     if (Constraint[1] == 'v') {
10571       RC = &AMDGPU::VGPR_32RegClass;
10572     } else if (Constraint[1] == 's') {
10573       RC = &AMDGPU::SGPR_32RegClass;
10574     } else if (Constraint[1] == 'a') {
10575       RC = &AMDGPU::AGPR_32RegClass;
10576     }
10577 
10578     if (RC) {
10579       uint32_t Idx;
10580       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10581       if (!Failed && Idx < RC->getNumRegs())
10582         return std::make_pair(RC->getRegister(Idx), RC);
10583     }
10584   }
10585   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10586 }
10587 
10588 SITargetLowering::ConstraintType
10589 SITargetLowering::getConstraintType(StringRef Constraint) const {
10590   if (Constraint.size() == 1) {
10591     switch (Constraint[0]) {
10592     default: break;
10593     case 's':
10594     case 'v':
10595     case 'a':
10596       return C_RegisterClass;
10597     }
10598   }
10599   return TargetLowering::getConstraintType(Constraint);
10600 }
10601 
10602 // Figure out which registers should be reserved for stack access. Only after
10603 // the function is legalized do we know all of the non-spill stack objects or if
10604 // calls are present.
10605 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10606   MachineRegisterInfo &MRI = MF.getRegInfo();
10607   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10608   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10609   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10610 
10611   if (Info->isEntryFunction()) {
10612     // Callable functions have fixed registers used for stack access.
10613     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10614   }
10615 
10616   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10617                              Info->getStackPtrOffsetReg()));
10618   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10619     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10620 
10621   // We need to worry about replacing the default register with itself in case
10622   // of MIR testcases missing the MFI.
10623   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10624     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10625 
10626   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10627     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10628 
10629   if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
10630     MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
10631                        Info->getScratchWaveOffsetReg());
10632   }
10633 
10634   Info->limitOccupancy(MF);
10635 
10636   if (ST.isWave32() && !MF.empty()) {
10637     // Add VCC_HI def because many instructions marked as imp-use VCC where
10638     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10639     // having a use of undef.
10640 
10641     const SIInstrInfo *TII = ST.getInstrInfo();
10642     DebugLoc DL;
10643 
10644     MachineBasicBlock &MBB = MF.front();
10645     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10646     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10647 
10648     for (auto &MBB : MF) {
10649       for (auto &MI : MBB) {
10650         TII->fixImplicitOperands(MI);
10651       }
10652     }
10653   }
10654 
10655   TargetLoweringBase::finalizeLowering(MF);
10656 }
10657 
10658 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10659                                                      KnownBits &Known,
10660                                                      const APInt &DemandedElts,
10661                                                      const SelectionDAG &DAG,
10662                                                      unsigned Depth) const {
10663   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10664                                                 DAG, Depth);
10665 
10666   // Set the high bits to zero based on the maximum allowed scratch size per
10667   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10668   // calculation won't overflow, so assume the sign bit is never set.
10669   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10670 }
10671 
10672 unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10673   const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10674   const unsigned CacheLineAlign = 6; // log2(64)
10675 
10676   // Pre-GFX10 target did not benefit from loop alignment
10677   if (!ML || DisableLoopAlignment ||
10678       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10679       getSubtarget()->hasInstFwdPrefetchBug())
10680     return PrefAlign;
10681 
10682   // On GFX10 I$ is 4 x 64 bytes cache lines.
10683   // By default prefetcher keeps one cache line behind and reads two ahead.
10684   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10685   // behind and one ahead.
10686   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10687   // If loop fits 64 bytes it always spans no more than two cache lines and
10688   // does not need an alignment.
10689   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10690   // Else if loop is less or equal 192 bytes we need two lines behind.
10691 
10692   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10693   const MachineBasicBlock *Header = ML->getHeader();
10694   if (Header->getAlignment() != PrefAlign)
10695     return Header->getAlignment(); // Already processed.
10696 
10697   unsigned LoopSize = 0;
10698   for (const MachineBasicBlock *MBB : ML->blocks()) {
10699     // If inner loop block is aligned assume in average half of the alignment
10700     // size to be added as nops.
10701     if (MBB != Header)
10702       LoopSize += (1 << MBB->getAlignment()) / 2;
10703 
10704     for (const MachineInstr &MI : *MBB) {
10705       LoopSize += TII->getInstSizeInBytes(MI);
10706       if (LoopSize > 192)
10707         return PrefAlign;
10708     }
10709   }
10710 
10711   if (LoopSize <= 64)
10712     return PrefAlign;
10713 
10714   if (LoopSize <= 128)
10715     return CacheLineAlign;
10716 
10717   // If any of parent loops is surrounded by prefetch instructions do not
10718   // insert new for inner loop, which would reset parent's settings.
10719   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10720     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10721       auto I = Exit->getFirstNonDebugInstr();
10722       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10723         return CacheLineAlign;
10724     }
10725   }
10726 
10727   MachineBasicBlock *Pre = ML->getLoopPreheader();
10728   MachineBasicBlock *Exit = ML->getExitBlock();
10729 
10730   if (Pre && Exit) {
10731     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10732             TII->get(AMDGPU::S_INST_PREFETCH))
10733       .addImm(1); // prefetch 2 lines behind PC
10734 
10735     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10736             TII->get(AMDGPU::S_INST_PREFETCH))
10737       .addImm(2); // prefetch 1 line behind PC
10738   }
10739 
10740   return CacheLineAlign;
10741 }
10742 
10743 LLVM_ATTRIBUTE_UNUSED
10744 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10745   assert(N->getOpcode() == ISD::CopyFromReg);
10746   do {
10747     // Follow the chain until we find an INLINEASM node.
10748     N = N->getOperand(0).getNode();
10749     if (N->getOpcode() == ISD::INLINEASM ||
10750         N->getOpcode() == ISD::INLINEASM_BR)
10751       return true;
10752   } while (N->getOpcode() == ISD::CopyFromReg);
10753   return false;
10754 }
10755 
10756 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10757   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10758 {
10759   switch (N->getOpcode()) {
10760     case ISD::CopyFromReg:
10761     {
10762       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10763       const MachineFunction * MF = FLI->MF;
10764       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10765       const MachineRegisterInfo &MRI = MF->getRegInfo();
10766       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10767       unsigned Reg = R->getReg();
10768       if (Register::isPhysicalRegister(Reg))
10769         return !TRI.isSGPRReg(MRI, Reg);
10770 
10771       if (MRI.isLiveIn(Reg)) {
10772         // workitem.id.x workitem.id.y workitem.id.z
10773         // Any VGPR formal argument is also considered divergent
10774         if (!TRI.isSGPRReg(MRI, Reg))
10775           return true;
10776         // Formal arguments of non-entry functions
10777         // are conservatively considered divergent
10778         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10779           return true;
10780         return false;
10781       }
10782       const Value *V = FLI->getValueFromVirtualReg(Reg);
10783       if (V)
10784         return KDA->isDivergent(V);
10785       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10786       return !TRI.isSGPRReg(MRI, Reg);
10787     }
10788     break;
10789     case ISD::LOAD: {
10790       const LoadSDNode *L = cast<LoadSDNode>(N);
10791       unsigned AS = L->getAddressSpace();
10792       // A flat load may access private memory.
10793       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10794     } break;
10795     case ISD::CALLSEQ_END:
10796     return true;
10797     break;
10798     case ISD::INTRINSIC_WO_CHAIN:
10799     {
10800 
10801     }
10802       return AMDGPU::isIntrinsicSourceOfDivergence(
10803       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10804     case ISD::INTRINSIC_W_CHAIN:
10805       return AMDGPU::isIntrinsicSourceOfDivergence(
10806       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10807     // In some cases intrinsics that are a source of divergence have been
10808     // lowered to AMDGPUISD so we also need to check those too.
10809     case AMDGPUISD::INTERP_MOV:
10810     case AMDGPUISD::INTERP_P1:
10811     case AMDGPUISD::INTERP_P2:
10812       return true;
10813   }
10814   return false;
10815 }
10816 
10817 bool SITargetLowering::denormalsEnabledForType(EVT VT) const {
10818   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10819   case MVT::f32:
10820     return Subtarget->hasFP32Denormals();
10821   case MVT::f64:
10822     return Subtarget->hasFP64Denormals();
10823   case MVT::f16:
10824     return Subtarget->hasFP16Denormals();
10825   default:
10826     return false;
10827   }
10828 }
10829 
10830 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10831                                                     const SelectionDAG &DAG,
10832                                                     bool SNaN,
10833                                                     unsigned Depth) const {
10834   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10835     const MachineFunction &MF = DAG.getMachineFunction();
10836     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10837 
10838     if (Info->getMode().DX10Clamp)
10839       return true; // Clamped to 0.
10840     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10841   }
10842 
10843   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10844                                                             SNaN, Depth);
10845 }
10846 
10847 TargetLowering::AtomicExpansionKind
10848 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10849   switch (RMW->getOperation()) {
10850   case AtomicRMWInst::FAdd: {
10851     Type *Ty = RMW->getType();
10852 
10853     // We don't have a way to support 16-bit atomics now, so just leave them
10854     // as-is.
10855     if (Ty->isHalfTy())
10856       return AtomicExpansionKind::None;
10857 
10858     if (!Ty->isFloatTy())
10859       return AtomicExpansionKind::CmpXChg;
10860 
10861     // TODO: Do have these for flat. Older targets also had them for buffers.
10862     unsigned AS = RMW->getPointerAddressSpace();
10863     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10864       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10865   }
10866   default:
10867     break;
10868   }
10869 
10870   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10871 }
10872