1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifdef _MSC_VER
16 // Provide M_PI.
17 #define _USE_MATH_DEFINES
18 #endif
19 
20 #include "SIISelLowering.h"
21 #include "AMDGPU.h"
22 #include "AMDGPUIntrinsicInfo.h"
23 #include "AMDGPUSubtarget.h"
24 #include "AMDGPUTargetMachine.h"
25 #include "SIDefines.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
30 #include "Utils/AMDGPUBaseInfo.h"
31 #include "llvm/ADT/APFloat.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Twine.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/CallingConvLower.h"
42 #include "llvm/CodeGen/DAGCombine.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
93 static cl::opt<bool> EnableVGPRIndexMode(
94   "amdgpu-vgpr-index-mode",
95   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
96   cl::init(false));
97 
98 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
99   "amdgpu-frame-index-zero-bits",
100   cl::desc("High bits of frame index assumed to be zero"),
101   cl::init(5),
102   cl::ReallyHidden);
103 
104 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
105   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
106   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
107     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
108       return AMDGPU::SGPR0 + Reg;
109     }
110   }
111   llvm_unreachable("Cannot allocate sgpr");
112 }
113 
114 SITargetLowering::SITargetLowering(const TargetMachine &TM,
115                                    const GCNSubtarget &STI)
116     : AMDGPUTargetLowering(TM, STI),
117       Subtarget(&STI) {
118   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
119   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
120 
121   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
122   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
123 
124   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
125   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
126   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
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::v8i32, &AMDGPU::SReg_256RegClass);
135   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
136 
137   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
138   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
139 
140   if (Subtarget->has16BitInsts()) {
141     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
142     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
143 
144     // Unless there are also VOP3P operations, not operations are really legal.
145     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
146     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
147     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
148     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
149   }
150 
151   computeRegisterProperties(Subtarget->getRegisterInfo());
152 
153   // We need to custom lower vector stores from local memory
154   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
155   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::i1, Custom);
159 
160   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
161   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
162   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
163   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
164   setOperationAction(ISD::STORE, MVT::i1, Custom);
165 
166   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
167   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
168   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
169   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
170   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
171   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
172   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
173   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
174   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
175   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
176 
177   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
178   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
179 
180   setOperationAction(ISD::SELECT, MVT::i1, Promote);
181   setOperationAction(ISD::SELECT, MVT::i64, Custom);
182   setOperationAction(ISD::SELECT, MVT::f64, Promote);
183   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
184 
185   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
186   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
187   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
188   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
189   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
190 
191   setOperationAction(ISD::SETCC, MVT::i1, Promote);
192   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
193   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
194   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
195 
196   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
197   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
198 
199   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
200   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
201   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
202   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
203   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
204   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
205   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
206 
207   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
208   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
209   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
210   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
211   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
212 
213   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
214   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
215   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
216 
217   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
218   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
219   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
220   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
221 
222   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
223   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
224   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
225   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
226   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
227   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
228 
229   setOperationAction(ISD::UADDO, MVT::i32, Legal);
230   setOperationAction(ISD::USUBO, MVT::i32, Legal);
231 
232   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
233   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
234 
235 #if 0
236   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
237   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
238 #endif
239 
240   // We only support LOAD/STORE and vector manipulation ops for vectors
241   // with > 4 elements.
242   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
243         MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16 }) {
244     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
245       switch (Op) {
246       case ISD::LOAD:
247       case ISD::STORE:
248       case ISD::BUILD_VECTOR:
249       case ISD::BITCAST:
250       case ISD::EXTRACT_VECTOR_ELT:
251       case ISD::INSERT_VECTOR_ELT:
252       case ISD::INSERT_SUBVECTOR:
253       case ISD::EXTRACT_SUBVECTOR:
254       case ISD::SCALAR_TO_VECTOR:
255         break;
256       case ISD::CONCAT_VECTORS:
257         setOperationAction(Op, VT, Custom);
258         break;
259       default:
260         setOperationAction(Op, VT, Expand);
261         break;
262       }
263     }
264   }
265 
266   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
267 
268   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
269   // is expanded to avoid having two separate loops in case the index is a VGPR.
270 
271   // Most operations are naturally 32-bit vector operations. We only support
272   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
273   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
274     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
275     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
276 
277     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
278     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
279 
280     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
281     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
282 
283     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
284     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
285   }
286 
287   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
288   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
289   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
290   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
291 
292   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
293   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
294 
295   // Avoid stack access for these.
296   // TODO: Generalize to more vector types.
297   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
298   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
299   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
300   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
301 
302   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
303   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
304   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
305   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
306   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
307 
308   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
309   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
310   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
311 
312   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
313   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
314   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
315   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
316 
317   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
318   // and output demarshalling
319   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
320   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
321 
322   // We can't return success/failure, only the old value,
323   // let LLVM add the comparison
324   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
325   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
326 
327   if (Subtarget->hasFlatAddressSpace()) {
328     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
329     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
330   }
331 
332   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
333   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
334 
335   // On SI this is s_memtime and s_memrealtime on VI.
336   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
337   setOperationAction(ISD::TRAP, MVT::Other, Custom);
338   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
339 
340   if (Subtarget->has16BitInsts()) {
341     setOperationAction(ISD::FLOG, MVT::f16, Custom);
342     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
343   }
344 
345   // v_mad_f32 does not support denormals according to some sources.
346   if (!Subtarget->hasFP32Denormals())
347     setOperationAction(ISD::FMAD, MVT::f32, Legal);
348 
349   if (!Subtarget->hasBFI()) {
350     // fcopysign can be done in a single instruction with BFI.
351     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
352     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
353   }
354 
355   if (!Subtarget->hasBCNT(32))
356     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
357 
358   if (!Subtarget->hasBCNT(64))
359     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
360 
361   if (Subtarget->hasFFBH())
362     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
363 
364   if (Subtarget->hasFFBL())
365     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
366 
367   // We only really have 32-bit BFE instructions (and 16-bit on VI).
368   //
369   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
370   // effort to match them now. We want this to be false for i64 cases when the
371   // extraction isn't restricted to the upper or lower half. Ideally we would
372   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
373   // span the midpoint are probably relatively rare, so don't worry about them
374   // for now.
375   if (Subtarget->hasBFE())
376     setHasExtractBitsInsn(true);
377 
378   setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
379   setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
380 
381   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
382     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
383     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
384     setOperationAction(ISD::FRINT, MVT::f64, Legal);
385   } else {
386     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
387     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
388     setOperationAction(ISD::FRINT, MVT::f64, Custom);
389     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
390   }
391 
392   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
393 
394   setOperationAction(ISD::FSIN, MVT::f32, Custom);
395   setOperationAction(ISD::FCOS, MVT::f32, Custom);
396   setOperationAction(ISD::FDIV, MVT::f32, Custom);
397   setOperationAction(ISD::FDIV, MVT::f64, Custom);
398 
399   if (Subtarget->has16BitInsts()) {
400     setOperationAction(ISD::Constant, MVT::i16, Legal);
401 
402     setOperationAction(ISD::SMIN, MVT::i16, Legal);
403     setOperationAction(ISD::SMAX, MVT::i16, Legal);
404 
405     setOperationAction(ISD::UMIN, MVT::i16, Legal);
406     setOperationAction(ISD::UMAX, MVT::i16, Legal);
407 
408     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
409     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
410 
411     setOperationAction(ISD::ROTR, MVT::i16, Promote);
412     setOperationAction(ISD::ROTL, MVT::i16, Promote);
413 
414     setOperationAction(ISD::SDIV, MVT::i16, Promote);
415     setOperationAction(ISD::UDIV, MVT::i16, Promote);
416     setOperationAction(ISD::SREM, MVT::i16, Promote);
417     setOperationAction(ISD::UREM, MVT::i16, Promote);
418 
419     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
420     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
421 
422     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
423     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
424     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
425     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
426     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
427 
428     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
429 
430     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
431 
432     setOperationAction(ISD::LOAD, MVT::i16, Custom);
433 
434     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
435 
436     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
437     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
438     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
439     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
440 
441     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
442     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
443     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
444     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
445 
446     // F16 - Constant Actions.
447     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
448 
449     // F16 - Load/Store Actions.
450     setOperationAction(ISD::LOAD, MVT::f16, Promote);
451     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
452     setOperationAction(ISD::STORE, MVT::f16, Promote);
453     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
454 
455     // F16 - VOP1 Actions.
456     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
457     setOperationAction(ISD::FCOS, MVT::f16, Promote);
458     setOperationAction(ISD::FSIN, MVT::f16, Promote);
459     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
460     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
461     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
462     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
463     setOperationAction(ISD::FROUND, MVT::f16, Custom);
464 
465     // F16 - VOP2 Actions.
466     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
467     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
468     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
469     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
470     setOperationAction(ISD::FDIV, MVT::f16, Custom);
471 
472     // F16 - VOP3 Actions.
473     setOperationAction(ISD::FMA, MVT::f16, Legal);
474     if (!Subtarget->hasFP16Denormals())
475       setOperationAction(ISD::FMAD, MVT::f16, Legal);
476 
477     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
478       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
479         switch (Op) {
480         case ISD::LOAD:
481         case ISD::STORE:
482         case ISD::BUILD_VECTOR:
483         case ISD::BITCAST:
484         case ISD::EXTRACT_VECTOR_ELT:
485         case ISD::INSERT_VECTOR_ELT:
486         case ISD::INSERT_SUBVECTOR:
487         case ISD::EXTRACT_SUBVECTOR:
488         case ISD::SCALAR_TO_VECTOR:
489           break;
490         case ISD::CONCAT_VECTORS:
491           setOperationAction(Op, VT, Custom);
492           break;
493         default:
494           setOperationAction(Op, VT, Expand);
495           break;
496         }
497       }
498     }
499 
500     // XXX - Do these do anything? Vector constants turn into build_vector.
501     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
502     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
503 
504     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
505     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
506 
507     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
508     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
509     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
510     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
511 
512     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
513     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
514     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
515     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
516 
517     setOperationAction(ISD::AND, MVT::v2i16, Promote);
518     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
519     setOperationAction(ISD::OR, MVT::v2i16, Promote);
520     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
521     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
522     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
523 
524     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
525     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
526     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
527     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
528 
529     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
530     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
531     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
532     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
533 
534     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
535     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
536     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
537     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
538 
539     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
540     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
541     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
542 
543     if (!Subtarget->hasVOP3PInsts()) {
544       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
545       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
546     }
547 
548     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
549     // This isn't really legal, but this avoids the legalizer unrolling it (and
550     // allows matching fneg (fabs x) patterns)
551     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
552   }
553 
554   if (Subtarget->hasVOP3PInsts()) {
555     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
556     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
557     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
558     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
559     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
560     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
561     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
562     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
563     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
564     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
565 
566     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
567     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
568     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
569     setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
570     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
571     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
572 
573     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
574     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
575 
576     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
577     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
578     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
579     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
580     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
581     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
582 
583     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
584     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
585     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
586     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
587 
588     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
589     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
590     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
591     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
592 
593     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
594     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
595   }
596 
597   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
598   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
599 
600   if (Subtarget->has16BitInsts()) {
601     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
602     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
603     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
604     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
605   } else {
606     // Legalization hack.
607     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
608     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
609 
610     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
611     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
612   }
613 
614   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
615     setOperationAction(ISD::SELECT, VT, Custom);
616   }
617 
618   setTargetDAGCombine(ISD::ADD);
619   setTargetDAGCombine(ISD::ADDCARRY);
620   setTargetDAGCombine(ISD::SUB);
621   setTargetDAGCombine(ISD::SUBCARRY);
622   setTargetDAGCombine(ISD::FADD);
623   setTargetDAGCombine(ISD::FSUB);
624   setTargetDAGCombine(ISD::FMINNUM);
625   setTargetDAGCombine(ISD::FMAXNUM);
626   setTargetDAGCombine(ISD::FMA);
627   setTargetDAGCombine(ISD::SMIN);
628   setTargetDAGCombine(ISD::SMAX);
629   setTargetDAGCombine(ISD::UMIN);
630   setTargetDAGCombine(ISD::UMAX);
631   setTargetDAGCombine(ISD::SETCC);
632   setTargetDAGCombine(ISD::AND);
633   setTargetDAGCombine(ISD::OR);
634   setTargetDAGCombine(ISD::XOR);
635   setTargetDAGCombine(ISD::SINT_TO_FP);
636   setTargetDAGCombine(ISD::UINT_TO_FP);
637   setTargetDAGCombine(ISD::FCANONICALIZE);
638   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
639   setTargetDAGCombine(ISD::ZERO_EXTEND);
640   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
641   setTargetDAGCombine(ISD::BUILD_VECTOR);
642 
643   // All memory operations. Some folding on the pointer operand is done to help
644   // matching the constant offsets in the addressing modes.
645   setTargetDAGCombine(ISD::LOAD);
646   setTargetDAGCombine(ISD::STORE);
647   setTargetDAGCombine(ISD::ATOMIC_LOAD);
648   setTargetDAGCombine(ISD::ATOMIC_STORE);
649   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
650   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
651   setTargetDAGCombine(ISD::ATOMIC_SWAP);
652   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
653   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
654   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
655   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
656   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
657   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
658   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
659   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
660   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
661   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
662 
663   setSchedulingPreference(Sched::RegPressure);
664 
665   // SI at least has hardware support for floating point exceptions, but no way
666   // of using or handling them is implemented. They are also optional in OpenCL
667   // (Section 7.3)
668   setHasFloatingPointExceptions(Subtarget->hasFPExceptions());
669 }
670 
671 const GCNSubtarget *SITargetLowering::getSubtarget() const {
672   return Subtarget;
673 }
674 
675 //===----------------------------------------------------------------------===//
676 // TargetLowering queries
677 //===----------------------------------------------------------------------===//
678 
679 // v_mad_mix* support a conversion from f16 to f32.
680 //
681 // There is only one special case when denormals are enabled we don't currently,
682 // where this is OK to use.
683 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
684                                            EVT DestVT, EVT SrcVT) const {
685   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
686           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
687          DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
688          SrcVT.getScalarType() == MVT::f16;
689 }
690 
691 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
692   // SI has some legal vector types, but no legal vector operations. Say no
693   // shuffles are legal in order to prefer scalarizing some vector operations.
694   return false;
695 }
696 
697 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
698                                           const CallInst &CI,
699                                           MachineFunction &MF,
700                                           unsigned IntrID) const {
701   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
702           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
703     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
704                                                   (Intrinsic::ID)IntrID);
705     if (Attr.hasFnAttribute(Attribute::ReadNone))
706       return false;
707 
708     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
709 
710     if (RsrcIntr->IsImage) {
711       Info.ptrVal = MFI->getImagePSV(
712         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
713         CI.getArgOperand(RsrcIntr->RsrcArg));
714       Info.align = 0;
715     } else {
716       Info.ptrVal = MFI->getBufferPSV(
717         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
718         CI.getArgOperand(RsrcIntr->RsrcArg));
719     }
720 
721     Info.flags = MachineMemOperand::MODereferenceable;
722     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
723       Info.opc = ISD::INTRINSIC_W_CHAIN;
724       Info.memVT = MVT::getVT(CI.getType());
725       Info.flags |= MachineMemOperand::MOLoad;
726     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
727       Info.opc = ISD::INTRINSIC_VOID;
728       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
729       Info.flags |= MachineMemOperand::MOStore;
730     } else {
731       // Atomic
732       Info.opc = ISD::INTRINSIC_W_CHAIN;
733       Info.memVT = MVT::getVT(CI.getType());
734       Info.flags = MachineMemOperand::MOLoad |
735                    MachineMemOperand::MOStore |
736                    MachineMemOperand::MODereferenceable;
737 
738       // XXX - Should this be volatile without known ordering?
739       Info.flags |= MachineMemOperand::MOVolatile;
740     }
741     return true;
742   }
743 
744   switch (IntrID) {
745   case Intrinsic::amdgcn_atomic_inc:
746   case Intrinsic::amdgcn_atomic_dec:
747   case Intrinsic::amdgcn_ds_fadd:
748   case Intrinsic::amdgcn_ds_fmin:
749   case Intrinsic::amdgcn_ds_fmax: {
750     Info.opc = ISD::INTRINSIC_W_CHAIN;
751     Info.memVT = MVT::getVT(CI.getType());
752     Info.ptrVal = CI.getOperand(0);
753     Info.align = 0;
754     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
755 
756     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
757     if (!Vol || !Vol->isZero())
758       Info.flags |= MachineMemOperand::MOVolatile;
759 
760     return true;
761   }
762 
763   default:
764     return false;
765   }
766 }
767 
768 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
769                                             SmallVectorImpl<Value*> &Ops,
770                                             Type *&AccessTy) const {
771   switch (II->getIntrinsicID()) {
772   case Intrinsic::amdgcn_atomic_inc:
773   case Intrinsic::amdgcn_atomic_dec:
774   case Intrinsic::amdgcn_ds_fadd:
775   case Intrinsic::amdgcn_ds_fmin:
776   case Intrinsic::amdgcn_ds_fmax: {
777     Value *Ptr = II->getArgOperand(0);
778     AccessTy = II->getType();
779     Ops.push_back(Ptr);
780     return true;
781   }
782   default:
783     return false;
784   }
785 }
786 
787 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
788   if (!Subtarget->hasFlatInstOffsets()) {
789     // Flat instructions do not have offsets, and only have the register
790     // address.
791     return AM.BaseOffs == 0 && AM.Scale == 0;
792   }
793 
794   // GFX9 added a 13-bit signed offset. When using regular flat instructions,
795   // the sign bit is ignored and is treated as a 12-bit unsigned offset.
796 
797   // Just r + i
798   return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
799 }
800 
801 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
802   if (Subtarget->hasFlatGlobalInsts())
803     return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
804 
805   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
806       // Assume the we will use FLAT for all global memory accesses
807       // on VI.
808       // FIXME: This assumption is currently wrong.  On VI we still use
809       // MUBUF instructions for the r + i addressing mode.  As currently
810       // implemented, the MUBUF instructions only work on buffer < 4GB.
811       // It may be possible to support > 4GB buffers with MUBUF instructions,
812       // by setting the stride value in the resource descriptor which would
813       // increase the size limit to (stride * 4GB).  However, this is risky,
814       // because it has never been validated.
815     return isLegalFlatAddressingMode(AM);
816   }
817 
818   return isLegalMUBUFAddressingMode(AM);
819 }
820 
821 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
822   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
823   // additionally can do r + r + i with addr64. 32-bit has more addressing
824   // mode options. Depending on the resource constant, it can also do
825   // (i64 r0) + (i32 r1) * (i14 i).
826   //
827   // Private arrays end up using a scratch buffer most of the time, so also
828   // assume those use MUBUF instructions. Scratch loads / stores are currently
829   // implemented as mubuf instructions with offen bit set, so slightly
830   // different than the normal addr64.
831   if (!isUInt<12>(AM.BaseOffs))
832     return false;
833 
834   // FIXME: Since we can split immediate into soffset and immediate offset,
835   // would it make sense to allow any immediate?
836 
837   switch (AM.Scale) {
838   case 0: // r + i or just i, depending on HasBaseReg.
839     return true;
840   case 1:
841     return true; // We have r + r or r + i.
842   case 2:
843     if (AM.HasBaseReg) {
844       // Reject 2 * r + r.
845       return false;
846     }
847 
848     // Allow 2 * r as r + r
849     // Or  2 * r + i is allowed as r + r + i.
850     return true;
851   default: // Don't allow n * r
852     return false;
853   }
854 }
855 
856 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
857                                              const AddrMode &AM, Type *Ty,
858                                              unsigned AS, Instruction *I) const {
859   // No global is ever allowed as a base.
860   if (AM.BaseGV)
861     return false;
862 
863   if (AS == AMDGPUASI.GLOBAL_ADDRESS)
864     return isLegalGlobalAddressingMode(AM);
865 
866   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
867       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
868     // If the offset isn't a multiple of 4, it probably isn't going to be
869     // correctly aligned.
870     // FIXME: Can we get the real alignment here?
871     if (AM.BaseOffs % 4 != 0)
872       return isLegalMUBUFAddressingMode(AM);
873 
874     // There are no SMRD extloads, so if we have to do a small type access we
875     // will use a MUBUF load.
876     // FIXME?: We also need to do this if unaligned, but we don't know the
877     // alignment here.
878     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
879       return isLegalGlobalAddressingMode(AM);
880 
881     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
882       // SMRD instructions have an 8-bit, dword offset on SI.
883       if (!isUInt<8>(AM.BaseOffs / 4))
884         return false;
885     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
886       // On CI+, this can also be a 32-bit literal constant offset. If it fits
887       // in 8-bits, it can use a smaller encoding.
888       if (!isUInt<32>(AM.BaseOffs / 4))
889         return false;
890     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
891       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
892       if (!isUInt<20>(AM.BaseOffs))
893         return false;
894     } else
895       llvm_unreachable("unhandled generation");
896 
897     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
898       return true;
899 
900     if (AM.Scale == 1 && AM.HasBaseReg)
901       return true;
902 
903     return false;
904 
905   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
906     return isLegalMUBUFAddressingMode(AM);
907   } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
908              AS == AMDGPUASI.REGION_ADDRESS) {
909     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
910     // field.
911     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
912     // an 8-bit dword offset but we don't know the alignment here.
913     if (!isUInt<16>(AM.BaseOffs))
914       return false;
915 
916     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
917       return true;
918 
919     if (AM.Scale == 1 && AM.HasBaseReg)
920       return true;
921 
922     return false;
923   } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
924              AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
925     // For an unknown address space, this usually means that this is for some
926     // reason being used for pure arithmetic, and not based on some addressing
927     // computation. We don't have instructions that compute pointers with any
928     // addressing modes, so treat them as having no offset like flat
929     // instructions.
930     return isLegalFlatAddressingMode(AM);
931   } else {
932     llvm_unreachable("unhandled address space");
933   }
934 }
935 
936 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
937                                         const SelectionDAG &DAG) const {
938   if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
939     return (MemVT.getSizeInBits() <= 4 * 32);
940   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
941     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
942     return (MemVT.getSizeInBits() <= MaxPrivateBits);
943   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
944     return (MemVT.getSizeInBits() <= 2 * 32);
945   }
946   return true;
947 }
948 
949 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
950                                                       unsigned AddrSpace,
951                                                       unsigned Align,
952                                                       bool *IsFast) const {
953   if (IsFast)
954     *IsFast = false;
955 
956   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
957   // which isn't a simple VT.
958   // Until MVT is extended to handle this, simply check for the size and
959   // rely on the condition below: allow accesses if the size is a multiple of 4.
960   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
961                            VT.getStoreSize() > 16)) {
962     return false;
963   }
964 
965   if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
966       AddrSpace == AMDGPUASI.REGION_ADDRESS) {
967     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
968     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
969     // with adjacent offsets.
970     bool AlignedBy4 = (Align % 4 == 0);
971     if (IsFast)
972       *IsFast = AlignedBy4;
973 
974     return AlignedBy4;
975   }
976 
977   // FIXME: We have to be conservative here and assume that flat operations
978   // will access scratch.  If we had access to the IR function, then we
979   // could determine if any private memory was used in the function.
980   if (!Subtarget->hasUnalignedScratchAccess() &&
981       (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
982        AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
983     return false;
984   }
985 
986   if (Subtarget->hasUnalignedBufferAccess()) {
987     // If we have an uniform constant load, it still requires using a slow
988     // buffer instruction if unaligned.
989     if (IsFast) {
990       *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS ||
991                  AddrSpace == AMDGPUASI.CONSTANT_ADDRESS_32BIT) ?
992         (Align % 4 == 0) : true;
993     }
994 
995     return true;
996   }
997 
998   // Smaller than dword value must be aligned.
999   if (VT.bitsLT(MVT::i32))
1000     return false;
1001 
1002   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1003   // byte-address are ignored, thus forcing Dword alignment.
1004   // This applies to private, global, and constant memory.
1005   if (IsFast)
1006     *IsFast = true;
1007 
1008   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1009 }
1010 
1011 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
1012                                           unsigned SrcAlign, bool IsMemset,
1013                                           bool ZeroMemset,
1014                                           bool MemcpyStrSrc,
1015                                           MachineFunction &MF) const {
1016   // FIXME: Should account for address space here.
1017 
1018   // The default fallback uses the private pointer size as a guess for a type to
1019   // use. Make sure we switch these to 64-bit accesses.
1020 
1021   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1022     return MVT::v4i32;
1023 
1024   if (Size >= 8 && DstAlign >= 4)
1025     return MVT::v2i32;
1026 
1027   // Use the default.
1028   return MVT::Other;
1029 }
1030 
1031 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
1032   return AS == AMDGPUASI.GLOBAL_ADDRESS ||
1033          AS == AMDGPUASI.FLAT_ADDRESS ||
1034          AS == AMDGPUASI.CONSTANT_ADDRESS ||
1035          AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT;
1036 }
1037 
1038 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1039                                            unsigned DestAS) const {
1040   return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
1041          isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
1042 }
1043 
1044 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1045   const MemSDNode *MemNode = cast<MemSDNode>(N);
1046   const Value *Ptr = MemNode->getMemOperand()->getValue();
1047   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1048   return I && I->getMetadata("amdgpu.noclobber");
1049 }
1050 
1051 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
1052                                             unsigned DestAS) const {
1053   // Flat -> private/local is a simple truncate.
1054   // Flat -> global is no-op
1055   if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
1056     return true;
1057 
1058   return isNoopAddrSpaceCast(SrcAS, DestAS);
1059 }
1060 
1061 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1062   const MemSDNode *MemNode = cast<MemSDNode>(N);
1063 
1064   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1065 }
1066 
1067 TargetLoweringBase::LegalizeTypeAction
1068 SITargetLowering::getPreferredVectorAction(EVT VT) const {
1069   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1070     return TypeSplitVector;
1071 
1072   return TargetLoweringBase::getPreferredVectorAction(VT);
1073 }
1074 
1075 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1076                                                          Type *Ty) const {
1077   // FIXME: Could be smarter if called for vector constants.
1078   return true;
1079 }
1080 
1081 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1082   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1083     switch (Op) {
1084     case ISD::LOAD:
1085     case ISD::STORE:
1086 
1087     // These operations are done with 32-bit instructions anyway.
1088     case ISD::AND:
1089     case ISD::OR:
1090     case ISD::XOR:
1091     case ISD::SELECT:
1092       // TODO: Extensions?
1093       return true;
1094     default:
1095       return false;
1096     }
1097   }
1098 
1099   // SimplifySetCC uses this function to determine whether or not it should
1100   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1101   if (VT == MVT::i1 && Op == ISD::SETCC)
1102     return false;
1103 
1104   return TargetLowering::isTypeDesirableForOp(Op, VT);
1105 }
1106 
1107 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1108                                                    const SDLoc &SL,
1109                                                    SDValue Chain,
1110                                                    uint64_t Offset) const {
1111   const DataLayout &DL = DAG.getDataLayout();
1112   MachineFunction &MF = DAG.getMachineFunction();
1113   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1114 
1115   const ArgDescriptor *InputPtrReg;
1116   const TargetRegisterClass *RC;
1117 
1118   std::tie(InputPtrReg, RC)
1119     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1120 
1121   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1122   MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
1123   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1124     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1125 
1126   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1127 }
1128 
1129 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1130                                             const SDLoc &SL) const {
1131   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1132                                                FIRST_IMPLICIT);
1133   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1134 }
1135 
1136 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1137                                          const SDLoc &SL, SDValue Val,
1138                                          bool Signed,
1139                                          const ISD::InputArg *Arg) const {
1140   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1141       VT.bitsLT(MemVT)) {
1142     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1143     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1144   }
1145 
1146   if (MemVT.isFloatingPoint())
1147     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1148   else if (Signed)
1149     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1150   else
1151     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1152 
1153   return Val;
1154 }
1155 
1156 SDValue SITargetLowering::lowerKernargMemParameter(
1157   SelectionDAG &DAG, EVT VT, EVT MemVT,
1158   const SDLoc &SL, SDValue Chain,
1159   uint64_t Offset, unsigned Align, bool Signed,
1160   const ISD::InputArg *Arg) const {
1161   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1162   PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
1163   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1164 
1165   // Try to avoid using an extload by loading earlier than the argument address,
1166   // and extracting the relevant bits. The load should hopefully be merged with
1167   // the previous argument.
1168   if (Align < 4) {
1169     assert(MemVT.getStoreSize() < 4);
1170     int64_t AlignDownOffset = alignDown(Offset, 4);
1171     int64_t OffsetDiff = Offset - AlignDownOffset;
1172 
1173     EVT IntVT = MemVT.changeTypeToInteger();
1174 
1175     // TODO: If we passed in the base kernel offset we could have a better
1176     // alignment than 4, but we don't really need it.
1177     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1178     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1179                                MachineMemOperand::MODereferenceable |
1180                                MachineMemOperand::MOInvariant);
1181 
1182     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1183     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1184 
1185     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1186     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1187     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1188 
1189 
1190     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1191   }
1192 
1193   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1194   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1195                              MachineMemOperand::MODereferenceable |
1196                              MachineMemOperand::MOInvariant);
1197 
1198   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1199   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1200 }
1201 
1202 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1203                                               const SDLoc &SL, SDValue Chain,
1204                                               const ISD::InputArg &Arg) const {
1205   MachineFunction &MF = DAG.getMachineFunction();
1206   MachineFrameInfo &MFI = MF.getFrameInfo();
1207 
1208   if (Arg.Flags.isByVal()) {
1209     unsigned Size = Arg.Flags.getByValSize();
1210     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1211     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1212   }
1213 
1214   unsigned ArgOffset = VA.getLocMemOffset();
1215   unsigned ArgSize = VA.getValVT().getStoreSize();
1216 
1217   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1218 
1219   // Create load nodes to retrieve arguments from the stack.
1220   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1221   SDValue ArgValue;
1222 
1223   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1224   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1225   MVT MemVT = VA.getValVT();
1226 
1227   switch (VA.getLocInfo()) {
1228   default:
1229     break;
1230   case CCValAssign::BCvt:
1231     MemVT = VA.getLocVT();
1232     break;
1233   case CCValAssign::SExt:
1234     ExtType = ISD::SEXTLOAD;
1235     break;
1236   case CCValAssign::ZExt:
1237     ExtType = ISD::ZEXTLOAD;
1238     break;
1239   case CCValAssign::AExt:
1240     ExtType = ISD::EXTLOAD;
1241     break;
1242   }
1243 
1244   ArgValue = DAG.getExtLoad(
1245     ExtType, SL, VA.getLocVT(), Chain, FIN,
1246     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1247     MemVT);
1248   return ArgValue;
1249 }
1250 
1251 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1252   const SIMachineFunctionInfo &MFI,
1253   EVT VT,
1254   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1255   const ArgDescriptor *Reg;
1256   const TargetRegisterClass *RC;
1257 
1258   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1259   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1260 }
1261 
1262 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1263                                    CallingConv::ID CallConv,
1264                                    ArrayRef<ISD::InputArg> Ins,
1265                                    BitVector &Skipped,
1266                                    FunctionType *FType,
1267                                    SIMachineFunctionInfo *Info) {
1268   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1269     const ISD::InputArg *Arg = &Ins[I];
1270 
1271     // First check if it's a PS input addr.
1272     if (CallConv == CallingConv::AMDGPU_PS &&
1273         !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) {
1274 
1275       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1276 
1277       // Inconveniently only the first part of the split is marked as isSplit,
1278       // so skip to the end. We only want to increment PSInputNum once for the
1279       // entire split argument.
1280       if (Arg->Flags.isSplit()) {
1281         while (!Arg->Flags.isSplitEnd()) {
1282           assert(!Arg->VT.isVector() &&
1283                  "unexpected vector split in ps argument type");
1284           if (!SkipArg)
1285             Splits.push_back(*Arg);
1286           Arg = &Ins[++I];
1287         }
1288       }
1289 
1290       if (SkipArg) {
1291         // We can safely skip PS inputs.
1292         Skipped.set(Arg->getOrigArgIndex());
1293         ++PSInputNum;
1294         continue;
1295       }
1296 
1297       Info->markPSInputAllocated(PSInputNum);
1298       if (Arg->Used)
1299         Info->markPSInputEnabled(PSInputNum);
1300 
1301       ++PSInputNum;
1302     }
1303 
1304     // Second split vertices into their elements.
1305     if (Arg->VT.isVector()) {
1306       ISD::InputArg NewArg = *Arg;
1307       NewArg.Flags.setSplit();
1308       NewArg.VT = Arg->VT.getVectorElementType();
1309 
1310       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1311       // three or five element vertex only needs three or five registers,
1312       // NOT four or eight.
1313       Type *ParamType = FType->getParamType(Arg->getOrigArgIndex());
1314       unsigned NumElements = ParamType->getVectorNumElements();
1315 
1316       for (unsigned J = 0; J != NumElements; ++J) {
1317         Splits.push_back(NewArg);
1318         NewArg.PartOffset += NewArg.VT.getStoreSize();
1319       }
1320     } else {
1321       Splits.push_back(*Arg);
1322     }
1323   }
1324 }
1325 
1326 // Allocate special inputs passed in VGPRs.
1327 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1328                                            MachineFunction &MF,
1329                                            const SIRegisterInfo &TRI,
1330                                            SIMachineFunctionInfo &Info) {
1331   if (Info.hasWorkItemIDX()) {
1332     unsigned Reg = AMDGPU::VGPR0;
1333     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1334 
1335     CCInfo.AllocateReg(Reg);
1336     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1337   }
1338 
1339   if (Info.hasWorkItemIDY()) {
1340     unsigned Reg = AMDGPU::VGPR1;
1341     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1342 
1343     CCInfo.AllocateReg(Reg);
1344     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1345   }
1346 
1347   if (Info.hasWorkItemIDZ()) {
1348     unsigned Reg = AMDGPU::VGPR2;
1349     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1350 
1351     CCInfo.AllocateReg(Reg);
1352     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1353   }
1354 }
1355 
1356 // Try to allocate a VGPR at the end of the argument list, or if no argument
1357 // VGPRs are left allocating a stack slot.
1358 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1359   ArrayRef<MCPhysReg> ArgVGPRs
1360     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1361   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1362   if (RegIdx == ArgVGPRs.size()) {
1363     // Spill to stack required.
1364     int64_t Offset = CCInfo.AllocateStack(4, 4);
1365 
1366     return ArgDescriptor::createStack(Offset);
1367   }
1368 
1369   unsigned Reg = ArgVGPRs[RegIdx];
1370   Reg = CCInfo.AllocateReg(Reg);
1371   assert(Reg != AMDGPU::NoRegister);
1372 
1373   MachineFunction &MF = CCInfo.getMachineFunction();
1374   MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1375   return ArgDescriptor::createRegister(Reg);
1376 }
1377 
1378 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1379                                              const TargetRegisterClass *RC,
1380                                              unsigned NumArgRegs) {
1381   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1382   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1383   if (RegIdx == ArgSGPRs.size())
1384     report_fatal_error("ran out of SGPRs for arguments");
1385 
1386   unsigned Reg = ArgSGPRs[RegIdx];
1387   Reg = CCInfo.AllocateReg(Reg);
1388   assert(Reg != AMDGPU::NoRegister);
1389 
1390   MachineFunction &MF = CCInfo.getMachineFunction();
1391   MF.addLiveIn(Reg, RC);
1392   return ArgDescriptor::createRegister(Reg);
1393 }
1394 
1395 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1396   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1397 }
1398 
1399 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1400   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1401 }
1402 
1403 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1404                                       MachineFunction &MF,
1405                                       const SIRegisterInfo &TRI,
1406                                       SIMachineFunctionInfo &Info) {
1407   if (Info.hasWorkItemIDX())
1408     Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1409 
1410   if (Info.hasWorkItemIDY())
1411     Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1412 
1413   if (Info.hasWorkItemIDZ())
1414     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1415 }
1416 
1417 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1418                                       MachineFunction &MF,
1419                                       const SIRegisterInfo &TRI,
1420                                       SIMachineFunctionInfo &Info) {
1421   auto &ArgInfo = Info.getArgInfo();
1422 
1423   // TODO: Unify handling with private memory pointers.
1424 
1425   if (Info.hasDispatchPtr())
1426     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1427 
1428   if (Info.hasQueuePtr())
1429     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1430 
1431   if (Info.hasKernargSegmentPtr())
1432     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1433 
1434   if (Info.hasDispatchID())
1435     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1436 
1437   // flat_scratch_init is not applicable for non-kernel functions.
1438 
1439   if (Info.hasWorkGroupIDX())
1440     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1441 
1442   if (Info.hasWorkGroupIDY())
1443     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1444 
1445   if (Info.hasWorkGroupIDZ())
1446     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1447 
1448   if (Info.hasImplicitArgPtr())
1449     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1450 }
1451 
1452 // Allocate special inputs passed in user SGPRs.
1453 static void allocateHSAUserSGPRs(CCState &CCInfo,
1454                                  MachineFunction &MF,
1455                                  const SIRegisterInfo &TRI,
1456                                  SIMachineFunctionInfo &Info) {
1457   if (Info.hasImplicitBufferPtr()) {
1458     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1459     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1460     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1461   }
1462 
1463   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1464   if (Info.hasPrivateSegmentBuffer()) {
1465     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1466     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1467     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1468   }
1469 
1470   if (Info.hasDispatchPtr()) {
1471     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1472     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1473     CCInfo.AllocateReg(DispatchPtrReg);
1474   }
1475 
1476   if (Info.hasQueuePtr()) {
1477     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1478     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1479     CCInfo.AllocateReg(QueuePtrReg);
1480   }
1481 
1482   if (Info.hasKernargSegmentPtr()) {
1483     unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1484     MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1485     CCInfo.AllocateReg(InputPtrReg);
1486   }
1487 
1488   if (Info.hasDispatchID()) {
1489     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1490     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1491     CCInfo.AllocateReg(DispatchIDReg);
1492   }
1493 
1494   if (Info.hasFlatScratchInit()) {
1495     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1496     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1497     CCInfo.AllocateReg(FlatScratchInitReg);
1498   }
1499 
1500   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1501   // these from the dispatch pointer.
1502 }
1503 
1504 // Allocate special input registers that are initialized per-wave.
1505 static void allocateSystemSGPRs(CCState &CCInfo,
1506                                 MachineFunction &MF,
1507                                 SIMachineFunctionInfo &Info,
1508                                 CallingConv::ID CallConv,
1509                                 bool IsShader) {
1510   if (Info.hasWorkGroupIDX()) {
1511     unsigned Reg = Info.addWorkGroupIDX();
1512     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1513     CCInfo.AllocateReg(Reg);
1514   }
1515 
1516   if (Info.hasWorkGroupIDY()) {
1517     unsigned Reg = Info.addWorkGroupIDY();
1518     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1519     CCInfo.AllocateReg(Reg);
1520   }
1521 
1522   if (Info.hasWorkGroupIDZ()) {
1523     unsigned Reg = Info.addWorkGroupIDZ();
1524     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1525     CCInfo.AllocateReg(Reg);
1526   }
1527 
1528   if (Info.hasWorkGroupInfo()) {
1529     unsigned Reg = Info.addWorkGroupInfo();
1530     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1531     CCInfo.AllocateReg(Reg);
1532   }
1533 
1534   if (Info.hasPrivateSegmentWaveByteOffset()) {
1535     // Scratch wave offset passed in system SGPR.
1536     unsigned PrivateSegmentWaveByteOffsetReg;
1537 
1538     if (IsShader) {
1539       PrivateSegmentWaveByteOffsetReg =
1540         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1541 
1542       // This is true if the scratch wave byte offset doesn't have a fixed
1543       // location.
1544       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1545         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1546         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1547       }
1548     } else
1549       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1550 
1551     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1552     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1553   }
1554 }
1555 
1556 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1557                                      MachineFunction &MF,
1558                                      const SIRegisterInfo &TRI,
1559                                      SIMachineFunctionInfo &Info) {
1560   // Now that we've figured out where the scratch register inputs are, see if
1561   // should reserve the arguments and use them directly.
1562   MachineFrameInfo &MFI = MF.getFrameInfo();
1563   bool HasStackObjects = MFI.hasStackObjects();
1564 
1565   // Record that we know we have non-spill stack objects so we don't need to
1566   // check all stack objects later.
1567   if (HasStackObjects)
1568     Info.setHasNonSpillStackObjects(true);
1569 
1570   // Everything live out of a block is spilled with fast regalloc, so it's
1571   // almost certain that spilling will be required.
1572   if (TM.getOptLevel() == CodeGenOpt::None)
1573     HasStackObjects = true;
1574 
1575   // For now assume stack access is needed in any callee functions, so we need
1576   // the scratch registers to pass in.
1577   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1578 
1579   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1580   if (ST.isAmdCodeObjectV2(MF.getFunction())) {
1581     if (RequiresStackAccess) {
1582       // If we have stack objects, we unquestionably need the private buffer
1583       // resource. For the Code Object V2 ABI, this will be the first 4 user
1584       // SGPR inputs. We can reserve those and use them directly.
1585 
1586       unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1587         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1588       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1589 
1590       if (MFI.hasCalls()) {
1591         // If we have calls, we need to keep the frame register in a register
1592         // that won't be clobbered by a call, so ensure it is copied somewhere.
1593 
1594         // This is not a problem for the scratch wave offset, because the same
1595         // registers are reserved in all functions.
1596 
1597         // FIXME: Nothing is really ensuring this is a call preserved register,
1598         // it's just selected from the end so it happens to be.
1599         unsigned ReservedOffsetReg
1600           = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1601         Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1602       } else {
1603         unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1604           AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1605         Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1606       }
1607     } else {
1608       unsigned ReservedBufferReg
1609         = TRI.reservedPrivateSegmentBufferReg(MF);
1610       unsigned ReservedOffsetReg
1611         = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1612 
1613       // We tentatively reserve the last registers (skipping the last two
1614       // which may contain VCC). After register allocation, we'll replace
1615       // these with the ones immediately after those which were really
1616       // allocated. In the prologue copies will be inserted from the argument
1617       // to these reserved registers.
1618       Info.setScratchRSrcReg(ReservedBufferReg);
1619       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1620     }
1621   } else {
1622     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1623 
1624     // Without HSA, relocations are used for the scratch pointer and the
1625     // buffer resource setup is always inserted in the prologue. Scratch wave
1626     // offset is still in an input SGPR.
1627     Info.setScratchRSrcReg(ReservedBufferReg);
1628 
1629     if (HasStackObjects && !MFI.hasCalls()) {
1630       unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1631         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1632       Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1633     } else {
1634       unsigned ReservedOffsetReg
1635         = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1636       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1637     }
1638   }
1639 }
1640 
1641 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1642   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1643   return !Info->isEntryFunction();
1644 }
1645 
1646 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1647 
1648 }
1649 
1650 void SITargetLowering::insertCopiesSplitCSR(
1651   MachineBasicBlock *Entry,
1652   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1653   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1654 
1655   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1656   if (!IStart)
1657     return;
1658 
1659   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1660   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1661   MachineBasicBlock::iterator MBBI = Entry->begin();
1662   for (const MCPhysReg *I = IStart; *I; ++I) {
1663     const TargetRegisterClass *RC = nullptr;
1664     if (AMDGPU::SReg_64RegClass.contains(*I))
1665       RC = &AMDGPU::SGPR_64RegClass;
1666     else if (AMDGPU::SReg_32RegClass.contains(*I))
1667       RC = &AMDGPU::SGPR_32RegClass;
1668     else
1669       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1670 
1671     unsigned NewVR = MRI->createVirtualRegister(RC);
1672     // Create copy from CSR to a virtual register.
1673     Entry->addLiveIn(*I);
1674     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1675       .addReg(*I);
1676 
1677     // Insert the copy-back instructions right before the terminator.
1678     for (auto *Exit : Exits)
1679       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1680               TII->get(TargetOpcode::COPY), *I)
1681         .addReg(NewVR);
1682   }
1683 }
1684 
1685 SDValue SITargetLowering::LowerFormalArguments(
1686     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1687     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1688     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1689   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1690 
1691   MachineFunction &MF = DAG.getMachineFunction();
1692   const Function &Fn = MF.getFunction();
1693   FunctionType *FType = MF.getFunction().getFunctionType();
1694   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1695   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1696 
1697   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1698     DiagnosticInfoUnsupported NoGraphicsHSA(
1699         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1700     DAG.getContext()->diagnose(NoGraphicsHSA);
1701     return DAG.getEntryNode();
1702   }
1703 
1704   // Create stack objects that are used for emitting debugger prologue if
1705   // "amdgpu-debugger-emit-prologue" attribute was specified.
1706   if (ST.debuggerEmitPrologue())
1707     createDebuggerPrologueStackObjects(MF);
1708 
1709   SmallVector<ISD::InputArg, 16> Splits;
1710   SmallVector<CCValAssign, 16> ArgLocs;
1711   BitVector Skipped(Ins.size());
1712   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1713                  *DAG.getContext());
1714 
1715   bool IsShader = AMDGPU::isShader(CallConv);
1716   bool IsKernel = AMDGPU::isKernel(CallConv);
1717   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1718 
1719   if (!IsEntryFunc) {
1720     // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1721     // this when allocating argument fixed offsets.
1722     CCInfo.AllocateStack(4, 4);
1723   }
1724 
1725   if (IsShader) {
1726     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1727 
1728     // At least one interpolation mode must be enabled or else the GPU will
1729     // hang.
1730     //
1731     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1732     // set PSInputAddr, the user wants to enable some bits after the compilation
1733     // based on run-time states. Since we can't know what the final PSInputEna
1734     // will look like, so we shouldn't do anything here and the user should take
1735     // responsibility for the correct programming.
1736     //
1737     // Otherwise, the following restrictions apply:
1738     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1739     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1740     //   enabled too.
1741     if (CallConv == CallingConv::AMDGPU_PS) {
1742       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1743            ((Info->getPSInputAddr() & 0xF) == 0 &&
1744             Info->isPSInputAllocated(11))) {
1745         CCInfo.AllocateReg(AMDGPU::VGPR0);
1746         CCInfo.AllocateReg(AMDGPU::VGPR1);
1747         Info->markPSInputAllocated(0);
1748         Info->markPSInputEnabled(0);
1749       }
1750       if (Subtarget->isAmdPalOS()) {
1751         // For isAmdPalOS, the user does not enable some bits after compilation
1752         // based on run-time states; the register values being generated here are
1753         // the final ones set in hardware. Therefore we need to apply the
1754         // workaround to PSInputAddr and PSInputEnable together.  (The case where
1755         // a bit is set in PSInputAddr but not PSInputEnable is where the
1756         // frontend set up an input arg for a particular interpolation mode, but
1757         // nothing uses that input arg. Really we should have an earlier pass
1758         // that removes such an arg.)
1759         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1760         if ((PsInputBits & 0x7F) == 0 ||
1761             ((PsInputBits & 0xF) == 0 &&
1762              (PsInputBits >> 11 & 1)))
1763           Info->markPSInputEnabled(
1764               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1765       }
1766     }
1767 
1768     assert(!Info->hasDispatchPtr() &&
1769            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1770            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1771            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1772            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1773            !Info->hasWorkItemIDZ());
1774   } else if (IsKernel) {
1775     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1776   } else {
1777     Splits.append(Ins.begin(), Ins.end());
1778   }
1779 
1780   if (IsEntryFunc) {
1781     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1782     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1783   }
1784 
1785   if (IsKernel) {
1786     analyzeFormalArgumentsCompute(CCInfo, Ins);
1787   } else {
1788     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1789     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1790   }
1791 
1792   SmallVector<SDValue, 16> Chains;
1793 
1794   // FIXME: This is the minimum kernel argument alignment. We should improve
1795   // this to the maximum alignment of the arguments.
1796   //
1797   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
1798   // kern arg offset.
1799   const unsigned KernelArgBaseAlign = 16;
1800   const unsigned ExplicitOffset = Subtarget->getExplicitKernelArgOffset(Fn);
1801 
1802    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1803     const ISD::InputArg &Arg = Ins[i];
1804     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
1805       InVals.push_back(DAG.getUNDEF(Arg.VT));
1806       continue;
1807     }
1808 
1809     CCValAssign &VA = ArgLocs[ArgIdx++];
1810     MVT VT = VA.getLocVT();
1811 
1812     if (IsEntryFunc && VA.isMemLoc()) {
1813       VT = Ins[i].VT;
1814       EVT MemVT = VA.getLocVT();
1815 
1816       const uint64_t Offset = ExplicitOffset + VA.getLocMemOffset();
1817       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
1818 
1819       // The first 36 bytes of the input buffer contains information about
1820       // thread group and global sizes for clover.
1821       SDValue Arg = lowerKernargMemParameter(
1822         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
1823       Chains.push_back(Arg.getValue(1));
1824 
1825       auto *ParamTy =
1826         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1827       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
1828           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1829         // On SI local pointers are just offsets into LDS, so they are always
1830         // less than 16-bits.  On CI and newer they could potentially be
1831         // real pointers, so we can't guarantee their size.
1832         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1833                           DAG.getValueType(MVT::i16));
1834       }
1835 
1836       InVals.push_back(Arg);
1837       continue;
1838     } else if (!IsEntryFunc && VA.isMemLoc()) {
1839       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1840       InVals.push_back(Val);
1841       if (!Arg.Flags.isByVal())
1842         Chains.push_back(Val.getValue(1));
1843       continue;
1844     }
1845 
1846     assert(VA.isRegLoc() && "Parameter must be in a register!");
1847 
1848     unsigned Reg = VA.getLocReg();
1849     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1850     EVT ValVT = VA.getValVT();
1851 
1852     Reg = MF.addLiveIn(Reg, RC);
1853     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1854 
1855     if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1856       // The return object should be reasonably addressable.
1857 
1858       // FIXME: This helps when the return is a real sret. If it is a
1859       // automatically inserted sret (i.e. CanLowerReturn returns false), an
1860       // extra copy is inserted in SelectionDAGBuilder which obscures this.
1861       unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1862       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1863         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1864     }
1865 
1866     // If this is an 8 or 16-bit value, it is really passed promoted
1867     // to 32 bits. Insert an assert[sz]ext to capture this, then
1868     // truncate to the right size.
1869     switch (VA.getLocInfo()) {
1870     case CCValAssign::Full:
1871       break;
1872     case CCValAssign::BCvt:
1873       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1874       break;
1875     case CCValAssign::SExt:
1876       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1877                         DAG.getValueType(ValVT));
1878       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1879       break;
1880     case CCValAssign::ZExt:
1881       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1882                         DAG.getValueType(ValVT));
1883       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1884       break;
1885     case CCValAssign::AExt:
1886       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1887       break;
1888     default:
1889       llvm_unreachable("Unknown loc info!");
1890     }
1891 
1892     if (IsShader && Arg.VT.isVector()) {
1893       // Build a vector from the registers
1894       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1895       unsigned NumElements = ParamType->getVectorNumElements();
1896 
1897       SmallVector<SDValue, 4> Regs;
1898       Regs.push_back(Val);
1899       for (unsigned j = 1; j != NumElements; ++j) {
1900         Reg = ArgLocs[ArgIdx++].getLocReg();
1901         Reg = MF.addLiveIn(Reg, RC);
1902 
1903         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1904         Regs.push_back(Copy);
1905       }
1906 
1907       // Fill up the missing vector elements
1908       NumElements = Arg.VT.getVectorNumElements() - NumElements;
1909       Regs.append(NumElements, DAG.getUNDEF(VT));
1910 
1911       InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1912       continue;
1913     }
1914 
1915     InVals.push_back(Val);
1916   }
1917 
1918   if (!IsEntryFunc) {
1919     // Special inputs come after user arguments.
1920     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1921   }
1922 
1923   // Start adding system SGPRs.
1924   if (IsEntryFunc) {
1925     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1926   } else {
1927     CCInfo.AllocateReg(Info->getScratchRSrcReg());
1928     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1929     CCInfo.AllocateReg(Info->getFrameOffsetReg());
1930     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
1931   }
1932 
1933   auto &ArgUsageInfo =
1934     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1935   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
1936 
1937   unsigned StackArgSize = CCInfo.getNextStackOffset();
1938   Info->setBytesInStackArgArea(StackArgSize);
1939 
1940   return Chains.empty() ? Chain :
1941     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1942 }
1943 
1944 // TODO: If return values can't fit in registers, we should return as many as
1945 // possible in registers before passing on stack.
1946 bool SITargetLowering::CanLowerReturn(
1947   CallingConv::ID CallConv,
1948   MachineFunction &MF, bool IsVarArg,
1949   const SmallVectorImpl<ISD::OutputArg> &Outs,
1950   LLVMContext &Context) const {
1951   // Replacing returns with sret/stack usage doesn't make sense for shaders.
1952   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1953   // for shaders. Vector types should be explicitly handled by CC.
1954   if (AMDGPU::isEntryFunctionCC(CallConv))
1955     return true;
1956 
1957   SmallVector<CCValAssign, 16> RVLocs;
1958   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1959   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1960 }
1961 
1962 SDValue
1963 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1964                               bool isVarArg,
1965                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1966                               const SmallVectorImpl<SDValue> &OutVals,
1967                               const SDLoc &DL, SelectionDAG &DAG) const {
1968   MachineFunction &MF = DAG.getMachineFunction();
1969   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1970 
1971   if (AMDGPU::isKernel(CallConv)) {
1972     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1973                                              OutVals, DL, DAG);
1974   }
1975 
1976   bool IsShader = AMDGPU::isShader(CallConv);
1977 
1978   Info->setIfReturnsVoid(Outs.size() == 0);
1979   bool IsWaveEnd = Info->returnsVoid() && IsShader;
1980 
1981   SmallVector<ISD::OutputArg, 48> Splits;
1982   SmallVector<SDValue, 48> SplitVals;
1983 
1984   // Split vectors into their elements.
1985   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1986     const ISD::OutputArg &Out = Outs[i];
1987 
1988     if (IsShader && Out.VT.isVector()) {
1989       MVT VT = Out.VT.getVectorElementType();
1990       ISD::OutputArg NewOut = Out;
1991       NewOut.Flags.setSplit();
1992       NewOut.VT = VT;
1993 
1994       // We want the original number of vector elements here, e.g.
1995       // three or five, not four or eight.
1996       unsigned NumElements = Out.ArgVT.getVectorNumElements();
1997 
1998       for (unsigned j = 0; j != NumElements; ++j) {
1999         SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
2000                                    DAG.getConstant(j, DL, MVT::i32));
2001         SplitVals.push_back(Elem);
2002         Splits.push_back(NewOut);
2003         NewOut.PartOffset += NewOut.VT.getStoreSize();
2004       }
2005     } else {
2006       SplitVals.push_back(OutVals[i]);
2007       Splits.push_back(Out);
2008     }
2009   }
2010 
2011   // CCValAssign - represent the assignment of the return value to a location.
2012   SmallVector<CCValAssign, 48> RVLocs;
2013 
2014   // CCState - Info about the registers and stack slots.
2015   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2016                  *DAG.getContext());
2017 
2018   // Analyze outgoing return values.
2019   CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
2020 
2021   SDValue Flag;
2022   SmallVector<SDValue, 48> RetOps;
2023   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2024 
2025   // Add return address for callable functions.
2026   if (!Info->isEntryFunction()) {
2027     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2028     SDValue ReturnAddrReg = CreateLiveInRegister(
2029       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2030 
2031     // FIXME: Should be able to use a vreg here, but need a way to prevent it
2032     // from being allcoated to a CSR.
2033 
2034     SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2035                                                 MVT::i64);
2036 
2037     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2038     Flag = Chain.getValue(1);
2039 
2040     RetOps.push_back(PhysReturnAddrReg);
2041   }
2042 
2043   // Copy the result values into the output registers.
2044   for (unsigned i = 0, realRVLocIdx = 0;
2045        i != RVLocs.size();
2046        ++i, ++realRVLocIdx) {
2047     CCValAssign &VA = RVLocs[i];
2048     assert(VA.isRegLoc() && "Can only return in registers!");
2049     // TODO: Partially return in registers if return values don't fit.
2050 
2051     SDValue Arg = SplitVals[realRVLocIdx];
2052 
2053     // Copied from other backends.
2054     switch (VA.getLocInfo()) {
2055     case CCValAssign::Full:
2056       break;
2057     case CCValAssign::BCvt:
2058       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2059       break;
2060     case CCValAssign::SExt:
2061       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2062       break;
2063     case CCValAssign::ZExt:
2064       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2065       break;
2066     case CCValAssign::AExt:
2067       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2068       break;
2069     default:
2070       llvm_unreachable("Unknown loc info!");
2071     }
2072 
2073     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2074     Flag = Chain.getValue(1);
2075     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2076   }
2077 
2078   // FIXME: Does sret work properly?
2079   if (!Info->isEntryFunction()) {
2080     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2081     const MCPhysReg *I =
2082       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2083     if (I) {
2084       for (; *I; ++I) {
2085         if (AMDGPU::SReg_64RegClass.contains(*I))
2086           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2087         else if (AMDGPU::SReg_32RegClass.contains(*I))
2088           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2089         else
2090           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2091       }
2092     }
2093   }
2094 
2095   // Update chain and glue.
2096   RetOps[0] = Chain;
2097   if (Flag.getNode())
2098     RetOps.push_back(Flag);
2099 
2100   unsigned Opc = AMDGPUISD::ENDPGM;
2101   if (!IsWaveEnd)
2102     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2103   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2104 }
2105 
2106 SDValue SITargetLowering::LowerCallResult(
2107     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2108     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2109     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2110     SDValue ThisVal) const {
2111   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2112 
2113   // Assign locations to each value returned by this call.
2114   SmallVector<CCValAssign, 16> RVLocs;
2115   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2116                  *DAG.getContext());
2117   CCInfo.AnalyzeCallResult(Ins, RetCC);
2118 
2119   // Copy all of the result registers out of their specified physreg.
2120   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2121     CCValAssign VA = RVLocs[i];
2122     SDValue Val;
2123 
2124     if (VA.isRegLoc()) {
2125       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2126       Chain = Val.getValue(1);
2127       InFlag = Val.getValue(2);
2128     } else if (VA.isMemLoc()) {
2129       report_fatal_error("TODO: return values in memory");
2130     } else
2131       llvm_unreachable("unknown argument location type");
2132 
2133     switch (VA.getLocInfo()) {
2134     case CCValAssign::Full:
2135       break;
2136     case CCValAssign::BCvt:
2137       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2138       break;
2139     case CCValAssign::ZExt:
2140       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2141                         DAG.getValueType(VA.getValVT()));
2142       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2143       break;
2144     case CCValAssign::SExt:
2145       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2146                         DAG.getValueType(VA.getValVT()));
2147       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2148       break;
2149     case CCValAssign::AExt:
2150       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2151       break;
2152     default:
2153       llvm_unreachable("Unknown loc info!");
2154     }
2155 
2156     InVals.push_back(Val);
2157   }
2158 
2159   return Chain;
2160 }
2161 
2162 // Add code to pass special inputs required depending on used features separate
2163 // from the explicit user arguments present in the IR.
2164 void SITargetLowering::passSpecialInputs(
2165     CallLoweringInfo &CLI,
2166     const SIMachineFunctionInfo &Info,
2167     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2168     SmallVectorImpl<SDValue> &MemOpChains,
2169     SDValue Chain,
2170     SDValue StackPtr) const {
2171   // If we don't have a call site, this was a call inserted by
2172   // legalization. These can never use special inputs.
2173   if (!CLI.CS)
2174     return;
2175 
2176   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2177   assert(CalleeFunc);
2178 
2179   SelectionDAG &DAG = CLI.DAG;
2180   const SDLoc &DL = CLI.DL;
2181 
2182   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2183 
2184   auto &ArgUsageInfo =
2185     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2186   const AMDGPUFunctionArgInfo &CalleeArgInfo
2187     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2188 
2189   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2190 
2191   // TODO: Unify with private memory register handling. This is complicated by
2192   // the fact that at least in kernels, the input argument is not necessarily
2193   // in the same location as the input.
2194   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2195     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2196     AMDGPUFunctionArgInfo::QUEUE_PTR,
2197     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2198     AMDGPUFunctionArgInfo::DISPATCH_ID,
2199     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2200     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2201     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2202     AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2203     AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2204     AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2205     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2206   };
2207 
2208   for (auto InputID : InputRegs) {
2209     const ArgDescriptor *OutgoingArg;
2210     const TargetRegisterClass *ArgRC;
2211 
2212     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2213     if (!OutgoingArg)
2214       continue;
2215 
2216     const ArgDescriptor *IncomingArg;
2217     const TargetRegisterClass *IncomingArgRC;
2218     std::tie(IncomingArg, IncomingArgRC)
2219       = CallerArgInfo.getPreloadedValue(InputID);
2220     assert(IncomingArgRC == ArgRC);
2221 
2222     // All special arguments are ints for now.
2223     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2224     SDValue InputReg;
2225 
2226     if (IncomingArg) {
2227       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2228     } else {
2229       // The implicit arg ptr is special because it doesn't have a corresponding
2230       // input for kernels, and is computed from the kernarg segment pointer.
2231       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2232       InputReg = getImplicitArgPtr(DAG, DL);
2233     }
2234 
2235     if (OutgoingArg->isRegister()) {
2236       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2237     } else {
2238       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr,
2239                                               InputReg,
2240                                               OutgoingArg->getStackOffset());
2241       MemOpChains.push_back(ArgStore);
2242     }
2243   }
2244 }
2245 
2246 static bool canGuaranteeTCO(CallingConv::ID CC) {
2247   return CC == CallingConv::Fast;
2248 }
2249 
2250 /// Return true if we might ever do TCO for calls with this calling convention.
2251 static bool mayTailCallThisCC(CallingConv::ID CC) {
2252   switch (CC) {
2253   case CallingConv::C:
2254     return true;
2255   default:
2256     return canGuaranteeTCO(CC);
2257   }
2258 }
2259 
2260 bool SITargetLowering::isEligibleForTailCallOptimization(
2261     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2262     const SmallVectorImpl<ISD::OutputArg> &Outs,
2263     const SmallVectorImpl<SDValue> &OutVals,
2264     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2265   if (!mayTailCallThisCC(CalleeCC))
2266     return false;
2267 
2268   MachineFunction &MF = DAG.getMachineFunction();
2269   const Function &CallerF = MF.getFunction();
2270   CallingConv::ID CallerCC = CallerF.getCallingConv();
2271   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2272   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2273 
2274   // Kernels aren't callable, and don't have a live in return address so it
2275   // doesn't make sense to do a tail call with entry functions.
2276   if (!CallerPreserved)
2277     return false;
2278 
2279   bool CCMatch = CallerCC == CalleeCC;
2280 
2281   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2282     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2283       return true;
2284     return false;
2285   }
2286 
2287   // TODO: Can we handle var args?
2288   if (IsVarArg)
2289     return false;
2290 
2291   for (const Argument &Arg : CallerF.args()) {
2292     if (Arg.hasByValAttr())
2293       return false;
2294   }
2295 
2296   LLVMContext &Ctx = *DAG.getContext();
2297 
2298   // Check that the call results are passed in the same way.
2299   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2300                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2301                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2302     return false;
2303 
2304   // The callee has to preserve all registers the caller needs to preserve.
2305   if (!CCMatch) {
2306     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2307     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2308       return false;
2309   }
2310 
2311   // Nothing more to check if the callee is taking no arguments.
2312   if (Outs.empty())
2313     return true;
2314 
2315   SmallVector<CCValAssign, 16> ArgLocs;
2316   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2317 
2318   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2319 
2320   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2321   // If the stack arguments for this call do not fit into our own save area then
2322   // the call cannot be made tail.
2323   // TODO: Is this really necessary?
2324   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2325     return false;
2326 
2327   const MachineRegisterInfo &MRI = MF.getRegInfo();
2328   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2329 }
2330 
2331 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2332   if (!CI->isTailCall())
2333     return false;
2334 
2335   const Function *ParentFn = CI->getParent()->getParent();
2336   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2337     return false;
2338 
2339   auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2340   return (Attr.getValueAsString() != "true");
2341 }
2342 
2343 // The wave scratch offset register is used as the global base pointer.
2344 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2345                                     SmallVectorImpl<SDValue> &InVals) const {
2346   SelectionDAG &DAG = CLI.DAG;
2347   const SDLoc &DL = CLI.DL;
2348   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2349   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2350   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2351   SDValue Chain = CLI.Chain;
2352   SDValue Callee = CLI.Callee;
2353   bool &IsTailCall = CLI.IsTailCall;
2354   CallingConv::ID CallConv = CLI.CallConv;
2355   bool IsVarArg = CLI.IsVarArg;
2356   bool IsSibCall = false;
2357   bool IsThisReturn = false;
2358   MachineFunction &MF = DAG.getMachineFunction();
2359 
2360   if (IsVarArg) {
2361     return lowerUnhandledCall(CLI, InVals,
2362                               "unsupported call to variadic function ");
2363   }
2364 
2365   if (!CLI.CS.getCalledFunction()) {
2366     return lowerUnhandledCall(CLI, InVals,
2367                               "unsupported indirect call to function ");
2368   }
2369 
2370   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2371     return lowerUnhandledCall(CLI, InVals,
2372                               "unsupported required tail call to function ");
2373   }
2374 
2375   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2376     // Note the issue is with the CC of the calling function, not of the call
2377     // itself.
2378     return lowerUnhandledCall(CLI, InVals,
2379                           "unsupported call from graphics shader of function ");
2380   }
2381 
2382   // The first 4 bytes are reserved for the callee's emergency stack slot.
2383   const unsigned CalleeUsableStackOffset = 4;
2384 
2385   if (IsTailCall) {
2386     IsTailCall = isEligibleForTailCallOptimization(
2387       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2388     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2389       report_fatal_error("failed to perform tail call elimination on a call "
2390                          "site marked musttail");
2391     }
2392 
2393     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2394 
2395     // A sibling call is one where we're under the usual C ABI and not planning
2396     // to change that but can still do a tail call:
2397     if (!TailCallOpt && IsTailCall)
2398       IsSibCall = true;
2399 
2400     if (IsTailCall)
2401       ++NumTailCalls;
2402   }
2403 
2404   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) {
2405     // FIXME: Remove this hack for function pointer types after removing
2406     // support of old address space mapping. In the new address space
2407     // mapping the pointer in default address space is 64 bit, therefore
2408     // does not need this hack.
2409     if (Callee.getValueType() == MVT::i32) {
2410       const GlobalValue *GV = GA->getGlobal();
2411       Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false,
2412                                     GA->getTargetFlags());
2413     }
2414   }
2415   assert(Callee.getValueType() == MVT::i64);
2416 
2417   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2418 
2419   // Analyze operands of the call, assigning locations to each operand.
2420   SmallVector<CCValAssign, 16> ArgLocs;
2421   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2422   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2423   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2424 
2425   // Get a count of how many bytes are to be pushed on the stack.
2426   unsigned NumBytes = CCInfo.getNextStackOffset();
2427 
2428   if (IsSibCall) {
2429     // Since we're not changing the ABI to make this a tail call, the memory
2430     // operands are already available in the caller's incoming argument space.
2431     NumBytes = 0;
2432   }
2433 
2434   // FPDiff is the byte offset of the call's argument area from the callee's.
2435   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2436   // by this amount for a tail call. In a sibling call it must be 0 because the
2437   // caller will deallocate the entire stack and the callee still expects its
2438   // arguments to begin at SP+0. Completely unused for non-tail calls.
2439   int32_t FPDiff = 0;
2440   MachineFrameInfo &MFI = MF.getFrameInfo();
2441   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2442 
2443   SDValue CallerSavedFP;
2444 
2445   // Adjust the stack pointer for the new arguments...
2446   // These operations are automatically eliminated by the prolog/epilog pass
2447   if (!IsSibCall) {
2448     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2449 
2450     unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2451 
2452     // In the HSA case, this should be an identity copy.
2453     SDValue ScratchRSrcReg
2454       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2455     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2456 
2457     // TODO: Don't hardcode these registers and get from the callee function.
2458     SDValue ScratchWaveOffsetReg
2459       = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2460     RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2461 
2462     if (!Info->isEntryFunction()) {
2463       // Avoid clobbering this function's FP value. In the current convention
2464       // callee will overwrite this, so do save/restore around the call site.
2465       CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2466                                          Info->getFrameOffsetReg(), MVT::i32);
2467     }
2468   }
2469 
2470   // Stack pointer relative accesses are done by changing the offset SGPR. This
2471   // is just the VGPR offset component.
2472   SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32);
2473 
2474   SmallVector<SDValue, 8> MemOpChains;
2475   MVT PtrVT = MVT::i32;
2476 
2477   // Walk the register/memloc assignments, inserting copies/loads.
2478   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2479        ++i, ++realArgIdx) {
2480     CCValAssign &VA = ArgLocs[i];
2481     SDValue Arg = OutVals[realArgIdx];
2482 
2483     // Promote the value if needed.
2484     switch (VA.getLocInfo()) {
2485     case CCValAssign::Full:
2486       break;
2487     case CCValAssign::BCvt:
2488       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2489       break;
2490     case CCValAssign::ZExt:
2491       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2492       break;
2493     case CCValAssign::SExt:
2494       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2495       break;
2496     case CCValAssign::AExt:
2497       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2498       break;
2499     case CCValAssign::FPExt:
2500       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2501       break;
2502     default:
2503       llvm_unreachable("Unknown loc info!");
2504     }
2505 
2506     if (VA.isRegLoc()) {
2507       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2508     } else {
2509       assert(VA.isMemLoc());
2510 
2511       SDValue DstAddr;
2512       MachinePointerInfo DstInfo;
2513 
2514       unsigned LocMemOffset = VA.getLocMemOffset();
2515       int32_t Offset = LocMemOffset;
2516 
2517       SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset);
2518 
2519       if (IsTailCall) {
2520         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2521         unsigned OpSize = Flags.isByVal() ?
2522           Flags.getByValSize() : VA.getValVT().getStoreSize();
2523 
2524         Offset = Offset + FPDiff;
2525         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2526 
2527         DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT),
2528                                          StackPtr);
2529         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2530 
2531         // Make sure any stack arguments overlapping with where we're storing
2532         // are loaded before this eventual operation. Otherwise they'll be
2533         // clobbered.
2534 
2535         // FIXME: Why is this really necessary? This seems to just result in a
2536         // lot of code to copy the stack and write them back to the same
2537         // locations, which are supposed to be immutable?
2538         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2539       } else {
2540         DstAddr = PtrOff;
2541         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2542       }
2543 
2544       if (Outs[i].Flags.isByVal()) {
2545         SDValue SizeNode =
2546             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2547         SDValue Cpy = DAG.getMemcpy(
2548             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2549             /*isVol = */ false, /*AlwaysInline = */ true,
2550             /*isTailCall = */ false, DstInfo,
2551             MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2552                 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS))));
2553 
2554         MemOpChains.push_back(Cpy);
2555       } else {
2556         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
2557         MemOpChains.push_back(Store);
2558       }
2559     }
2560   }
2561 
2562   // Copy special input registers after user input arguments.
2563   passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr);
2564 
2565   if (!MemOpChains.empty())
2566     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2567 
2568   // Build a sequence of copy-to-reg nodes chained together with token chain
2569   // and flag operands which copy the outgoing args into the appropriate regs.
2570   SDValue InFlag;
2571   for (auto &RegToPass : RegsToPass) {
2572     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2573                              RegToPass.second, InFlag);
2574     InFlag = Chain.getValue(1);
2575   }
2576 
2577 
2578   SDValue PhysReturnAddrReg;
2579   if (IsTailCall) {
2580     // Since the return is being combined with the call, we need to pass on the
2581     // return address.
2582 
2583     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2584     SDValue ReturnAddrReg = CreateLiveInRegister(
2585       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2586 
2587     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2588                                         MVT::i64);
2589     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2590     InFlag = Chain.getValue(1);
2591   }
2592 
2593   // We don't usually want to end the call-sequence here because we would tidy
2594   // the frame up *after* the call, however in the ABI-changing tail-call case
2595   // we've carefully laid out the parameters so that when sp is reset they'll be
2596   // in the correct location.
2597   if (IsTailCall && !IsSibCall) {
2598     Chain = DAG.getCALLSEQ_END(Chain,
2599                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2600                                DAG.getTargetConstant(0, DL, MVT::i32),
2601                                InFlag, DL);
2602     InFlag = Chain.getValue(1);
2603   }
2604 
2605   std::vector<SDValue> Ops;
2606   Ops.push_back(Chain);
2607   Ops.push_back(Callee);
2608 
2609   if (IsTailCall) {
2610     // Each tail call may have to adjust the stack by a different amount, so
2611     // this information must travel along with the operation for eventual
2612     // consumption by emitEpilogue.
2613     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2614 
2615     Ops.push_back(PhysReturnAddrReg);
2616   }
2617 
2618   // Add argument registers to the end of the list so that they are known live
2619   // into the call.
2620   for (auto &RegToPass : RegsToPass) {
2621     Ops.push_back(DAG.getRegister(RegToPass.first,
2622                                   RegToPass.second.getValueType()));
2623   }
2624 
2625   // Add a register mask operand representing the call-preserved registers.
2626 
2627   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2628   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2629   assert(Mask && "Missing call preserved mask for calling convention");
2630   Ops.push_back(DAG.getRegisterMask(Mask));
2631 
2632   if (InFlag.getNode())
2633     Ops.push_back(InFlag);
2634 
2635   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2636 
2637   // If we're doing a tall call, use a TC_RETURN here rather than an
2638   // actual call instruction.
2639   if (IsTailCall) {
2640     MFI.setHasTailCall();
2641     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2642   }
2643 
2644   // Returns a chain and a flag for retval copy to use.
2645   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2646   Chain = Call.getValue(0);
2647   InFlag = Call.getValue(1);
2648 
2649   if (CallerSavedFP) {
2650     SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2651     Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2652     InFlag = Chain.getValue(1);
2653   }
2654 
2655   uint64_t CalleePopBytes = NumBytes;
2656   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2657                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2658                              InFlag, DL);
2659   if (!Ins.empty())
2660     InFlag = Chain.getValue(1);
2661 
2662   // Handle result values, copying them out of physregs into vregs that we
2663   // return.
2664   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2665                          InVals, IsThisReturn,
2666                          IsThisReturn ? OutVals[0] : SDValue());
2667 }
2668 
2669 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2670                                              SelectionDAG &DAG) const {
2671   unsigned Reg = StringSwitch<unsigned>(RegName)
2672     .Case("m0", AMDGPU::M0)
2673     .Case("exec", AMDGPU::EXEC)
2674     .Case("exec_lo", AMDGPU::EXEC_LO)
2675     .Case("exec_hi", AMDGPU::EXEC_HI)
2676     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2677     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2678     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2679     .Default(AMDGPU::NoRegister);
2680 
2681   if (Reg == AMDGPU::NoRegister) {
2682     report_fatal_error(Twine("invalid register name \""
2683                              + StringRef(RegName)  + "\"."));
2684 
2685   }
2686 
2687   if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2688       Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2689     report_fatal_error(Twine("invalid register \""
2690                              + StringRef(RegName)  + "\" for subtarget."));
2691   }
2692 
2693   switch (Reg) {
2694   case AMDGPU::M0:
2695   case AMDGPU::EXEC_LO:
2696   case AMDGPU::EXEC_HI:
2697   case AMDGPU::FLAT_SCR_LO:
2698   case AMDGPU::FLAT_SCR_HI:
2699     if (VT.getSizeInBits() == 32)
2700       return Reg;
2701     break;
2702   case AMDGPU::EXEC:
2703   case AMDGPU::FLAT_SCR:
2704     if (VT.getSizeInBits() == 64)
2705       return Reg;
2706     break;
2707   default:
2708     llvm_unreachable("missing register type checking");
2709   }
2710 
2711   report_fatal_error(Twine("invalid type for register \""
2712                            + StringRef(RegName) + "\"."));
2713 }
2714 
2715 // If kill is not the last instruction, split the block so kill is always a
2716 // proper terminator.
2717 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2718                                                     MachineBasicBlock *BB) const {
2719   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2720 
2721   MachineBasicBlock::iterator SplitPoint(&MI);
2722   ++SplitPoint;
2723 
2724   if (SplitPoint == BB->end()) {
2725     // Don't bother with a new block.
2726     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2727     return BB;
2728   }
2729 
2730   MachineFunction *MF = BB->getParent();
2731   MachineBasicBlock *SplitBB
2732     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2733 
2734   MF->insert(++MachineFunction::iterator(BB), SplitBB);
2735   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2736 
2737   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2738   BB->addSuccessor(SplitBB);
2739 
2740   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2741   return SplitBB;
2742 }
2743 
2744 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2745 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2746 // will only do one iteration. In the worst case, this will loop 64 times.
2747 //
2748 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2749 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2750   const SIInstrInfo *TII,
2751   MachineRegisterInfo &MRI,
2752   MachineBasicBlock &OrigBB,
2753   MachineBasicBlock &LoopBB,
2754   const DebugLoc &DL,
2755   const MachineOperand &IdxReg,
2756   unsigned InitReg,
2757   unsigned ResultReg,
2758   unsigned PhiReg,
2759   unsigned InitSaveExecReg,
2760   int Offset,
2761   bool UseGPRIdxMode,
2762   bool IsIndirectSrc) {
2763   MachineBasicBlock::iterator I = LoopBB.begin();
2764 
2765   unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2766   unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2767   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2768   unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2769 
2770   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2771     .addReg(InitReg)
2772     .addMBB(&OrigBB)
2773     .addReg(ResultReg)
2774     .addMBB(&LoopBB);
2775 
2776   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2777     .addReg(InitSaveExecReg)
2778     .addMBB(&OrigBB)
2779     .addReg(NewExec)
2780     .addMBB(&LoopBB);
2781 
2782   // Read the next variant <- also loop target.
2783   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2784     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2785 
2786   // Compare the just read M0 value to all possible Idx values.
2787   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2788     .addReg(CurrentIdxReg)
2789     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2790 
2791   // Update EXEC, save the original EXEC value to VCC.
2792   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2793     .addReg(CondReg, RegState::Kill);
2794 
2795   MRI.setSimpleHint(NewExec, CondReg);
2796 
2797   if (UseGPRIdxMode) {
2798     unsigned IdxReg;
2799     if (Offset == 0) {
2800       IdxReg = CurrentIdxReg;
2801     } else {
2802       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2803       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2804         .addReg(CurrentIdxReg, RegState::Kill)
2805         .addImm(Offset);
2806     }
2807     unsigned IdxMode = IsIndirectSrc ?
2808       VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2809     MachineInstr *SetOn =
2810       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2811       .addReg(IdxReg, RegState::Kill)
2812       .addImm(IdxMode);
2813     SetOn->getOperand(3).setIsUndef();
2814   } else {
2815     // Move index from VCC into M0
2816     if (Offset == 0) {
2817       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2818         .addReg(CurrentIdxReg, RegState::Kill);
2819     } else {
2820       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2821         .addReg(CurrentIdxReg, RegState::Kill)
2822         .addImm(Offset);
2823     }
2824   }
2825 
2826   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2827   MachineInstr *InsertPt =
2828     BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2829     .addReg(AMDGPU::EXEC)
2830     .addReg(NewExec);
2831 
2832   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2833   // s_cbranch_scc0?
2834 
2835   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2836   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2837     .addMBB(&LoopBB);
2838 
2839   return InsertPt->getIterator();
2840 }
2841 
2842 // This has slightly sub-optimal regalloc when the source vector is killed by
2843 // the read. The register allocator does not understand that the kill is
2844 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2845 // subregister from it, using 1 more VGPR than necessary. This was saved when
2846 // this was expanded after register allocation.
2847 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2848                                                   MachineBasicBlock &MBB,
2849                                                   MachineInstr &MI,
2850                                                   unsigned InitResultReg,
2851                                                   unsigned PhiReg,
2852                                                   int Offset,
2853                                                   bool UseGPRIdxMode,
2854                                                   bool IsIndirectSrc) {
2855   MachineFunction *MF = MBB.getParent();
2856   MachineRegisterInfo &MRI = MF->getRegInfo();
2857   const DebugLoc &DL = MI.getDebugLoc();
2858   MachineBasicBlock::iterator I(&MI);
2859 
2860   unsigned DstReg = MI.getOperand(0).getReg();
2861   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2862   unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2863 
2864   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2865 
2866   // Save the EXEC mask
2867   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2868     .addReg(AMDGPU::EXEC);
2869 
2870   // To insert the loop we need to split the block. Move everything after this
2871   // point to a new block, and insert a new empty block between the two.
2872   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2873   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2874   MachineFunction::iterator MBBI(MBB);
2875   ++MBBI;
2876 
2877   MF->insert(MBBI, LoopBB);
2878   MF->insert(MBBI, RemainderBB);
2879 
2880   LoopBB->addSuccessor(LoopBB);
2881   LoopBB->addSuccessor(RemainderBB);
2882 
2883   // Move the rest of the block into a new block.
2884   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2885   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2886 
2887   MBB.addSuccessor(LoopBB);
2888 
2889   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2890 
2891   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2892                                       InitResultReg, DstReg, PhiReg, TmpExec,
2893                                       Offset, UseGPRIdxMode, IsIndirectSrc);
2894 
2895   MachineBasicBlock::iterator First = RemainderBB->begin();
2896   BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2897     .addReg(SaveExec);
2898 
2899   return InsPt;
2900 }
2901 
2902 // Returns subreg index, offset
2903 static std::pair<unsigned, int>
2904 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2905                             const TargetRegisterClass *SuperRC,
2906                             unsigned VecReg,
2907                             int Offset) {
2908   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2909 
2910   // Skip out of bounds offsets, or else we would end up using an undefined
2911   // register.
2912   if (Offset >= NumElts || Offset < 0)
2913     return std::make_pair(AMDGPU::sub0, Offset);
2914 
2915   return std::make_pair(AMDGPU::sub0 + Offset, 0);
2916 }
2917 
2918 // Return true if the index is an SGPR and was set.
2919 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
2920                                  MachineRegisterInfo &MRI,
2921                                  MachineInstr &MI,
2922                                  int Offset,
2923                                  bool UseGPRIdxMode,
2924                                  bool IsIndirectSrc) {
2925   MachineBasicBlock *MBB = MI.getParent();
2926   const DebugLoc &DL = MI.getDebugLoc();
2927   MachineBasicBlock::iterator I(&MI);
2928 
2929   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2930   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2931 
2932   assert(Idx->getReg() != AMDGPU::NoRegister);
2933 
2934   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2935     return false;
2936 
2937   if (UseGPRIdxMode) {
2938     unsigned IdxMode = IsIndirectSrc ?
2939       VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2940     if (Offset == 0) {
2941       MachineInstr *SetOn =
2942           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2943               .add(*Idx)
2944               .addImm(IdxMode);
2945 
2946       SetOn->getOperand(3).setIsUndef();
2947     } else {
2948       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2949       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
2950           .add(*Idx)
2951           .addImm(Offset);
2952       MachineInstr *SetOn =
2953         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2954         .addReg(Tmp, RegState::Kill)
2955         .addImm(IdxMode);
2956 
2957       SetOn->getOperand(3).setIsUndef();
2958     }
2959 
2960     return true;
2961   }
2962 
2963   if (Offset == 0) {
2964     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2965       .add(*Idx);
2966   } else {
2967     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2968       .add(*Idx)
2969       .addImm(Offset);
2970   }
2971 
2972   return true;
2973 }
2974 
2975 // Control flow needs to be inserted if indexing with a VGPR.
2976 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
2977                                           MachineBasicBlock &MBB,
2978                                           const GCNSubtarget &ST) {
2979   const SIInstrInfo *TII = ST.getInstrInfo();
2980   const SIRegisterInfo &TRI = TII->getRegisterInfo();
2981   MachineFunction *MF = MBB.getParent();
2982   MachineRegisterInfo &MRI = MF->getRegInfo();
2983 
2984   unsigned Dst = MI.getOperand(0).getReg();
2985   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
2986   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2987 
2988   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
2989 
2990   unsigned SubReg;
2991   std::tie(SubReg, Offset)
2992     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
2993 
2994   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2995 
2996   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
2997     MachineBasicBlock::iterator I(&MI);
2998     const DebugLoc &DL = MI.getDebugLoc();
2999 
3000     if (UseGPRIdxMode) {
3001       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3002       // to avoid interfering with other uses, so probably requires a new
3003       // optimization pass.
3004       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3005         .addReg(SrcReg, RegState::Undef, SubReg)
3006         .addReg(SrcReg, RegState::Implicit)
3007         .addReg(AMDGPU::M0, RegState::Implicit);
3008       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3009     } else {
3010       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3011         .addReg(SrcReg, RegState::Undef, SubReg)
3012         .addReg(SrcReg, RegState::Implicit);
3013     }
3014 
3015     MI.eraseFromParent();
3016 
3017     return &MBB;
3018   }
3019 
3020   const DebugLoc &DL = MI.getDebugLoc();
3021   MachineBasicBlock::iterator I(&MI);
3022 
3023   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3024   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3025 
3026   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3027 
3028   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3029                               Offset, UseGPRIdxMode, true);
3030   MachineBasicBlock *LoopBB = InsPt->getParent();
3031 
3032   if (UseGPRIdxMode) {
3033     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3034       .addReg(SrcReg, RegState::Undef, SubReg)
3035       .addReg(SrcReg, RegState::Implicit)
3036       .addReg(AMDGPU::M0, RegState::Implicit);
3037     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3038   } else {
3039     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3040       .addReg(SrcReg, RegState::Undef, SubReg)
3041       .addReg(SrcReg, RegState::Implicit);
3042   }
3043 
3044   MI.eraseFromParent();
3045 
3046   return LoopBB;
3047 }
3048 
3049 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3050                                  const TargetRegisterClass *VecRC) {
3051   switch (TRI.getRegSizeInBits(*VecRC)) {
3052   case 32: // 4 bytes
3053     return AMDGPU::V_MOVRELD_B32_V1;
3054   case 64: // 8 bytes
3055     return AMDGPU::V_MOVRELD_B32_V2;
3056   case 128: // 16 bytes
3057     return AMDGPU::V_MOVRELD_B32_V4;
3058   case 256: // 32 bytes
3059     return AMDGPU::V_MOVRELD_B32_V8;
3060   case 512: // 64 bytes
3061     return AMDGPU::V_MOVRELD_B32_V16;
3062   default:
3063     llvm_unreachable("unsupported size for MOVRELD pseudos");
3064   }
3065 }
3066 
3067 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3068                                           MachineBasicBlock &MBB,
3069                                           const GCNSubtarget &ST) {
3070   const SIInstrInfo *TII = ST.getInstrInfo();
3071   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3072   MachineFunction *MF = MBB.getParent();
3073   MachineRegisterInfo &MRI = MF->getRegInfo();
3074 
3075   unsigned Dst = MI.getOperand(0).getReg();
3076   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3077   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3078   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3079   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3080   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3081 
3082   // This can be an immediate, but will be folded later.
3083   assert(Val->getReg());
3084 
3085   unsigned SubReg;
3086   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3087                                                          SrcVec->getReg(),
3088                                                          Offset);
3089   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3090 
3091   if (Idx->getReg() == AMDGPU::NoRegister) {
3092     MachineBasicBlock::iterator I(&MI);
3093     const DebugLoc &DL = MI.getDebugLoc();
3094 
3095     assert(Offset == 0);
3096 
3097     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3098         .add(*SrcVec)
3099         .add(*Val)
3100         .addImm(SubReg);
3101 
3102     MI.eraseFromParent();
3103     return &MBB;
3104   }
3105 
3106   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3107     MachineBasicBlock::iterator I(&MI);
3108     const DebugLoc &DL = MI.getDebugLoc();
3109 
3110     if (UseGPRIdxMode) {
3111       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3112           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3113           .add(*Val)
3114           .addReg(Dst, RegState::ImplicitDefine)
3115           .addReg(SrcVec->getReg(), RegState::Implicit)
3116           .addReg(AMDGPU::M0, RegState::Implicit);
3117 
3118       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3119     } else {
3120       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3121 
3122       BuildMI(MBB, I, DL, MovRelDesc)
3123           .addReg(Dst, RegState::Define)
3124           .addReg(SrcVec->getReg())
3125           .add(*Val)
3126           .addImm(SubReg - AMDGPU::sub0);
3127     }
3128 
3129     MI.eraseFromParent();
3130     return &MBB;
3131   }
3132 
3133   if (Val->isReg())
3134     MRI.clearKillFlags(Val->getReg());
3135 
3136   const DebugLoc &DL = MI.getDebugLoc();
3137 
3138   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3139 
3140   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3141                               Offset, UseGPRIdxMode, false);
3142   MachineBasicBlock *LoopBB = InsPt->getParent();
3143 
3144   if (UseGPRIdxMode) {
3145     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3146         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3147         .add(*Val)                               // src0
3148         .addReg(Dst, RegState::ImplicitDefine)
3149         .addReg(PhiReg, RegState::Implicit)
3150         .addReg(AMDGPU::M0, RegState::Implicit);
3151     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3152   } else {
3153     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3154 
3155     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3156         .addReg(Dst, RegState::Define)
3157         .addReg(PhiReg)
3158         .add(*Val)
3159         .addImm(SubReg - AMDGPU::sub0);
3160   }
3161 
3162   MI.eraseFromParent();
3163 
3164   return LoopBB;
3165 }
3166 
3167 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3168   MachineInstr &MI, MachineBasicBlock *BB) const {
3169 
3170   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3171   MachineFunction *MF = BB->getParent();
3172   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3173 
3174   if (TII->isMIMG(MI)) {
3175     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3176       report_fatal_error("missing mem operand from MIMG instruction");
3177     }
3178     // Add a memoperand for mimg instructions so that they aren't assumed to
3179     // be ordered memory instuctions.
3180 
3181     return BB;
3182   }
3183 
3184   switch (MI.getOpcode()) {
3185   case AMDGPU::S_ADD_U64_PSEUDO:
3186   case AMDGPU::S_SUB_U64_PSEUDO: {
3187     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3188     const DebugLoc &DL = MI.getDebugLoc();
3189 
3190     MachineOperand &Dest = MI.getOperand(0);
3191     MachineOperand &Src0 = MI.getOperand(1);
3192     MachineOperand &Src1 = MI.getOperand(2);
3193 
3194     unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3195     unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3196 
3197     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3198      Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3199      &AMDGPU::SReg_32_XM0RegClass);
3200     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3201       Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3202       &AMDGPU::SReg_32_XM0RegClass);
3203 
3204     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3205       Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3206       &AMDGPU::SReg_32_XM0RegClass);
3207     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3208       Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3209       &AMDGPU::SReg_32_XM0RegClass);
3210 
3211     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3212 
3213     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3214     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3215     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3216       .add(Src0Sub0)
3217       .add(Src1Sub0);
3218     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3219       .add(Src0Sub1)
3220       .add(Src1Sub1);
3221     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3222       .addReg(DestSub0)
3223       .addImm(AMDGPU::sub0)
3224       .addReg(DestSub1)
3225       .addImm(AMDGPU::sub1);
3226     MI.eraseFromParent();
3227     return BB;
3228   }
3229   case AMDGPU::SI_INIT_M0: {
3230     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3231             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3232         .add(MI.getOperand(0));
3233     MI.eraseFromParent();
3234     return BB;
3235   }
3236   case AMDGPU::SI_INIT_EXEC:
3237     // This should be before all vector instructions.
3238     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3239             AMDGPU::EXEC)
3240         .addImm(MI.getOperand(0).getImm());
3241     MI.eraseFromParent();
3242     return BB;
3243 
3244   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3245     // Extract the thread count from an SGPR input and set EXEC accordingly.
3246     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3247     //
3248     // S_BFE_U32 count, input, {shift, 7}
3249     // S_BFM_B64 exec, count, 0
3250     // S_CMP_EQ_U32 count, 64
3251     // S_CMOV_B64 exec, -1
3252     MachineInstr *FirstMI = &*BB->begin();
3253     MachineRegisterInfo &MRI = MF->getRegInfo();
3254     unsigned InputReg = MI.getOperand(0).getReg();
3255     unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3256     bool Found = false;
3257 
3258     // Move the COPY of the input reg to the beginning, so that we can use it.
3259     for (auto I = BB->begin(); I != &MI; I++) {
3260       if (I->getOpcode() != TargetOpcode::COPY ||
3261           I->getOperand(0).getReg() != InputReg)
3262         continue;
3263 
3264       if (I == FirstMI) {
3265         FirstMI = &*++BB->begin();
3266       } else {
3267         I->removeFromParent();
3268         BB->insert(FirstMI, &*I);
3269       }
3270       Found = true;
3271       break;
3272     }
3273     assert(Found);
3274     (void)Found;
3275 
3276     // This should be before all vector instructions.
3277     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3278         .addReg(InputReg)
3279         .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3280     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3281             AMDGPU::EXEC)
3282         .addReg(CountReg)
3283         .addImm(0);
3284     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3285         .addReg(CountReg, RegState::Kill)
3286         .addImm(64);
3287     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3288             AMDGPU::EXEC)
3289         .addImm(-1);
3290     MI.eraseFromParent();
3291     return BB;
3292   }
3293 
3294   case AMDGPU::GET_GROUPSTATICSIZE: {
3295     DebugLoc DL = MI.getDebugLoc();
3296     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3297         .add(MI.getOperand(0))
3298         .addImm(MFI->getLDSSize());
3299     MI.eraseFromParent();
3300     return BB;
3301   }
3302   case AMDGPU::SI_INDIRECT_SRC_V1:
3303   case AMDGPU::SI_INDIRECT_SRC_V2:
3304   case AMDGPU::SI_INDIRECT_SRC_V4:
3305   case AMDGPU::SI_INDIRECT_SRC_V8:
3306   case AMDGPU::SI_INDIRECT_SRC_V16:
3307     return emitIndirectSrc(MI, *BB, *getSubtarget());
3308   case AMDGPU::SI_INDIRECT_DST_V1:
3309   case AMDGPU::SI_INDIRECT_DST_V2:
3310   case AMDGPU::SI_INDIRECT_DST_V4:
3311   case AMDGPU::SI_INDIRECT_DST_V8:
3312   case AMDGPU::SI_INDIRECT_DST_V16:
3313     return emitIndirectDst(MI, *BB, *getSubtarget());
3314   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3315   case AMDGPU::SI_KILL_I1_PSEUDO:
3316     return splitKillBlock(MI, BB);
3317   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3318     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3319 
3320     unsigned Dst = MI.getOperand(0).getReg();
3321     unsigned Src0 = MI.getOperand(1).getReg();
3322     unsigned Src1 = MI.getOperand(2).getReg();
3323     const DebugLoc &DL = MI.getDebugLoc();
3324     unsigned SrcCond = MI.getOperand(3).getReg();
3325 
3326     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3327     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3328     unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3329 
3330     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3331       .addReg(SrcCond);
3332     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3333       .addReg(Src0, 0, AMDGPU::sub0)
3334       .addReg(Src1, 0, AMDGPU::sub0)
3335       .addReg(SrcCondCopy);
3336     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3337       .addReg(Src0, 0, AMDGPU::sub1)
3338       .addReg(Src1, 0, AMDGPU::sub1)
3339       .addReg(SrcCondCopy);
3340 
3341     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3342       .addReg(DstLo)
3343       .addImm(AMDGPU::sub0)
3344       .addReg(DstHi)
3345       .addImm(AMDGPU::sub1);
3346     MI.eraseFromParent();
3347     return BB;
3348   }
3349   case AMDGPU::SI_BR_UNDEF: {
3350     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3351     const DebugLoc &DL = MI.getDebugLoc();
3352     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3353                            .add(MI.getOperand(0));
3354     Br->getOperand(1).setIsUndef(true); // read undef SCC
3355     MI.eraseFromParent();
3356     return BB;
3357   }
3358   case AMDGPU::ADJCALLSTACKUP:
3359   case AMDGPU::ADJCALLSTACKDOWN: {
3360     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3361     MachineInstrBuilder MIB(*MF, &MI);
3362 
3363     // Add an implicit use of the frame offset reg to prevent the restore copy
3364     // inserted after the call from being reorderd after stack operations in the
3365     // the caller's frame.
3366     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3367         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3368         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3369     return BB;
3370   }
3371   case AMDGPU::SI_CALL_ISEL:
3372   case AMDGPU::SI_TCRETURN_ISEL: {
3373     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3374     const DebugLoc &DL = MI.getDebugLoc();
3375     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3376 
3377     MachineRegisterInfo &MRI = MF->getRegInfo();
3378     unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3379     MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3380     assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3381 
3382     const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3383 
3384     MachineInstrBuilder MIB;
3385     if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3386       MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3387         .add(MI.getOperand(0))
3388         .addGlobalAddress(G);
3389     } else {
3390       MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3391         .add(MI.getOperand(0))
3392         .addGlobalAddress(G);
3393 
3394       // There is an additional imm operand for tcreturn, but it should be in the
3395       // right place already.
3396     }
3397 
3398     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3399       MIB.add(MI.getOperand(I));
3400 
3401     MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3402     MI.eraseFromParent();
3403     return BB;
3404   }
3405   default:
3406     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3407   }
3408 }
3409 
3410 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3411   return isTypeLegal(VT.getScalarType());
3412 }
3413 
3414 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3415   // This currently forces unfolding various combinations of fsub into fma with
3416   // free fneg'd operands. As long as we have fast FMA (controlled by
3417   // isFMAFasterThanFMulAndFAdd), we should perform these.
3418 
3419   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3420   // most of these combines appear to be cycle neutral but save on instruction
3421   // count / code size.
3422   return true;
3423 }
3424 
3425 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3426                                          EVT VT) const {
3427   if (!VT.isVector()) {
3428     return MVT::i1;
3429   }
3430   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3431 }
3432 
3433 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3434   // TODO: Should i16 be used always if legal? For now it would force VALU
3435   // shifts.
3436   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3437 }
3438 
3439 // Answering this is somewhat tricky and depends on the specific device which
3440 // have different rates for fma or all f64 operations.
3441 //
3442 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3443 // regardless of which device (although the number of cycles differs between
3444 // devices), so it is always profitable for f64.
3445 //
3446 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3447 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3448 // which we can always do even without fused FP ops since it returns the same
3449 // result as the separate operations and since it is always full
3450 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3451 // however does not support denormals, so we do report fma as faster if we have
3452 // a fast fma device and require denormals.
3453 //
3454 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3455   VT = VT.getScalarType();
3456 
3457   switch (VT.getSimpleVT().SimpleTy) {
3458   case MVT::f32: {
3459     // This is as fast on some subtargets. However, we always have full rate f32
3460     // mad available which returns the same result as the separate operations
3461     // which we should prefer over fma. We can't use this if we want to support
3462     // denormals, so only report this in these cases.
3463     if (Subtarget->hasFP32Denormals())
3464       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3465 
3466     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3467     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3468   }
3469   case MVT::f64:
3470     return true;
3471   case MVT::f16:
3472     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3473   default:
3474     break;
3475   }
3476 
3477   return false;
3478 }
3479 
3480 //===----------------------------------------------------------------------===//
3481 // Custom DAG Lowering Operations
3482 //===----------------------------------------------------------------------===//
3483 
3484 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3485 // wider vector type is legal.
3486 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3487                                              SelectionDAG &DAG) const {
3488   unsigned Opc = Op.getOpcode();
3489   EVT VT = Op.getValueType();
3490   assert(VT == MVT::v4f16);
3491 
3492   SDValue Lo, Hi;
3493   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3494 
3495   SDLoc SL(Op);
3496   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3497                              Op->getFlags());
3498   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3499                              Op->getFlags());
3500 
3501   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3502 }
3503 
3504 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3505 // wider vector type is legal.
3506 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3507                                               SelectionDAG &DAG) const {
3508   unsigned Opc = Op.getOpcode();
3509   EVT VT = Op.getValueType();
3510   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3511 
3512   SDValue Lo0, Hi0;
3513   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3514   SDValue Lo1, Hi1;
3515   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3516 
3517   SDLoc SL(Op);
3518 
3519   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3520                              Op->getFlags());
3521   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3522                              Op->getFlags());
3523 
3524   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3525 }
3526 
3527 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3528   switch (Op.getOpcode()) {
3529   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3530   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3531   case ISD::LOAD: {
3532     SDValue Result = LowerLOAD(Op, DAG);
3533     assert((!Result.getNode() ||
3534             Result.getNode()->getNumValues() == 2) &&
3535            "Load should return a value and a chain");
3536     return Result;
3537   }
3538 
3539   case ISD::FSIN:
3540   case ISD::FCOS:
3541     return LowerTrig(Op, DAG);
3542   case ISD::SELECT: return LowerSELECT(Op, DAG);
3543   case ISD::FDIV: return LowerFDIV(Op, DAG);
3544   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3545   case ISD::STORE: return LowerSTORE(Op, DAG);
3546   case ISD::GlobalAddress: {
3547     MachineFunction &MF = DAG.getMachineFunction();
3548     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3549     return LowerGlobalAddress(MFI, Op, DAG);
3550   }
3551   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3552   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3553   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3554   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3555   case ISD::INSERT_VECTOR_ELT:
3556     return lowerINSERT_VECTOR_ELT(Op, DAG);
3557   case ISD::EXTRACT_VECTOR_ELT:
3558     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3559   case ISD::BUILD_VECTOR:
3560     return lowerBUILD_VECTOR(Op, DAG);
3561   case ISD::FP_ROUND:
3562     return lowerFP_ROUND(Op, DAG);
3563   case ISD::TRAP:
3564     return lowerTRAP(Op, DAG);
3565   case ISD::DEBUGTRAP:
3566     return lowerDEBUGTRAP(Op, DAG);
3567   case ISD::FABS:
3568   case ISD::FNEG:
3569     return splitUnaryVectorOp(Op, DAG);
3570   case ISD::SHL:
3571   case ISD::SRA:
3572   case ISD::SRL:
3573   case ISD::ADD:
3574   case ISD::SUB:
3575   case ISD::MUL:
3576   case ISD::SMIN:
3577   case ISD::SMAX:
3578   case ISD::UMIN:
3579   case ISD::UMAX:
3580   case ISD::FMINNUM:
3581   case ISD::FMAXNUM:
3582   case ISD::FADD:
3583   case ISD::FMUL:
3584     return splitBinaryVectorOp(Op, DAG);
3585   }
3586   return SDValue();
3587 }
3588 
3589 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
3590                                        const SDLoc &DL,
3591                                        SelectionDAG &DAG, bool Unpacked) {
3592   if (!LoadVT.isVector())
3593     return Result;
3594 
3595   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3596     // Truncate to v2i16/v4i16.
3597     EVT IntLoadVT = LoadVT.changeTypeToInteger();
3598 
3599     // Workaround legalizer not scalarizing truncate after vector op
3600     // legalization byt not creating intermediate vector trunc.
3601     SmallVector<SDValue, 4> Elts;
3602     DAG.ExtractVectorElements(Result, Elts);
3603     for (SDValue &Elt : Elts)
3604       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3605 
3606     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3607 
3608     // Bitcast to original type (v2f16/v4f16).
3609     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3610   }
3611 
3612   // Cast back to the original packed type.
3613   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3614 }
3615 
3616 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
3617                                               MemSDNode *M,
3618                                               SelectionDAG &DAG,
3619                                               bool IsIntrinsic) const {
3620   SDLoc DL(M);
3621   SmallVector<SDValue, 10> Ops;
3622   Ops.reserve(M->getNumOperands());
3623 
3624   Ops.push_back(M->getOperand(0));
3625   if (IsIntrinsic)
3626     Ops.push_back(DAG.getConstant(Opcode, DL, MVT::i32));
3627 
3628   // Skip 1, as it is the intrinsic ID.
3629   for (unsigned I = 2, E = M->getNumOperands(); I != E; ++I)
3630     Ops.push_back(M->getOperand(I));
3631 
3632   bool Unpacked = Subtarget->hasUnpackedD16VMem();
3633   EVT LoadVT = M->getValueType(0);
3634 
3635   EVT EquivLoadVT = LoadVT;
3636   if (Unpacked && LoadVT.isVector()) {
3637     EquivLoadVT = LoadVT.isVector() ?
3638       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3639                        LoadVT.getVectorNumElements()) : LoadVT;
3640   }
3641 
3642   // Change from v4f16/v2f16 to EquivLoadVT.
3643   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3644 
3645   SDValue Load
3646     = DAG.getMemIntrinsicNode(
3647       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
3648       VTList, Ops, M->getMemoryVT(),
3649       M->getMemOperand());
3650   if (!Unpacked) // Just adjusted the opcode.
3651     return Load;
3652 
3653   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
3654 
3655   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
3656 }
3657 
3658 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3659                                           SmallVectorImpl<SDValue> &Results,
3660                                           SelectionDAG &DAG) const {
3661   switch (N->getOpcode()) {
3662   case ISD::INSERT_VECTOR_ELT: {
3663     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3664       Results.push_back(Res);
3665     return;
3666   }
3667   case ISD::EXTRACT_VECTOR_ELT: {
3668     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3669       Results.push_back(Res);
3670     return;
3671   }
3672   case ISD::INTRINSIC_WO_CHAIN: {
3673     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3674     switch (IID) {
3675     case Intrinsic::amdgcn_cvt_pkrtz: {
3676       SDValue Src0 = N->getOperand(1);
3677       SDValue Src1 = N->getOperand(2);
3678       SDLoc SL(N);
3679       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3680                                 Src0, Src1);
3681       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3682       return;
3683     }
3684     case Intrinsic::amdgcn_cvt_pknorm_i16:
3685     case Intrinsic::amdgcn_cvt_pknorm_u16:
3686     case Intrinsic::amdgcn_cvt_pk_i16:
3687     case Intrinsic::amdgcn_cvt_pk_u16: {
3688       SDValue Src0 = N->getOperand(1);
3689       SDValue Src1 = N->getOperand(2);
3690       SDLoc SL(N);
3691       unsigned Opcode;
3692 
3693       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3694         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
3695       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3696         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
3697       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3698         Opcode = AMDGPUISD::CVT_PK_I16_I32;
3699       else
3700         Opcode = AMDGPUISD::CVT_PK_U16_U32;
3701 
3702       SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
3703       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
3704       return;
3705     }
3706     }
3707     break;
3708   }
3709   case ISD::INTRINSIC_W_CHAIN: {
3710     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
3711       Results.push_back(Res);
3712       Results.push_back(Res.getValue(1));
3713       return;
3714     }
3715 
3716     break;
3717   }
3718   case ISD::SELECT: {
3719     SDLoc SL(N);
3720     EVT VT = N->getValueType(0);
3721     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3722     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3723     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3724 
3725     EVT SelectVT = NewVT;
3726     if (NewVT.bitsLT(MVT::i32)) {
3727       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3728       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3729       SelectVT = MVT::i32;
3730     }
3731 
3732     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3733                                     N->getOperand(0), LHS, RHS);
3734 
3735     if (NewVT != SelectVT)
3736       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3737     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3738     return;
3739   }
3740   case ISD::FNEG: {
3741     if (N->getValueType(0) != MVT::v2f16)
3742       break;
3743 
3744     SDLoc SL(N);
3745     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3746 
3747     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
3748                              BC,
3749                              DAG.getConstant(0x80008000, SL, MVT::i32));
3750     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3751     return;
3752   }
3753   case ISD::FABS: {
3754     if (N->getValueType(0) != MVT::v2f16)
3755       break;
3756 
3757     SDLoc SL(N);
3758     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3759 
3760     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
3761                              BC,
3762                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
3763     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3764     return;
3765   }
3766   default:
3767     break;
3768   }
3769 }
3770 
3771 /// Helper function for LowerBRCOND
3772 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3773 
3774   SDNode *Parent = Value.getNode();
3775   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3776        I != E; ++I) {
3777 
3778     if (I.getUse().get() != Value)
3779       continue;
3780 
3781     if (I->getOpcode() == Opcode)
3782       return *I;
3783   }
3784   return nullptr;
3785 }
3786 
3787 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3788   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3789     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3790     case Intrinsic::amdgcn_if:
3791       return AMDGPUISD::IF;
3792     case Intrinsic::amdgcn_else:
3793       return AMDGPUISD::ELSE;
3794     case Intrinsic::amdgcn_loop:
3795       return AMDGPUISD::LOOP;
3796     case Intrinsic::amdgcn_end_cf:
3797       llvm_unreachable("should not occur");
3798     default:
3799       return 0;
3800     }
3801   }
3802 
3803   // break, if_break, else_break are all only used as inputs to loop, not
3804   // directly as branch conditions.
3805   return 0;
3806 }
3807 
3808 void SITargetLowering::createDebuggerPrologueStackObjects(
3809     MachineFunction &MF) const {
3810   // Create stack objects that are used for emitting debugger prologue.
3811   //
3812   // Debugger prologue writes work group IDs and work item IDs to scratch memory
3813   // at fixed location in the following format:
3814   //   offset 0:  work group ID x
3815   //   offset 4:  work group ID y
3816   //   offset 8:  work group ID z
3817   //   offset 16: work item ID x
3818   //   offset 20: work item ID y
3819   //   offset 24: work item ID z
3820   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3821   int ObjectIdx = 0;
3822 
3823   // For each dimension:
3824   for (unsigned i = 0; i < 3; ++i) {
3825     // Create fixed stack object for work group ID.
3826     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
3827     Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
3828     // Create fixed stack object for work item ID.
3829     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
3830     Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
3831   }
3832 }
3833 
3834 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
3835   const Triple &TT = getTargetMachine().getTargetTriple();
3836   return (GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
3837           GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
3838          AMDGPU::shouldEmitConstantsToTextSection(TT);
3839 }
3840 
3841 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
3842   return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
3843           GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
3844           GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
3845          !shouldEmitFixup(GV) &&
3846          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3847 }
3848 
3849 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
3850   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
3851 }
3852 
3853 /// This transforms the control flow intrinsics to get the branch destination as
3854 /// last parameter, also switches branch target with BR if the need arise
3855 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
3856                                       SelectionDAG &DAG) const {
3857   SDLoc DL(BRCOND);
3858 
3859   SDNode *Intr = BRCOND.getOperand(1).getNode();
3860   SDValue Target = BRCOND.getOperand(2);
3861   SDNode *BR = nullptr;
3862   SDNode *SetCC = nullptr;
3863 
3864   if (Intr->getOpcode() == ISD::SETCC) {
3865     // As long as we negate the condition everything is fine
3866     SetCC = Intr;
3867     Intr = SetCC->getOperand(0).getNode();
3868 
3869   } else {
3870     // Get the target from BR if we don't negate the condition
3871     BR = findUser(BRCOND, ISD::BR);
3872     Target = BR->getOperand(1);
3873   }
3874 
3875   // FIXME: This changes the types of the intrinsics instead of introducing new
3876   // nodes with the correct types.
3877   // e.g. llvm.amdgcn.loop
3878 
3879   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
3880   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
3881 
3882   unsigned CFNode = isCFIntrinsic(Intr);
3883   if (CFNode == 0) {
3884     // This is a uniform branch so we don't need to legalize.
3885     return BRCOND;
3886   }
3887 
3888   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
3889                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
3890 
3891   assert(!SetCC ||
3892         (SetCC->getConstantOperandVal(1) == 1 &&
3893          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
3894                                                              ISD::SETNE));
3895 
3896   // operands of the new intrinsic call
3897   SmallVector<SDValue, 4> Ops;
3898   if (HaveChain)
3899     Ops.push_back(BRCOND.getOperand(0));
3900 
3901   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
3902   Ops.push_back(Target);
3903 
3904   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
3905 
3906   // build the new intrinsic call
3907   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
3908 
3909   if (!HaveChain) {
3910     SDValue Ops[] =  {
3911       SDValue(Result, 0),
3912       BRCOND.getOperand(0)
3913     };
3914 
3915     Result = DAG.getMergeValues(Ops, DL).getNode();
3916   }
3917 
3918   if (BR) {
3919     // Give the branch instruction our target
3920     SDValue Ops[] = {
3921       BR->getOperand(0),
3922       BRCOND.getOperand(2)
3923     };
3924     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
3925     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
3926     BR = NewBR.getNode();
3927   }
3928 
3929   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
3930 
3931   // Copy the intrinsic results to registers
3932   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
3933     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
3934     if (!CopyToReg)
3935       continue;
3936 
3937     Chain = DAG.getCopyToReg(
3938       Chain, DL,
3939       CopyToReg->getOperand(1),
3940       SDValue(Result, i - 1),
3941       SDValue());
3942 
3943     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
3944   }
3945 
3946   // Remove the old intrinsic from the chain
3947   DAG.ReplaceAllUsesOfValueWith(
3948     SDValue(Intr, Intr->getNumValues() - 1),
3949     Intr->getOperand(0));
3950 
3951   return Chain;
3952 }
3953 
3954 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
3955                                             SDValue Op,
3956                                             const SDLoc &DL,
3957                                             EVT VT) const {
3958   return Op.getValueType().bitsLE(VT) ?
3959       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
3960       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
3961 }
3962 
3963 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
3964   assert(Op.getValueType() == MVT::f16 &&
3965          "Do not know how to custom lower FP_ROUND for non-f16 type");
3966 
3967   SDValue Src = Op.getOperand(0);
3968   EVT SrcVT = Src.getValueType();
3969   if (SrcVT != MVT::f64)
3970     return Op;
3971 
3972   SDLoc DL(Op);
3973 
3974   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
3975   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
3976   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
3977 }
3978 
3979 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
3980   SDLoc SL(Op);
3981   SDValue Chain = Op.getOperand(0);
3982 
3983   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
3984       !Subtarget->isTrapHandlerEnabled())
3985     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
3986 
3987   MachineFunction &MF = DAG.getMachineFunction();
3988   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3989   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3990   assert(UserSGPR != AMDGPU::NoRegister);
3991   SDValue QueuePtr = CreateLiveInRegister(
3992     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3993   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
3994   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
3995                                    QueuePtr, SDValue());
3996   SDValue Ops[] = {
3997     ToReg,
3998     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
3999     SGPR01,
4000     ToReg.getValue(1)
4001   };
4002   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4003 }
4004 
4005 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4006   SDLoc SL(Op);
4007   SDValue Chain = Op.getOperand(0);
4008   MachineFunction &MF = DAG.getMachineFunction();
4009 
4010   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4011       !Subtarget->isTrapHandlerEnabled()) {
4012     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4013                                      "debugtrap handler not supported",
4014                                      Op.getDebugLoc(),
4015                                      DS_Warning);
4016     LLVMContext &Ctx = MF.getFunction().getContext();
4017     Ctx.diagnose(NoTrap);
4018     return Chain;
4019   }
4020 
4021   SDValue Ops[] = {
4022     Chain,
4023     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4024   };
4025   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4026 }
4027 
4028 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4029                                              SelectionDAG &DAG) const {
4030   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4031   if (Subtarget->hasApertureRegs()) {
4032     unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
4033         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4034         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4035     unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
4036         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4037         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4038     unsigned Encoding =
4039         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4040         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4041         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4042 
4043     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4044     SDValue ApertureReg = SDValue(
4045         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4046     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4047     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4048   }
4049 
4050   MachineFunction &MF = DAG.getMachineFunction();
4051   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4052   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4053   assert(UserSGPR != AMDGPU::NoRegister);
4054 
4055   SDValue QueuePtr = CreateLiveInRegister(
4056     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4057 
4058   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4059   // private_segment_aperture_base_hi.
4060   uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
4061 
4062   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4063 
4064   // TODO: Use custom target PseudoSourceValue.
4065   // TODO: We should use the value from the IR intrinsic call, but it might not
4066   // be available and how do we get it?
4067   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4068                                               AMDGPUASI.CONSTANT_ADDRESS));
4069 
4070   MachinePointerInfo PtrInfo(V, StructOffset);
4071   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4072                      MinAlign(64, StructOffset),
4073                      MachineMemOperand::MODereferenceable |
4074                          MachineMemOperand::MOInvariant);
4075 }
4076 
4077 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4078                                              SelectionDAG &DAG) const {
4079   SDLoc SL(Op);
4080   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4081 
4082   SDValue Src = ASC->getOperand(0);
4083   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4084 
4085   const AMDGPUTargetMachine &TM =
4086     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4087 
4088   // flat -> local/private
4089   if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4090     unsigned DestAS = ASC->getDestAddressSpace();
4091 
4092     if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
4093         DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
4094       unsigned NullVal = TM.getNullPointerValue(DestAS);
4095       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4096       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4097       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4098 
4099       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4100                          NonNull, Ptr, SegmentNullPtr);
4101     }
4102   }
4103 
4104   // local/private -> flat
4105   if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4106     unsigned SrcAS = ASC->getSrcAddressSpace();
4107 
4108     if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
4109         SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
4110       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4111       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4112 
4113       SDValue NonNull
4114         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4115 
4116       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4117       SDValue CvtPtr
4118         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4119 
4120       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4121                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4122                          FlatNullPtr);
4123     }
4124   }
4125 
4126   // global <-> flat are no-ops and never emitted.
4127 
4128   const MachineFunction &MF = DAG.getMachineFunction();
4129   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4130     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4131   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4132 
4133   return DAG.getUNDEF(ASC->getValueType(0));
4134 }
4135 
4136 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4137                                                  SelectionDAG &DAG) const {
4138   SDValue Vec = Op.getOperand(0);
4139   SDValue InsVal = Op.getOperand(1);
4140   SDValue Idx = Op.getOperand(2);
4141   EVT VecVT = Vec.getValueType();
4142   EVT EltVT = VecVT.getVectorElementType();
4143   unsigned VecSize = VecVT.getSizeInBits();
4144   unsigned EltSize = EltVT.getSizeInBits();
4145 
4146 
4147   assert(VecSize <= 64);
4148 
4149   unsigned NumElts = VecVT.getVectorNumElements();
4150   SDLoc SL(Op);
4151   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4152 
4153   if (NumElts == 4 && EltSize == 16 && KIdx) {
4154     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4155 
4156     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4157                                  DAG.getConstant(0, SL, MVT::i32));
4158     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4159                                  DAG.getConstant(1, SL, MVT::i32));
4160 
4161     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4162     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4163 
4164     unsigned Idx = KIdx->getZExtValue();
4165     bool InsertLo = Idx < 2;
4166     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4167       InsertLo ? LoVec : HiVec,
4168       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4169       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4170 
4171     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4172 
4173     SDValue Concat = InsertLo ?
4174       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4175       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4176 
4177     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4178   }
4179 
4180   if (isa<ConstantSDNode>(Idx))
4181     return SDValue();
4182 
4183   MVT IntVT = MVT::getIntegerVT(VecSize);
4184 
4185   // Avoid stack access for dynamic indexing.
4186   SDValue Val = InsVal;
4187   if (InsVal.getValueType() == MVT::f16)
4188       Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal);
4189 
4190   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4191   SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Val);
4192 
4193   assert(isPowerOf2_32(EltSize));
4194   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4195 
4196   // Convert vector index to bit-index.
4197   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4198 
4199   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4200   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4201                             DAG.getConstant(0xffff, SL, IntVT),
4202                             ScaledIdx);
4203 
4204   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4205   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4206                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4207 
4208   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4209   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4210 }
4211 
4212 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4213                                                   SelectionDAG &DAG) const {
4214   SDLoc SL(Op);
4215 
4216   EVT ResultVT = Op.getValueType();
4217   SDValue Vec = Op.getOperand(0);
4218   SDValue Idx = Op.getOperand(1);
4219   EVT VecVT = Vec.getValueType();
4220   unsigned VecSize = VecVT.getSizeInBits();
4221   EVT EltVT = VecVT.getVectorElementType();
4222   assert(VecSize <= 64);
4223 
4224   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4225 
4226   // Make sure we do any optimizations that will make it easier to fold
4227   // source modifiers before obscuring it with bit operations.
4228 
4229   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4230   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4231     return Combined;
4232 
4233   unsigned EltSize = EltVT.getSizeInBits();
4234   assert(isPowerOf2_32(EltSize));
4235 
4236   MVT IntVT = MVT::getIntegerVT(VecSize);
4237   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4238 
4239   // Convert vector index to bit-index (* EltSize)
4240   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4241 
4242   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4243   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4244 
4245   if (ResultVT == MVT::f16) {
4246     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4247     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4248   }
4249 
4250   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4251 }
4252 
4253 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4254                                             SelectionDAG &DAG) const {
4255   SDLoc SL(Op);
4256   EVT VT = Op.getValueType();
4257 
4258   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4259     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4260 
4261     // Turn into pair of packed build_vectors.
4262     // TODO: Special case for constants that can be materialized with s_mov_b64.
4263     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4264                                     { Op.getOperand(0), Op.getOperand(1) });
4265     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4266                                     { Op.getOperand(2), Op.getOperand(3) });
4267 
4268     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4269     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4270 
4271     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4272     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4273   }
4274 
4275   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4276 
4277   SDValue Lo = Op.getOperand(0);
4278   SDValue Hi = Op.getOperand(1);
4279 
4280   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4281   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4282 
4283   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4284   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4285 
4286   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4287                               DAG.getConstant(16, SL, MVT::i32));
4288 
4289   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4290 
4291   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4292 }
4293 
4294 bool
4295 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4296   // We can fold offsets for anything that doesn't require a GOT relocation.
4297   return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
4298           GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4299           GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4300          !shouldEmitGOTReloc(GA->getGlobal());
4301 }
4302 
4303 static SDValue
4304 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4305                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
4306                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
4307   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4308   // lowered to the following code sequence:
4309   //
4310   // For constant address space:
4311   //   s_getpc_b64 s[0:1]
4312   //   s_add_u32 s0, s0, $symbol
4313   //   s_addc_u32 s1, s1, 0
4314   //
4315   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4316   //   a fixup or relocation is emitted to replace $symbol with a literal
4317   //   constant, which is a pc-relative offset from the encoding of the $symbol
4318   //   operand to the global variable.
4319   //
4320   // For global address space:
4321   //   s_getpc_b64 s[0:1]
4322   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4323   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4324   //
4325   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4326   //   fixups or relocations are emitted to replace $symbol@*@lo and
4327   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4328   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
4329   //   operand to the global variable.
4330   //
4331   // What we want here is an offset from the value returned by s_getpc
4332   // (which is the address of the s_add_u32 instruction) to the global
4333   // variable, but since the encoding of $symbol starts 4 bytes after the start
4334   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4335   // small. This requires us to add 4 to the global variable offset in order to
4336   // compute the correct address.
4337   SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4338                                              GAFlags);
4339   SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4340                                              GAFlags == SIInstrInfo::MO_NONE ?
4341                                              GAFlags : GAFlags + 1);
4342   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4343 }
4344 
4345 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4346                                              SDValue Op,
4347                                              SelectionDAG &DAG) const {
4348   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4349   const GlobalValue *GV = GSD->getGlobal();
4350 
4351   if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
4352       GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
4353       GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS &&
4354       // FIXME: It isn't correct to rely on the type of the pointer. This should
4355       // be removed when address space 0 is 64-bit.
4356       !GV->getType()->getElementType()->isFunctionTy())
4357     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4358 
4359   SDLoc DL(GSD);
4360   EVT PtrVT = Op.getValueType();
4361 
4362   if (shouldEmitFixup(GV))
4363     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4364   else if (shouldEmitPCReloc(GV))
4365     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4366                                    SIInstrInfo::MO_REL32);
4367 
4368   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4369                                             SIInstrInfo::MO_GOTPCREL32);
4370 
4371   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4372   PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
4373   const DataLayout &DataLayout = DAG.getDataLayout();
4374   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4375   // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
4376   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
4377 
4378   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4379                      MachineMemOperand::MODereferenceable |
4380                          MachineMemOperand::MOInvariant);
4381 }
4382 
4383 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4384                                    const SDLoc &DL, SDValue V) const {
4385   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4386   // the destination register.
4387   //
4388   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4389   // so we will end up with redundant moves to m0.
4390   //
4391   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4392 
4393   // A Null SDValue creates a glue result.
4394   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4395                                   V, Chain);
4396   return SDValue(M0, 0);
4397 }
4398 
4399 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4400                                                  SDValue Op,
4401                                                  MVT VT,
4402                                                  unsigned Offset) const {
4403   SDLoc SL(Op);
4404   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4405                                            DAG.getEntryNode(), Offset, 4, false);
4406   // The local size values will have the hi 16-bits as zero.
4407   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4408                      DAG.getValueType(VT));
4409 }
4410 
4411 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4412                                         EVT VT) {
4413   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4414                                       "non-hsa intrinsic with hsa target",
4415                                       DL.getDebugLoc());
4416   DAG.getContext()->diagnose(BadIntrin);
4417   return DAG.getUNDEF(VT);
4418 }
4419 
4420 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4421                                          EVT VT) {
4422   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4423                                       "intrinsic not supported on subtarget",
4424                                       DL.getDebugLoc());
4425   DAG.getContext()->diagnose(BadIntrin);
4426   return DAG.getUNDEF(VT);
4427 }
4428 
4429 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
4430                                     ArrayRef<SDValue> Elts) {
4431   assert(!Elts.empty());
4432   MVT Type;
4433   unsigned NumElts;
4434 
4435   if (Elts.size() == 1) {
4436     Type = MVT::f32;
4437     NumElts = 1;
4438   } else if (Elts.size() == 2) {
4439     Type = MVT::v2f32;
4440     NumElts = 2;
4441   } else if (Elts.size() <= 4) {
4442     Type = MVT::v4f32;
4443     NumElts = 4;
4444   } else if (Elts.size() <= 8) {
4445     Type = MVT::v8f32;
4446     NumElts = 8;
4447   } else {
4448     assert(Elts.size() <= 16);
4449     Type = MVT::v16f32;
4450     NumElts = 16;
4451   }
4452 
4453   SmallVector<SDValue, 16> VecElts(NumElts);
4454   for (unsigned i = 0; i < Elts.size(); ++i) {
4455     SDValue Elt = Elts[i];
4456     if (Elt.getValueType() != MVT::f32)
4457       Elt = DAG.getBitcast(MVT::f32, Elt);
4458     VecElts[i] = Elt;
4459   }
4460   for (unsigned i = Elts.size(); i < NumElts; ++i)
4461     VecElts[i] = DAG.getUNDEF(MVT::f32);
4462 
4463   if (NumElts == 1)
4464     return VecElts[0];
4465   return DAG.getBuildVector(Type, DL, VecElts);
4466 }
4467 
4468 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
4469                              SDValue *GLC, SDValue *SLC) {
4470   auto CachePolicyConst = dyn_cast<ConstantSDNode>(CachePolicy.getNode());
4471   if (!CachePolicyConst)
4472     return false;
4473 
4474   uint64_t Value = CachePolicyConst->getZExtValue();
4475   SDLoc DL(CachePolicy);
4476   if (GLC) {
4477     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4478     Value &= ~(uint64_t)0x1;
4479   }
4480   if (SLC) {
4481     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4482     Value &= ~(uint64_t)0x2;
4483   }
4484 
4485   return Value == 0;
4486 }
4487 
4488 SDValue SITargetLowering::lowerImage(SDValue Op,
4489                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
4490                                      SelectionDAG &DAG) const {
4491   SDLoc DL(Op);
4492   MachineFunction &MF = DAG.getMachineFunction();
4493   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4494       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
4495   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
4496 
4497   SmallVector<EVT, 2> ResultTypes(Op->value_begin(), Op->value_end());
4498   bool IsD16 = false;
4499   SDValue VData;
4500   int NumVDataDwords;
4501   unsigned AddrIdx; // Index of first address argument
4502   unsigned DMask;
4503 
4504   if (BaseOpcode->Atomic) {
4505     VData = Op.getOperand(2);
4506 
4507     bool Is64Bit = VData.getValueType() == MVT::i64;
4508     if (BaseOpcode->AtomicX2) {
4509       SDValue VData2 = Op.getOperand(3);
4510       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
4511                                  {VData, VData2});
4512       if (Is64Bit)
4513         VData = DAG.getBitcast(MVT::v4i32, VData);
4514 
4515       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
4516       DMask = Is64Bit ? 0xf : 0x3;
4517       NumVDataDwords = Is64Bit ? 4 : 2;
4518       AddrIdx = 4;
4519     } else {
4520       DMask = Is64Bit ? 0x3 : 0x1;
4521       NumVDataDwords = Is64Bit ? 2 : 1;
4522       AddrIdx = 3;
4523     }
4524   } else {
4525     unsigned DMaskIdx;
4526 
4527     if (BaseOpcode->Store) {
4528       VData = Op.getOperand(2);
4529 
4530       MVT StoreVT = VData.getSimpleValueType();
4531       if (StoreVT.getScalarType() == MVT::f16) {
4532         if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4533             !BaseOpcode->HasD16)
4534           return Op; // D16 is unsupported for this instruction
4535 
4536         IsD16 = true;
4537         VData = handleD16VData(VData, DAG);
4538       }
4539 
4540       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
4541       DMaskIdx = 3;
4542     } else {
4543       MVT LoadVT = Op.getSimpleValueType();
4544       if (LoadVT.getScalarType() == MVT::f16) {
4545         if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4546             !BaseOpcode->HasD16)
4547           return Op; // D16 is unsupported for this instruction
4548 
4549         IsD16 = true;
4550         if (LoadVT.isVector() && Subtarget->hasUnpackedD16VMem())
4551           ResultTypes[0] = (LoadVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32;
4552       }
4553 
4554       NumVDataDwords = (ResultTypes[0].getSizeInBits() + 31) / 32;
4555       DMaskIdx = isa<MemSDNode>(Op) ? 2 : 1;
4556     }
4557 
4558     auto DMaskConst = dyn_cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
4559     if (!DMaskConst)
4560       return Op;
4561 
4562     AddrIdx = DMaskIdx + 1;
4563     DMask = DMaskConst->getZExtValue();
4564     if (!DMask && !BaseOpcode->Store) {
4565       // Eliminate no-op loads. Stores with dmask == 0 are *not* no-op: they
4566       // store the channels' default values.
4567       SDValue Undef = DAG.getUNDEF(Op.getValueType());
4568       if (isa<MemSDNode>(Op))
4569         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
4570       return Undef;
4571     }
4572   }
4573 
4574   unsigned NumVAddrs = BaseOpcode->NumExtraArgs +
4575                        (BaseOpcode->Gradients ? DimInfo->NumGradients : 0) +
4576                        (BaseOpcode->Coordinates ? DimInfo->NumCoords : 0) +
4577                        (BaseOpcode->LodOrClampOrMip ? 1 : 0);
4578   SmallVector<SDValue, 4> VAddrs;
4579   for (unsigned i = 0; i < NumVAddrs; ++i)
4580     VAddrs.push_back(Op.getOperand(AddrIdx + i));
4581   SDValue VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
4582 
4583   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
4584   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
4585   unsigned CtrlIdx; // Index of texfailctrl argument
4586   SDValue Unorm;
4587   if (!BaseOpcode->Sampler) {
4588     Unorm = True;
4589     CtrlIdx = AddrIdx + NumVAddrs + 1;
4590   } else {
4591     auto UnormConst =
4592         dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
4593     if (!UnormConst)
4594       return Op;
4595 
4596     Unorm = UnormConst->getZExtValue() ? True : False;
4597     CtrlIdx = AddrIdx + NumVAddrs + 3;
4598   }
4599 
4600   SDValue TexFail = Op.getOperand(CtrlIdx);
4601   auto TexFailConst = dyn_cast<ConstantSDNode>(TexFail.getNode());
4602   if (!TexFailConst || TexFailConst->getZExtValue() != 0)
4603     return Op;
4604 
4605   SDValue GLC;
4606   SDValue SLC;
4607   if (BaseOpcode->Atomic) {
4608     GLC = True; // TODO no-return optimization
4609     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC))
4610       return Op;
4611   } else {
4612     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC))
4613       return Op;
4614   }
4615 
4616   SmallVector<SDValue, 14> Ops;
4617   if (BaseOpcode->Store || BaseOpcode->Atomic)
4618     Ops.push_back(VData); // vdata
4619   Ops.push_back(VAddr);
4620   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
4621   if (BaseOpcode->Sampler)
4622     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
4623   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
4624   Ops.push_back(Unorm);
4625   Ops.push_back(GLC);
4626   Ops.push_back(SLC);
4627   Ops.push_back(False); // r128
4628   Ops.push_back(False); // tfe
4629   Ops.push_back(False); // lwe
4630   Ops.push_back(DimInfo->DA ? True : False);
4631   if (BaseOpcode->HasD16)
4632     Ops.push_back(IsD16 ? True : False);
4633   if (isa<MemSDNode>(Op))
4634     Ops.push_back(Op.getOperand(0)); // chain
4635 
4636   int NumVAddrDwords = VAddr.getValueType().getSizeInBits() / 32;
4637   int Opcode = -1;
4638 
4639   if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
4640     Opcode = AMDGPU::getMIMGOpcode(Intr->BaseOpcode, AMDGPU::MIMGEncGfx8,
4641                                    NumVDataDwords, NumVAddrDwords);
4642   if (Opcode == -1)
4643     Opcode = AMDGPU::getMIMGOpcode(Intr->BaseOpcode, AMDGPU::MIMGEncGfx6,
4644                                    NumVDataDwords, NumVAddrDwords);
4645   assert(Opcode != -1);
4646 
4647   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
4648   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
4649     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
4650     *MemRefs = MemOp->getMemOperand();
4651     NewNode->setMemRefs(MemRefs, MemRefs + 1);
4652   }
4653 
4654   if (BaseOpcode->AtomicX2) {
4655     SmallVector<SDValue, 1> Elt;
4656     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
4657     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
4658   } else if (IsD16 && !BaseOpcode->Store) {
4659     MVT LoadVT = Op.getSimpleValueType();
4660     SDValue Adjusted = adjustLoadValueTypeImpl(
4661         SDValue(NewNode, 0), LoadVT, DL, DAG, Subtarget->hasUnpackedD16VMem());
4662     return DAG.getMergeValues({Adjusted, SDValue(NewNode, 1)}, DL);
4663   }
4664 
4665   return SDValue(NewNode, 0);
4666 }
4667 
4668 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4669                                                   SelectionDAG &DAG) const {
4670   MachineFunction &MF = DAG.getMachineFunction();
4671   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
4672 
4673   EVT VT = Op.getValueType();
4674   SDLoc DL(Op);
4675   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4676 
4677   // TODO: Should this propagate fast-math-flags?
4678 
4679   switch (IntrinsicID) {
4680   case Intrinsic::amdgcn_implicit_buffer_ptr: {
4681     if (getSubtarget()->isAmdCodeObjectV2(MF.getFunction()))
4682       return emitNonHSAIntrinsicError(DAG, DL, VT);
4683     return getPreloadedValue(DAG, *MFI, VT,
4684                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
4685   }
4686   case Intrinsic::amdgcn_dispatch_ptr:
4687   case Intrinsic::amdgcn_queue_ptr: {
4688     if (!Subtarget->isAmdCodeObjectV2(MF.getFunction())) {
4689       DiagnosticInfoUnsupported BadIntrin(
4690           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
4691           DL.getDebugLoc());
4692       DAG.getContext()->diagnose(BadIntrin);
4693       return DAG.getUNDEF(VT);
4694     }
4695 
4696     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
4697       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
4698     return getPreloadedValue(DAG, *MFI, VT, RegID);
4699   }
4700   case Intrinsic::amdgcn_implicitarg_ptr: {
4701     if (MFI->isEntryFunction())
4702       return getImplicitArgPtr(DAG, DL);
4703     return getPreloadedValue(DAG, *MFI, VT,
4704                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
4705   }
4706   case Intrinsic::amdgcn_kernarg_segment_ptr: {
4707     return getPreloadedValue(DAG, *MFI, VT,
4708                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
4709   }
4710   case Intrinsic::amdgcn_dispatch_id: {
4711     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
4712   }
4713   case Intrinsic::amdgcn_rcp:
4714     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
4715   case Intrinsic::amdgcn_rsq:
4716     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4717   case Intrinsic::amdgcn_rsq_legacy:
4718     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
4719       return emitRemovedIntrinsicError(DAG, DL, VT);
4720 
4721     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
4722   case Intrinsic::amdgcn_rcp_legacy:
4723     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
4724       return emitRemovedIntrinsicError(DAG, DL, VT);
4725     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
4726   case Intrinsic::amdgcn_rsq_clamp: {
4727     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
4728       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
4729 
4730     Type *Type = VT.getTypeForEVT(*DAG.getContext());
4731     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
4732     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
4733 
4734     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4735     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
4736                               DAG.getConstantFP(Max, DL, VT));
4737     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
4738                        DAG.getConstantFP(Min, DL, VT));
4739   }
4740   case Intrinsic::r600_read_ngroups_x:
4741     if (Subtarget->isAmdHsaOS())
4742       return emitNonHSAIntrinsicError(DAG, DL, VT);
4743 
4744     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4745                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
4746   case Intrinsic::r600_read_ngroups_y:
4747     if (Subtarget->isAmdHsaOS())
4748       return emitNonHSAIntrinsicError(DAG, DL, VT);
4749 
4750     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4751                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
4752   case Intrinsic::r600_read_ngroups_z:
4753     if (Subtarget->isAmdHsaOS())
4754       return emitNonHSAIntrinsicError(DAG, DL, VT);
4755 
4756     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4757                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
4758   case Intrinsic::r600_read_global_size_x:
4759     if (Subtarget->isAmdHsaOS())
4760       return emitNonHSAIntrinsicError(DAG, DL, VT);
4761 
4762     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4763                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
4764   case Intrinsic::r600_read_global_size_y:
4765     if (Subtarget->isAmdHsaOS())
4766       return emitNonHSAIntrinsicError(DAG, DL, VT);
4767 
4768     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4769                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
4770   case Intrinsic::r600_read_global_size_z:
4771     if (Subtarget->isAmdHsaOS())
4772       return emitNonHSAIntrinsicError(DAG, DL, VT);
4773 
4774     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4775                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
4776   case Intrinsic::r600_read_local_size_x:
4777     if (Subtarget->isAmdHsaOS())
4778       return emitNonHSAIntrinsicError(DAG, DL, VT);
4779 
4780     return lowerImplicitZextParam(DAG, Op, MVT::i16,
4781                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
4782   case Intrinsic::r600_read_local_size_y:
4783     if (Subtarget->isAmdHsaOS())
4784       return emitNonHSAIntrinsicError(DAG, DL, VT);
4785 
4786     return lowerImplicitZextParam(DAG, Op, MVT::i16,
4787                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
4788   case Intrinsic::r600_read_local_size_z:
4789     if (Subtarget->isAmdHsaOS())
4790       return emitNonHSAIntrinsicError(DAG, DL, VT);
4791 
4792     return lowerImplicitZextParam(DAG, Op, MVT::i16,
4793                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
4794   case Intrinsic::amdgcn_workgroup_id_x:
4795   case Intrinsic::r600_read_tgid_x:
4796     return getPreloadedValue(DAG, *MFI, VT,
4797                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
4798   case Intrinsic::amdgcn_workgroup_id_y:
4799   case Intrinsic::r600_read_tgid_y:
4800     return getPreloadedValue(DAG, *MFI, VT,
4801                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
4802   case Intrinsic::amdgcn_workgroup_id_z:
4803   case Intrinsic::r600_read_tgid_z:
4804     return getPreloadedValue(DAG, *MFI, VT,
4805                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
4806   case Intrinsic::amdgcn_workitem_id_x: {
4807   case Intrinsic::r600_read_tidig_x:
4808     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4809                           SDLoc(DAG.getEntryNode()),
4810                           MFI->getArgInfo().WorkItemIDX);
4811   }
4812   case Intrinsic::amdgcn_workitem_id_y:
4813   case Intrinsic::r600_read_tidig_y:
4814     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4815                           SDLoc(DAG.getEntryNode()),
4816                           MFI->getArgInfo().WorkItemIDY);
4817   case Intrinsic::amdgcn_workitem_id_z:
4818   case Intrinsic::r600_read_tidig_z:
4819     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4820                           SDLoc(DAG.getEntryNode()),
4821                           MFI->getArgInfo().WorkItemIDZ);
4822   case AMDGPUIntrinsic::SI_load_const: {
4823     SDValue Ops[] = {
4824       Op.getOperand(1),
4825       Op.getOperand(2)
4826     };
4827 
4828     MachineMemOperand *MMO = MF.getMachineMemOperand(
4829         MachinePointerInfo(),
4830         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
4831             MachineMemOperand::MOInvariant,
4832         VT.getStoreSize(), 4);
4833     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
4834                                    Op->getVTList(), Ops, VT, MMO);
4835   }
4836   case Intrinsic::amdgcn_fdiv_fast:
4837     return lowerFDIV_FAST(Op, DAG);
4838   case Intrinsic::amdgcn_interp_mov: {
4839     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4840     SDValue Glue = M0.getValue(1);
4841     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
4842                        Op.getOperand(2), Op.getOperand(3), Glue);
4843   }
4844   case Intrinsic::amdgcn_interp_p1: {
4845     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4846     SDValue Glue = M0.getValue(1);
4847     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
4848                        Op.getOperand(2), Op.getOperand(3), Glue);
4849   }
4850   case Intrinsic::amdgcn_interp_p2: {
4851     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
4852     SDValue Glue = SDValue(M0.getNode(), 1);
4853     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
4854                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
4855                        Glue);
4856   }
4857   case Intrinsic::amdgcn_sin:
4858     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
4859 
4860   case Intrinsic::amdgcn_cos:
4861     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
4862 
4863   case Intrinsic::amdgcn_log_clamp: {
4864     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
4865       return SDValue();
4866 
4867     DiagnosticInfoUnsupported BadIntrin(
4868       MF.getFunction(), "intrinsic not supported on subtarget",
4869       DL.getDebugLoc());
4870       DAG.getContext()->diagnose(BadIntrin);
4871       return DAG.getUNDEF(VT);
4872   }
4873   case Intrinsic::amdgcn_ldexp:
4874     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
4875                        Op.getOperand(1), Op.getOperand(2));
4876 
4877   case Intrinsic::amdgcn_fract:
4878     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
4879 
4880   case Intrinsic::amdgcn_class:
4881     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
4882                        Op.getOperand(1), Op.getOperand(2));
4883   case Intrinsic::amdgcn_div_fmas:
4884     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
4885                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
4886                        Op.getOperand(4));
4887 
4888   case Intrinsic::amdgcn_div_fixup:
4889     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
4890                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4891 
4892   case Intrinsic::amdgcn_trig_preop:
4893     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
4894                        Op.getOperand(1), Op.getOperand(2));
4895   case Intrinsic::amdgcn_div_scale: {
4896     // 3rd parameter required to be a constant.
4897     const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4898     if (!Param)
4899       return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
4900 
4901     // Translate to the operands expected by the machine instruction. The
4902     // first parameter must be the same as the first instruction.
4903     SDValue Numerator = Op.getOperand(1);
4904     SDValue Denominator = Op.getOperand(2);
4905 
4906     // Note this order is opposite of the machine instruction's operations,
4907     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
4908     // intrinsic has the numerator as the first operand to match a normal
4909     // division operation.
4910 
4911     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
4912 
4913     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
4914                        Denominator, Numerator);
4915   }
4916   case Intrinsic::amdgcn_icmp: {
4917     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4918     if (!CD)
4919       return DAG.getUNDEF(VT);
4920 
4921     int CondCode = CD->getSExtValue();
4922     if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4923         CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4924       return DAG.getUNDEF(VT);
4925 
4926     ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4927     ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4928     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4929                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
4930   }
4931   case Intrinsic::amdgcn_fcmp: {
4932     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4933     if (!CD)
4934       return DAG.getUNDEF(VT);
4935 
4936     int CondCode = CD->getSExtValue();
4937     if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4938         CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
4939       return DAG.getUNDEF(VT);
4940 
4941     FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4942     ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4943     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4944                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
4945   }
4946   case Intrinsic::amdgcn_fmed3:
4947     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
4948                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4949   case Intrinsic::amdgcn_fdot2:
4950     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
4951                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4952   case Intrinsic::amdgcn_fmul_legacy:
4953     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
4954                        Op.getOperand(1), Op.getOperand(2));
4955   case Intrinsic::amdgcn_sffbh:
4956     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
4957   case Intrinsic::amdgcn_sbfe:
4958     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
4959                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4960   case Intrinsic::amdgcn_ubfe:
4961     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
4962                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4963   case Intrinsic::amdgcn_cvt_pkrtz:
4964   case Intrinsic::amdgcn_cvt_pknorm_i16:
4965   case Intrinsic::amdgcn_cvt_pknorm_u16:
4966   case Intrinsic::amdgcn_cvt_pk_i16:
4967   case Intrinsic::amdgcn_cvt_pk_u16: {
4968     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
4969     EVT VT = Op.getValueType();
4970     unsigned Opcode;
4971 
4972     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
4973       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
4974     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
4975       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4976     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
4977       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4978     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
4979       Opcode = AMDGPUISD::CVT_PK_I16_I32;
4980     else
4981       Opcode = AMDGPUISD::CVT_PK_U16_U32;
4982 
4983     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
4984                                Op.getOperand(1), Op.getOperand(2));
4985     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
4986   }
4987   case Intrinsic::amdgcn_wqm: {
4988     SDValue Src = Op.getOperand(1);
4989     return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
4990                    0);
4991   }
4992   case Intrinsic::amdgcn_wwm: {
4993     SDValue Src = Op.getOperand(1);
4994     return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
4995                    0);
4996   }
4997   case Intrinsic::amdgcn_fmad_ftz:
4998     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
4999                        Op.getOperand(2), Op.getOperand(3));
5000   default:
5001     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5002             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5003       return lowerImage(Op, ImageDimIntr, DAG);
5004 
5005     return Op;
5006   }
5007 }
5008 
5009 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
5010                                                  SelectionDAG &DAG) const {
5011   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5012   SDLoc DL(Op);
5013 
5014   switch (IntrID) {
5015   case Intrinsic::amdgcn_atomic_inc:
5016   case Intrinsic::amdgcn_atomic_dec:
5017   case Intrinsic::amdgcn_ds_fadd:
5018   case Intrinsic::amdgcn_ds_fmin:
5019   case Intrinsic::amdgcn_ds_fmax: {
5020     MemSDNode *M = cast<MemSDNode>(Op);
5021     unsigned Opc;
5022     switch (IntrID) {
5023     case Intrinsic::amdgcn_atomic_inc:
5024       Opc = AMDGPUISD::ATOMIC_INC;
5025       break;
5026     case Intrinsic::amdgcn_atomic_dec:
5027       Opc = AMDGPUISD::ATOMIC_DEC;
5028       break;
5029     case Intrinsic::amdgcn_ds_fadd:
5030       Opc = AMDGPUISD::ATOMIC_LOAD_FADD;
5031       break;
5032     case Intrinsic::amdgcn_ds_fmin:
5033       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
5034       break;
5035     case Intrinsic::amdgcn_ds_fmax:
5036       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
5037       break;
5038     default:
5039       llvm_unreachable("Unknown intrinsic!");
5040     }
5041     SDValue Ops[] = {
5042       M->getOperand(0), // Chain
5043       M->getOperand(2), // Ptr
5044       M->getOperand(3)  // Value
5045     };
5046 
5047     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
5048                                    M->getMemoryVT(), M->getMemOperand());
5049   }
5050   case Intrinsic::amdgcn_buffer_load:
5051   case Intrinsic::amdgcn_buffer_load_format: {
5052     SDValue Ops[] = {
5053       Op.getOperand(0), // Chain
5054       Op.getOperand(2), // rsrc
5055       Op.getOperand(3), // vindex
5056       Op.getOperand(4), // offset
5057       Op.getOperand(5), // glc
5058       Op.getOperand(6)  // slc
5059     };
5060 
5061     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
5062         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5063     EVT VT = Op.getValueType();
5064     EVT IntVT = VT.changeTypeToInteger();
5065     auto *M = cast<MemSDNode>(Op);
5066     EVT LoadVT = Op.getValueType();
5067     bool IsD16 = LoadVT.getScalarType() == MVT::f16;
5068     if (IsD16)
5069       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG);
5070 
5071     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5072                                    M->getMemOperand());
5073   }
5074   case Intrinsic::amdgcn_tbuffer_load: {
5075     MemSDNode *M = cast<MemSDNode>(Op);
5076     EVT LoadVT = Op.getValueType();
5077     bool IsD16 = LoadVT.getScalarType() == MVT::f16;
5078     if (IsD16) {
5079       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, M, DAG);
5080     }
5081 
5082     SDValue Ops[] = {
5083       Op.getOperand(0),  // Chain
5084       Op.getOperand(2),  // rsrc
5085       Op.getOperand(3),  // vindex
5086       Op.getOperand(4),  // voffset
5087       Op.getOperand(5),  // soffset
5088       Op.getOperand(6),  // offset
5089       Op.getOperand(7),  // dfmt
5090       Op.getOperand(8),  // nfmt
5091       Op.getOperand(9),  // glc
5092       Op.getOperand(10)   // slc
5093     };
5094 
5095     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5096                                    Op->getVTList(), Ops, LoadVT,
5097                                    M->getMemOperand());
5098   }
5099   case Intrinsic::amdgcn_buffer_atomic_swap:
5100   case Intrinsic::amdgcn_buffer_atomic_add:
5101   case Intrinsic::amdgcn_buffer_atomic_sub:
5102   case Intrinsic::amdgcn_buffer_atomic_smin:
5103   case Intrinsic::amdgcn_buffer_atomic_umin:
5104   case Intrinsic::amdgcn_buffer_atomic_smax:
5105   case Intrinsic::amdgcn_buffer_atomic_umax:
5106   case Intrinsic::amdgcn_buffer_atomic_and:
5107   case Intrinsic::amdgcn_buffer_atomic_or:
5108   case Intrinsic::amdgcn_buffer_atomic_xor: {
5109     SDValue Ops[] = {
5110       Op.getOperand(0), // Chain
5111       Op.getOperand(2), // vdata
5112       Op.getOperand(3), // rsrc
5113       Op.getOperand(4), // vindex
5114       Op.getOperand(5), // offset
5115       Op.getOperand(6)  // slc
5116     };
5117     EVT VT = Op.getValueType();
5118 
5119     auto *M = cast<MemSDNode>(Op);
5120     unsigned Opcode = 0;
5121 
5122     switch (IntrID) {
5123     case Intrinsic::amdgcn_buffer_atomic_swap:
5124       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
5125       break;
5126     case Intrinsic::amdgcn_buffer_atomic_add:
5127       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
5128       break;
5129     case Intrinsic::amdgcn_buffer_atomic_sub:
5130       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
5131       break;
5132     case Intrinsic::amdgcn_buffer_atomic_smin:
5133       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
5134       break;
5135     case Intrinsic::amdgcn_buffer_atomic_umin:
5136       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
5137       break;
5138     case Intrinsic::amdgcn_buffer_atomic_smax:
5139       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
5140       break;
5141     case Intrinsic::amdgcn_buffer_atomic_umax:
5142       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
5143       break;
5144     case Intrinsic::amdgcn_buffer_atomic_and:
5145       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
5146       break;
5147     case Intrinsic::amdgcn_buffer_atomic_or:
5148       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5149       break;
5150     case Intrinsic::amdgcn_buffer_atomic_xor:
5151       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5152       break;
5153     default:
5154       llvm_unreachable("unhandled atomic opcode");
5155     }
5156 
5157     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5158                                    M->getMemOperand());
5159   }
5160 
5161   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
5162     SDValue Ops[] = {
5163       Op.getOperand(0), // Chain
5164       Op.getOperand(2), // src
5165       Op.getOperand(3), // cmp
5166       Op.getOperand(4), // rsrc
5167       Op.getOperand(5), // vindex
5168       Op.getOperand(6), // offset
5169       Op.getOperand(7)  // slc
5170     };
5171     EVT VT = Op.getValueType();
5172     auto *M = cast<MemSDNode>(Op);
5173 
5174     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
5175                                    Op->getVTList(), Ops, VT, M->getMemOperand());
5176   }
5177 
5178   default:
5179     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5180             AMDGPU::getImageDimIntrinsicInfo(IntrID))
5181       return lowerImage(Op, ImageDimIntr, DAG);
5182 
5183     return SDValue();
5184   }
5185 }
5186 
5187 SDValue SITargetLowering::handleD16VData(SDValue VData,
5188                                          SelectionDAG &DAG) const {
5189   EVT StoreVT = VData.getValueType();
5190 
5191   // No change for f16 and legal vector D16 types.
5192   if (!StoreVT.isVector())
5193     return VData;
5194 
5195   SDLoc DL(VData);
5196   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
5197 
5198   if (Subtarget->hasUnpackedD16VMem()) {
5199     // We need to unpack the packed data to store.
5200     EVT IntStoreVT = StoreVT.changeTypeToInteger();
5201     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
5202 
5203     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
5204                                         StoreVT.getVectorNumElements());
5205     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
5206     return DAG.UnrollVectorOp(ZExt.getNode());
5207   }
5208 
5209   assert(isTypeLegal(StoreVT));
5210   return VData;
5211 }
5212 
5213 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5214                                               SelectionDAG &DAG) const {
5215   SDLoc DL(Op);
5216   SDValue Chain = Op.getOperand(0);
5217   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5218   MachineFunction &MF = DAG.getMachineFunction();
5219 
5220   switch (IntrinsicID) {
5221   case Intrinsic::amdgcn_exp: {
5222     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5223     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5224     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
5225     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
5226 
5227     const SDValue Ops[] = {
5228       Chain,
5229       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5230       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
5231       Op.getOperand(4), // src0
5232       Op.getOperand(5), // src1
5233       Op.getOperand(6), // src2
5234       Op.getOperand(7), // src3
5235       DAG.getTargetConstant(0, DL, MVT::i1), // compr
5236       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5237     };
5238 
5239     unsigned Opc = Done->isNullValue() ?
5240       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5241     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5242   }
5243   case Intrinsic::amdgcn_exp_compr: {
5244     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5245     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5246     SDValue Src0 = Op.getOperand(4);
5247     SDValue Src1 = Op.getOperand(5);
5248     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
5249     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
5250 
5251     SDValue Undef = DAG.getUNDEF(MVT::f32);
5252     const SDValue Ops[] = {
5253       Chain,
5254       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5255       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
5256       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
5257       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
5258       Undef, // src2
5259       Undef, // src3
5260       DAG.getTargetConstant(1, DL, MVT::i1), // compr
5261       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5262     };
5263 
5264     unsigned Opc = Done->isNullValue() ?
5265       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5266     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5267   }
5268   case Intrinsic::amdgcn_s_sendmsg:
5269   case Intrinsic::amdgcn_s_sendmsghalt: {
5270     unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
5271       AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
5272     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
5273     SDValue Glue = Chain.getValue(1);
5274     return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
5275                        Op.getOperand(2), Glue);
5276   }
5277   case Intrinsic::amdgcn_init_exec: {
5278     return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
5279                        Op.getOperand(2));
5280   }
5281   case Intrinsic::amdgcn_init_exec_from_input: {
5282     return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
5283                        Op.getOperand(2), Op.getOperand(3));
5284   }
5285   case AMDGPUIntrinsic::AMDGPU_kill: {
5286     SDValue Src = Op.getOperand(2);
5287     if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
5288       if (!K->isNegative())
5289         return Chain;
5290 
5291       SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
5292       return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
5293     }
5294 
5295     SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
5296     return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
5297   }
5298   case Intrinsic::amdgcn_s_barrier: {
5299     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
5300       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5301       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
5302       if (WGSize <= ST.getWavefrontSize())
5303         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
5304                                           Op.getOperand(0)), 0);
5305     }
5306     return SDValue();
5307   };
5308   case AMDGPUIntrinsic::SI_tbuffer_store: {
5309 
5310     // Extract vindex and voffset from vaddr as appropriate
5311     const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10));
5312     const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11));
5313     SDValue VAddr = Op.getOperand(5);
5314 
5315     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
5316 
5317     assert(!(OffEn->isOne() && IdxEn->isOne()) &&
5318            "Legacy intrinsic doesn't support both offset and index - use new version");
5319 
5320     SDValue VIndex = IdxEn->isOne() ? VAddr : Zero;
5321     SDValue VOffset = OffEn->isOne() ? VAddr : Zero;
5322 
5323     // Deal with the vec-3 case
5324     const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4));
5325     auto Opcode = NumChannels->getZExtValue() == 3 ?
5326       AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT;
5327 
5328     SDValue Ops[] = {
5329      Chain,
5330      Op.getOperand(3),  // vdata
5331      Op.getOperand(2),  // rsrc
5332      VIndex,
5333      VOffset,
5334      Op.getOperand(6),  // soffset
5335      Op.getOperand(7),  // inst_offset
5336      Op.getOperand(8),  // dfmt
5337      Op.getOperand(9),  // nfmt
5338      Op.getOperand(12), // glc
5339      Op.getOperand(13), // slc
5340     };
5341 
5342     assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 &&
5343            "Value of tfe other than zero is unsupported");
5344 
5345     EVT VT = Op.getOperand(3).getValueType();
5346     MachineMemOperand *MMO = MF.getMachineMemOperand(
5347       MachinePointerInfo(),
5348       MachineMemOperand::MOStore,
5349       VT.getStoreSize(), 4);
5350     return DAG.getMemIntrinsicNode(Opcode, DL,
5351                                    Op->getVTList(), Ops, VT, MMO);
5352   }
5353 
5354   case Intrinsic::amdgcn_tbuffer_store: {
5355     SDValue VData = Op.getOperand(2);
5356     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5357     if (IsD16)
5358       VData = handleD16VData(VData, DAG);
5359     SDValue Ops[] = {
5360       Chain,
5361       VData,             // vdata
5362       Op.getOperand(3),  // rsrc
5363       Op.getOperand(4),  // vindex
5364       Op.getOperand(5),  // voffset
5365       Op.getOperand(6),  // soffset
5366       Op.getOperand(7),  // offset
5367       Op.getOperand(8),  // dfmt
5368       Op.getOperand(9),  // nfmt
5369       Op.getOperand(10), // glc
5370       Op.getOperand(11)  // slc
5371     };
5372     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
5373                            AMDGPUISD::TBUFFER_STORE_FORMAT;
5374     MemSDNode *M = cast<MemSDNode>(Op);
5375     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5376                                    M->getMemoryVT(), M->getMemOperand());
5377   }
5378 
5379   case Intrinsic::amdgcn_buffer_store:
5380   case Intrinsic::amdgcn_buffer_store_format: {
5381     SDValue VData = Op.getOperand(2);
5382     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5383     if (IsD16)
5384       VData = handleD16VData(VData, DAG);
5385     SDValue Ops[] = {
5386       Chain,
5387       VData,            // vdata
5388       Op.getOperand(3), // rsrc
5389       Op.getOperand(4), // vindex
5390       Op.getOperand(5), // offset
5391       Op.getOperand(6), // glc
5392       Op.getOperand(7)  // slc
5393     };
5394     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
5395                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
5396     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
5397     MemSDNode *M = cast<MemSDNode>(Op);
5398     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5399                                    M->getMemoryVT(), M->getMemOperand());
5400   }
5401   default: {
5402     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5403             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5404       return lowerImage(Op, ImageDimIntr, DAG);
5405 
5406     return Op;
5407   }
5408   }
5409 }
5410 
5411 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
5412                                  ISD::LoadExtType ExtType, SDValue Op,
5413                                  const SDLoc &SL, EVT VT) {
5414   if (VT.bitsLT(Op.getValueType()))
5415     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
5416 
5417   switch (ExtType) {
5418   case ISD::SEXTLOAD:
5419     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
5420   case ISD::ZEXTLOAD:
5421     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
5422   case ISD::EXTLOAD:
5423     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
5424   case ISD::NON_EXTLOAD:
5425     return Op;
5426   }
5427 
5428   llvm_unreachable("invalid ext type");
5429 }
5430 
5431 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
5432   SelectionDAG &DAG = DCI.DAG;
5433   if (Ld->getAlignment() < 4 || Ld->isDivergent())
5434     return SDValue();
5435 
5436   // FIXME: Constant loads should all be marked invariant.
5437   unsigned AS = Ld->getAddressSpace();
5438   if (AS != AMDGPUASI.CONSTANT_ADDRESS &&
5439       AS != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
5440       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
5441     return SDValue();
5442 
5443   // Don't do this early, since it may interfere with adjacent load merging for
5444   // illegal types. We can avoid losing alignment information for exotic types
5445   // pre-legalize.
5446   EVT MemVT = Ld->getMemoryVT();
5447   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
5448       MemVT.getSizeInBits() >= 32)
5449     return SDValue();
5450 
5451   SDLoc SL(Ld);
5452 
5453   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
5454          "unexpected vector extload");
5455 
5456   // TODO: Drop only high part of range.
5457   SDValue Ptr = Ld->getBasePtr();
5458   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
5459                                 MVT::i32, SL, Ld->getChain(), Ptr,
5460                                 Ld->getOffset(),
5461                                 Ld->getPointerInfo(), MVT::i32,
5462                                 Ld->getAlignment(),
5463                                 Ld->getMemOperand()->getFlags(),
5464                                 Ld->getAAInfo(),
5465                                 nullptr); // Drop ranges
5466 
5467   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
5468   if (MemVT.isFloatingPoint()) {
5469     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
5470            "unexpected fp extload");
5471     TruncVT = MemVT.changeTypeToInteger();
5472   }
5473 
5474   SDValue Cvt = NewLoad;
5475   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
5476     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
5477                       DAG.getValueType(TruncVT));
5478   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
5479              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
5480     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
5481   } else {
5482     assert(Ld->getExtensionType() == ISD::EXTLOAD);
5483   }
5484 
5485   EVT VT = Ld->getValueType(0);
5486   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
5487 
5488   DCI.AddToWorklist(Cvt.getNode());
5489 
5490   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
5491   // the appropriate extension from the 32-bit load.
5492   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
5493   DCI.AddToWorklist(Cvt.getNode());
5494 
5495   // Handle conversion back to floating point if necessary.
5496   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
5497 
5498   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
5499 }
5500 
5501 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5502   SDLoc DL(Op);
5503   LoadSDNode *Load = cast<LoadSDNode>(Op);
5504   ISD::LoadExtType ExtType = Load->getExtensionType();
5505   EVT MemVT = Load->getMemoryVT();
5506 
5507   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
5508     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
5509       return SDValue();
5510 
5511     // FIXME: Copied from PPC
5512     // First, load into 32 bits, then truncate to 1 bit.
5513 
5514     SDValue Chain = Load->getChain();
5515     SDValue BasePtr = Load->getBasePtr();
5516     MachineMemOperand *MMO = Load->getMemOperand();
5517 
5518     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
5519 
5520     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
5521                                    BasePtr, RealMemVT, MMO);
5522 
5523     SDValue Ops[] = {
5524       DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
5525       NewLD.getValue(1)
5526     };
5527 
5528     return DAG.getMergeValues(Ops, DL);
5529   }
5530 
5531   if (!MemVT.isVector())
5532     return SDValue();
5533 
5534   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
5535          "Custom lowering for non-i32 vectors hasn't been implemented.");
5536 
5537   unsigned Alignment = Load->getAlignment();
5538   unsigned AS = Load->getAddressSpace();
5539   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
5540                           AS, Alignment)) {
5541     SDValue Ops[2];
5542     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
5543     return DAG.getMergeValues(Ops, DL);
5544   }
5545 
5546   MachineFunction &MF = DAG.getMachineFunction();
5547   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5548   // If there is a possibilty that flat instruction access scratch memory
5549   // then we need to use the same legalization rules we use for private.
5550   if (AS == AMDGPUASI.FLAT_ADDRESS)
5551     AS = MFI->hasFlatScratchInit() ?
5552          AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5553 
5554   unsigned NumElements = MemVT.getVectorNumElements();
5555 
5556   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5557       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
5558     if (!Op->isDivergent() && Alignment >= 4)
5559       return SDValue();
5560     // Non-uniform loads will be selected to MUBUF instructions, so they
5561     // have the same legalization requirements as global and private
5562     // loads.
5563     //
5564   }
5565 
5566   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5567       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5568       AS == AMDGPUASI.GLOBAL_ADDRESS) {
5569     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
5570         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
5571         Alignment >= 4)
5572       return SDValue();
5573     // Non-uniform loads will be selected to MUBUF instructions, so they
5574     // have the same legalization requirements as global and private
5575     // loads.
5576     //
5577   }
5578   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5579       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5580       AS == AMDGPUASI.GLOBAL_ADDRESS ||
5581       AS == AMDGPUASI.FLAT_ADDRESS) {
5582     if (NumElements > 4)
5583       return SplitVectorLoad(Op, DAG);
5584     // v4 loads are supported for private and global memory.
5585     return SDValue();
5586   }
5587   if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5588     // Depending on the setting of the private_element_size field in the
5589     // resource descriptor, we can only make private accesses up to a certain
5590     // size.
5591     switch (Subtarget->getMaxPrivateElementSize()) {
5592     case 4:
5593       return scalarizeVectorLoad(Load, DAG);
5594     case 8:
5595       if (NumElements > 2)
5596         return SplitVectorLoad(Op, DAG);
5597       return SDValue();
5598     case 16:
5599       // Same as global/flat
5600       if (NumElements > 4)
5601         return SplitVectorLoad(Op, DAG);
5602       return SDValue();
5603     default:
5604       llvm_unreachable("unsupported private_element_size");
5605     }
5606   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5607     // Use ds_read_b128 if possible.
5608     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
5609         MemVT.getStoreSize() == 16)
5610       return SDValue();
5611 
5612     if (NumElements > 2)
5613       return SplitVectorLoad(Op, DAG);
5614   }
5615   return SDValue();
5616 }
5617 
5618 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5619   EVT VT = Op.getValueType();
5620   assert(VT.getSizeInBits() == 64);
5621 
5622   SDLoc DL(Op);
5623   SDValue Cond = Op.getOperand(0);
5624 
5625   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
5626   SDValue One = DAG.getConstant(1, DL, MVT::i32);
5627 
5628   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
5629   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
5630 
5631   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
5632   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
5633 
5634   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
5635 
5636   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
5637   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
5638 
5639   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
5640 
5641   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
5642   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
5643 }
5644 
5645 // Catch division cases where we can use shortcuts with rcp and rsq
5646 // instructions.
5647 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
5648                                               SelectionDAG &DAG) const {
5649   SDLoc SL(Op);
5650   SDValue LHS = Op.getOperand(0);
5651   SDValue RHS = Op.getOperand(1);
5652   EVT VT = Op.getValueType();
5653   const SDNodeFlags Flags = Op->getFlags();
5654   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
5655 
5656   if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
5657     return SDValue();
5658 
5659   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
5660     if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
5661       if (CLHS->isExactlyValue(1.0)) {
5662         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
5663         // the CI documentation has a worst case error of 1 ulp.
5664         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
5665         // use it as long as we aren't trying to use denormals.
5666         //
5667         // v_rcp_f16 and v_rsq_f16 DO support denormals.
5668 
5669         // 1.0 / sqrt(x) -> rsq(x)
5670 
5671         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
5672         // error seems really high at 2^29 ULP.
5673         if (RHS.getOpcode() == ISD::FSQRT)
5674           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
5675 
5676         // 1.0 / x -> rcp(x)
5677         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5678       }
5679 
5680       // Same as for 1.0, but expand the sign out of the constant.
5681       if (CLHS->isExactlyValue(-1.0)) {
5682         // -1.0 / x -> rcp (fneg x)
5683         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
5684         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
5685       }
5686     }
5687   }
5688 
5689   if (Unsafe) {
5690     // Turn into multiply by the reciprocal.
5691     // x / y -> x * (1.0 / y)
5692     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5693     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
5694   }
5695 
5696   return SDValue();
5697 }
5698 
5699 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5700                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
5701   if (GlueChain->getNumValues() <= 1) {
5702     return DAG.getNode(Opcode, SL, VT, A, B);
5703   }
5704 
5705   assert(GlueChain->getNumValues() == 3);
5706 
5707   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5708   switch (Opcode) {
5709   default: llvm_unreachable("no chain equivalent for opcode");
5710   case ISD::FMUL:
5711     Opcode = AMDGPUISD::FMUL_W_CHAIN;
5712     break;
5713   }
5714 
5715   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
5716                      GlueChain.getValue(2));
5717 }
5718 
5719 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5720                            EVT VT, SDValue A, SDValue B, SDValue C,
5721                            SDValue GlueChain) {
5722   if (GlueChain->getNumValues() <= 1) {
5723     return DAG.getNode(Opcode, SL, VT, A, B, C);
5724   }
5725 
5726   assert(GlueChain->getNumValues() == 3);
5727 
5728   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5729   switch (Opcode) {
5730   default: llvm_unreachable("no chain equivalent for opcode");
5731   case ISD::FMA:
5732     Opcode = AMDGPUISD::FMA_W_CHAIN;
5733     break;
5734   }
5735 
5736   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
5737                      GlueChain.getValue(2));
5738 }
5739 
5740 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
5741   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5742     return FastLowered;
5743 
5744   SDLoc SL(Op);
5745   SDValue Src0 = Op.getOperand(0);
5746   SDValue Src1 = Op.getOperand(1);
5747 
5748   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5749   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5750 
5751   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
5752   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
5753 
5754   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
5755   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
5756 
5757   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
5758 }
5759 
5760 // Faster 2.5 ULP division that does not support denormals.
5761 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
5762   SDLoc SL(Op);
5763   SDValue LHS = Op.getOperand(1);
5764   SDValue RHS = Op.getOperand(2);
5765 
5766   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
5767 
5768   const APFloat K0Val(BitsToFloat(0x6f800000));
5769   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
5770 
5771   const APFloat K1Val(BitsToFloat(0x2f800000));
5772   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
5773 
5774   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5775 
5776   EVT SetCCVT =
5777     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
5778 
5779   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
5780 
5781   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
5782 
5783   // TODO: Should this propagate fast-math-flags?
5784   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
5785 
5786   // rcp does not support denormals.
5787   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
5788 
5789   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
5790 
5791   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
5792 }
5793 
5794 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
5795   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5796     return FastLowered;
5797 
5798   SDLoc SL(Op);
5799   SDValue LHS = Op.getOperand(0);
5800   SDValue RHS = Op.getOperand(1);
5801 
5802   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5803 
5804   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
5805 
5806   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5807                                           RHS, RHS, LHS);
5808   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5809                                         LHS, RHS, LHS);
5810 
5811   // Denominator is scaled to not be denormal, so using rcp is ok.
5812   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
5813                                   DenominatorScaled);
5814   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
5815                                      DenominatorScaled);
5816 
5817   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
5818                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
5819                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
5820 
5821   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
5822 
5823   if (!Subtarget->hasFP32Denormals()) {
5824     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
5825     const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
5826                                                       SL, MVT::i32);
5827     SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
5828                                        DAG.getEntryNode(),
5829                                        EnableDenormValue, BitField);
5830     SDValue Ops[3] = {
5831       NegDivScale0,
5832       EnableDenorm.getValue(0),
5833       EnableDenorm.getValue(1)
5834     };
5835 
5836     NegDivScale0 = DAG.getMergeValues(Ops, SL);
5837   }
5838 
5839   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
5840                              ApproxRcp, One, NegDivScale0);
5841 
5842   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
5843                              ApproxRcp, Fma0);
5844 
5845   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
5846                            Fma1, Fma1);
5847 
5848   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
5849                              NumeratorScaled, Mul);
5850 
5851   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
5852 
5853   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
5854                              NumeratorScaled, Fma3);
5855 
5856   if (!Subtarget->hasFP32Denormals()) {
5857     const SDValue DisableDenormValue =
5858         DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
5859     SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
5860                                         Fma4.getValue(1),
5861                                         DisableDenormValue,
5862                                         BitField,
5863                                         Fma4.getValue(2));
5864 
5865     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
5866                                       DisableDenorm, DAG.getRoot());
5867     DAG.setRoot(OutputChain);
5868   }
5869 
5870   SDValue Scale = NumeratorScaled.getValue(1);
5871   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
5872                              Fma4, Fma1, Fma3, Scale);
5873 
5874   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
5875 }
5876 
5877 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
5878   if (DAG.getTarget().Options.UnsafeFPMath)
5879     return lowerFastUnsafeFDIV(Op, DAG);
5880 
5881   SDLoc SL(Op);
5882   SDValue X = Op.getOperand(0);
5883   SDValue Y = Op.getOperand(1);
5884 
5885   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
5886 
5887   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
5888 
5889   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
5890 
5891   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
5892 
5893   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
5894 
5895   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
5896 
5897   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
5898 
5899   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
5900 
5901   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
5902 
5903   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
5904   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
5905 
5906   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
5907                              NegDivScale0, Mul, DivScale1);
5908 
5909   SDValue Scale;
5910 
5911   if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
5912     // Workaround a hardware bug on SI where the condition output from div_scale
5913     // is not usable.
5914 
5915     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
5916 
5917     // Figure out if the scale to use for div_fmas.
5918     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
5919     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
5920     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
5921     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
5922 
5923     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
5924     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
5925 
5926     SDValue Scale0Hi
5927       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
5928     SDValue Scale1Hi
5929       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
5930 
5931     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
5932     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
5933     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
5934   } else {
5935     Scale = DivScale1.getValue(1);
5936   }
5937 
5938   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
5939                              Fma4, Fma3, Mul, Scale);
5940 
5941   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
5942 }
5943 
5944 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
5945   EVT VT = Op.getValueType();
5946 
5947   if (VT == MVT::f32)
5948     return LowerFDIV32(Op, DAG);
5949 
5950   if (VT == MVT::f64)
5951     return LowerFDIV64(Op, DAG);
5952 
5953   if (VT == MVT::f16)
5954     return LowerFDIV16(Op, DAG);
5955 
5956   llvm_unreachable("Unexpected type for fdiv");
5957 }
5958 
5959 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5960   SDLoc DL(Op);
5961   StoreSDNode *Store = cast<StoreSDNode>(Op);
5962   EVT VT = Store->getMemoryVT();
5963 
5964   if (VT == MVT::i1) {
5965     return DAG.getTruncStore(Store->getChain(), DL,
5966        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
5967        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
5968   }
5969 
5970   assert(VT.isVector() &&
5971          Store->getValue().getValueType().getScalarType() == MVT::i32);
5972 
5973   unsigned AS = Store->getAddressSpace();
5974   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
5975                           AS, Store->getAlignment())) {
5976     return expandUnalignedStore(Store, DAG);
5977   }
5978 
5979   MachineFunction &MF = DAG.getMachineFunction();
5980   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5981   // If there is a possibilty that flat instruction access scratch memory
5982   // then we need to use the same legalization rules we use for private.
5983   if (AS == AMDGPUASI.FLAT_ADDRESS)
5984     AS = MFI->hasFlatScratchInit() ?
5985          AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5986 
5987   unsigned NumElements = VT.getVectorNumElements();
5988   if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
5989       AS == AMDGPUASI.FLAT_ADDRESS) {
5990     if (NumElements > 4)
5991       return SplitVectorStore(Op, DAG);
5992     return SDValue();
5993   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5994     switch (Subtarget->getMaxPrivateElementSize()) {
5995     case 4:
5996       return scalarizeVectorStore(Store, DAG);
5997     case 8:
5998       if (NumElements > 2)
5999         return SplitVectorStore(Op, DAG);
6000       return SDValue();
6001     case 16:
6002       if (NumElements > 4)
6003         return SplitVectorStore(Op, DAG);
6004       return SDValue();
6005     default:
6006       llvm_unreachable("unsupported private_element_size");
6007     }
6008   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
6009     // Use ds_write_b128 if possible.
6010     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
6011         VT.getStoreSize() == 16)
6012       return SDValue();
6013 
6014     if (NumElements > 2)
6015       return SplitVectorStore(Op, DAG);
6016     return SDValue();
6017   } else {
6018     llvm_unreachable("unhandled address space");
6019   }
6020 }
6021 
6022 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
6023   SDLoc DL(Op);
6024   EVT VT = Op.getValueType();
6025   SDValue Arg = Op.getOperand(0);
6026   // TODO: Should this propagate fast-math-flags?
6027   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
6028                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
6029                                               DAG.getConstantFP(0.5/M_PI, DL,
6030                                                                 VT)));
6031 
6032   switch (Op.getOpcode()) {
6033   case ISD::FCOS:
6034     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
6035   case ISD::FSIN:
6036     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
6037   default:
6038     llvm_unreachable("Wrong trig opcode");
6039   }
6040 }
6041 
6042 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
6043   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
6044   assert(AtomicNode->isCompareAndSwap());
6045   unsigned AS = AtomicNode->getAddressSpace();
6046 
6047   // No custom lowering required for local address space
6048   if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
6049     return Op;
6050 
6051   // Non-local address space requires custom lowering for atomic compare
6052   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
6053   SDLoc DL(Op);
6054   SDValue ChainIn = Op.getOperand(0);
6055   SDValue Addr = Op.getOperand(1);
6056   SDValue Old = Op.getOperand(2);
6057   SDValue New = Op.getOperand(3);
6058   EVT VT = Op.getValueType();
6059   MVT SimpleVT = VT.getSimpleVT();
6060   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
6061 
6062   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
6063   SDValue Ops[] = { ChainIn, Addr, NewOld };
6064 
6065   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
6066                                  Ops, VT, AtomicNode->getMemOperand());
6067 }
6068 
6069 //===----------------------------------------------------------------------===//
6070 // Custom DAG optimizations
6071 //===----------------------------------------------------------------------===//
6072 
6073 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
6074                                                      DAGCombinerInfo &DCI) const {
6075   EVT VT = N->getValueType(0);
6076   EVT ScalarVT = VT.getScalarType();
6077   if (ScalarVT != MVT::f32)
6078     return SDValue();
6079 
6080   SelectionDAG &DAG = DCI.DAG;
6081   SDLoc DL(N);
6082 
6083   SDValue Src = N->getOperand(0);
6084   EVT SrcVT = Src.getValueType();
6085 
6086   // TODO: We could try to match extracting the higher bytes, which would be
6087   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
6088   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
6089   // about in practice.
6090   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
6091     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
6092       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
6093       DCI.AddToWorklist(Cvt.getNode());
6094       return Cvt;
6095     }
6096   }
6097 
6098   return SDValue();
6099 }
6100 
6101 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
6102 
6103 // This is a variant of
6104 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
6105 //
6106 // The normal DAG combiner will do this, but only if the add has one use since
6107 // that would increase the number of instructions.
6108 //
6109 // This prevents us from seeing a constant offset that can be folded into a
6110 // memory instruction's addressing mode. If we know the resulting add offset of
6111 // a pointer can be folded into an addressing offset, we can replace the pointer
6112 // operand with the add of new constant offset. This eliminates one of the uses,
6113 // and may allow the remaining use to also be simplified.
6114 //
6115 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
6116                                                unsigned AddrSpace,
6117                                                EVT MemVT,
6118                                                DAGCombinerInfo &DCI) const {
6119   SDValue N0 = N->getOperand(0);
6120   SDValue N1 = N->getOperand(1);
6121 
6122   // We only do this to handle cases where it's profitable when there are
6123   // multiple uses of the add, so defer to the standard combine.
6124   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
6125       N0->hasOneUse())
6126     return SDValue();
6127 
6128   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
6129   if (!CN1)
6130     return SDValue();
6131 
6132   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6133   if (!CAdd)
6134     return SDValue();
6135 
6136   // If the resulting offset is too large, we can't fold it into the addressing
6137   // mode offset.
6138   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
6139   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
6140 
6141   AddrMode AM;
6142   AM.HasBaseReg = true;
6143   AM.BaseOffs = Offset.getSExtValue();
6144   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
6145     return SDValue();
6146 
6147   SelectionDAG &DAG = DCI.DAG;
6148   SDLoc SL(N);
6149   EVT VT = N->getValueType(0);
6150 
6151   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
6152   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
6153 
6154   SDNodeFlags Flags;
6155   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
6156                           (N0.getOpcode() == ISD::OR ||
6157                            N0->getFlags().hasNoUnsignedWrap()));
6158 
6159   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
6160 }
6161 
6162 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
6163                                                   DAGCombinerInfo &DCI) const {
6164   SDValue Ptr = N->getBasePtr();
6165   SelectionDAG &DAG = DCI.DAG;
6166   SDLoc SL(N);
6167 
6168   // TODO: We could also do this for multiplies.
6169   if (Ptr.getOpcode() == ISD::SHL) {
6170     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
6171                                           N->getMemoryVT(), DCI);
6172     if (NewPtr) {
6173       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
6174 
6175       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
6176       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
6177     }
6178   }
6179 
6180   return SDValue();
6181 }
6182 
6183 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
6184   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
6185          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
6186          (Opc == ISD::XOR && Val == 0);
6187 }
6188 
6189 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
6190 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
6191 // integer combine opportunities since most 64-bit operations are decomposed
6192 // this way.  TODO: We won't want this for SALU especially if it is an inline
6193 // immediate.
6194 SDValue SITargetLowering::splitBinaryBitConstantOp(
6195   DAGCombinerInfo &DCI,
6196   const SDLoc &SL,
6197   unsigned Opc, SDValue LHS,
6198   const ConstantSDNode *CRHS) const {
6199   uint64_t Val = CRHS->getZExtValue();
6200   uint32_t ValLo = Lo_32(Val);
6201   uint32_t ValHi = Hi_32(Val);
6202   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6203 
6204     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
6205          bitOpWithConstantIsReducible(Opc, ValHi)) ||
6206         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
6207     // If we need to materialize a 64-bit immediate, it will be split up later
6208     // anyway. Avoid creating the harder to understand 64-bit immediate
6209     // materialization.
6210     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
6211   }
6212 
6213   return SDValue();
6214 }
6215 
6216 // Returns true if argument is a boolean value which is not serialized into
6217 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
6218 static bool isBoolSGPR(SDValue V) {
6219   if (V.getValueType() != MVT::i1)
6220     return false;
6221   switch (V.getOpcode()) {
6222   default: break;
6223   case ISD::SETCC:
6224   case ISD::AND:
6225   case ISD::OR:
6226   case ISD::XOR:
6227   case AMDGPUISD::FP_CLASS:
6228     return true;
6229   }
6230   return false;
6231 }
6232 
6233 // If a constant has all zeroes or all ones within each byte return it.
6234 // Otherwise return 0.
6235 static uint32_t getConstantPermuteMask(uint32_t C) {
6236   // 0xff for any zero byte in the mask
6237   uint32_t ZeroByteMask = 0;
6238   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
6239   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
6240   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
6241   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
6242   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
6243   if ((NonZeroByteMask & C) != NonZeroByteMask)
6244     return 0; // Partial bytes selected.
6245   return C;
6246 }
6247 
6248 // Check if a node selects whole bytes from its operand 0 starting at a byte
6249 // boundary while masking the rest. Returns select mask as in the v_perm_b32
6250 // or -1 if not succeeded.
6251 // Note byte select encoding:
6252 // value 0-3 selects corresponding source byte;
6253 // value 0xc selects zero;
6254 // value 0xff selects 0xff.
6255 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
6256   assert(V.getValueSizeInBits() == 32);
6257 
6258   if (V.getNumOperands() != 2)
6259     return ~0;
6260 
6261   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
6262   if (!N1)
6263     return ~0;
6264 
6265   uint32_t C = N1->getZExtValue();
6266 
6267   switch (V.getOpcode()) {
6268   default:
6269     break;
6270   case ISD::AND:
6271     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
6272       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
6273     }
6274     break;
6275 
6276   case ISD::OR:
6277     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
6278       return (0x03020100 & ~ConstMask) | ConstMask;
6279     }
6280     break;
6281 
6282   case ISD::SHL:
6283     if (C % 8)
6284       return ~0;
6285 
6286     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
6287 
6288   case ISD::SRL:
6289     if (C % 8)
6290       return ~0;
6291 
6292     return uint32_t(0x0c0c0c0c03020100ull >> C);
6293   }
6294 
6295   return ~0;
6296 }
6297 
6298 SDValue SITargetLowering::performAndCombine(SDNode *N,
6299                                             DAGCombinerInfo &DCI) const {
6300   if (DCI.isBeforeLegalize())
6301     return SDValue();
6302 
6303   SelectionDAG &DAG = DCI.DAG;
6304   EVT VT = N->getValueType(0);
6305   SDValue LHS = N->getOperand(0);
6306   SDValue RHS = N->getOperand(1);
6307 
6308 
6309   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6310   if (VT == MVT::i64 && CRHS) {
6311     if (SDValue Split
6312         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
6313       return Split;
6314   }
6315 
6316   if (CRHS && VT == MVT::i32) {
6317     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
6318     // nb = number of trailing zeroes in mask
6319     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
6320     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
6321     uint64_t Mask = CRHS->getZExtValue();
6322     unsigned Bits = countPopulation(Mask);
6323     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
6324         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
6325       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
6326         unsigned Shift = CShift->getZExtValue();
6327         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
6328         unsigned Offset = NB + Shift;
6329         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
6330           SDLoc SL(N);
6331           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
6332                                     LHS->getOperand(0),
6333                                     DAG.getConstant(Offset, SL, MVT::i32),
6334                                     DAG.getConstant(Bits, SL, MVT::i32));
6335           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6336           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
6337                                     DAG.getValueType(NarrowVT));
6338           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
6339                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
6340           return Shl;
6341         }
6342       }
6343     }
6344 
6345     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
6346     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
6347         isa<ConstantSDNode>(LHS.getOperand(2))) {
6348       uint32_t Sel = getConstantPermuteMask(Mask);
6349       if (!Sel)
6350         return SDValue();
6351 
6352       // Select 0xc for all zero bytes
6353       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
6354       SDLoc DL(N);
6355       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
6356                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
6357     }
6358   }
6359 
6360   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
6361   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
6362   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
6363     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6364     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
6365 
6366     SDValue X = LHS.getOperand(0);
6367     SDValue Y = RHS.getOperand(0);
6368     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
6369       return SDValue();
6370 
6371     if (LCC == ISD::SETO) {
6372       if (X != LHS.getOperand(1))
6373         return SDValue();
6374 
6375       if (RCC == ISD::SETUNE) {
6376         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
6377         if (!C1 || !C1->isInfinity() || C1->isNegative())
6378           return SDValue();
6379 
6380         const uint32_t Mask = SIInstrFlags::N_NORMAL |
6381                               SIInstrFlags::N_SUBNORMAL |
6382                               SIInstrFlags::N_ZERO |
6383                               SIInstrFlags::P_ZERO |
6384                               SIInstrFlags::P_SUBNORMAL |
6385                               SIInstrFlags::P_NORMAL;
6386 
6387         static_assert(((~(SIInstrFlags::S_NAN |
6388                           SIInstrFlags::Q_NAN |
6389                           SIInstrFlags::N_INFINITY |
6390                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
6391                       "mask not equal");
6392 
6393         SDLoc DL(N);
6394         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6395                            X, DAG.getConstant(Mask, DL, MVT::i32));
6396       }
6397     }
6398   }
6399 
6400   if (VT == MVT::i32 &&
6401       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
6402     // and x, (sext cc from i1) => select cc, x, 0
6403     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
6404       std::swap(LHS, RHS);
6405     if (isBoolSGPR(RHS.getOperand(0)))
6406       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
6407                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
6408   }
6409 
6410   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
6411   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6412   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
6413       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
6414     uint32_t LHSMask = getPermuteMask(DAG, LHS);
6415     uint32_t RHSMask = getPermuteMask(DAG, RHS);
6416     if (LHSMask != ~0u && RHSMask != ~0u) {
6417       // Canonicalize the expression in an attempt to have fewer unique masks
6418       // and therefore fewer registers used to hold the masks.
6419       if (LHSMask > RHSMask) {
6420         std::swap(LHSMask, RHSMask);
6421         std::swap(LHS, RHS);
6422       }
6423 
6424       // Select 0xc for each lane used from source operand. Zero has 0xc mask
6425       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
6426       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6427       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6428 
6429       // Check of we need to combine values from two sources within a byte.
6430       if (!(LHSUsedLanes & RHSUsedLanes) &&
6431           // If we select high and lower word keep it for SDWA.
6432           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
6433           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
6434         // Each byte in each mask is either selector mask 0-3, or has higher
6435         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
6436         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
6437         // mask which is not 0xff wins. By anding both masks we have a correct
6438         // result except that 0x0c shall be corrected to give 0x0c only.
6439         uint32_t Mask = LHSMask & RHSMask;
6440         for (unsigned I = 0; I < 32; I += 8) {
6441           uint32_t ByteSel = 0xff << I;
6442           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
6443             Mask &= (0x0c << I) & 0xffffffff;
6444         }
6445 
6446         // Add 4 to each active LHS lane. It will not affect any existing 0xff
6447         // or 0x0c.
6448         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
6449         SDLoc DL(N);
6450 
6451         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
6452                            LHS.getOperand(0), RHS.getOperand(0),
6453                            DAG.getConstant(Sel, DL, MVT::i32));
6454       }
6455     }
6456   }
6457 
6458   return SDValue();
6459 }
6460 
6461 SDValue SITargetLowering::performOrCombine(SDNode *N,
6462                                            DAGCombinerInfo &DCI) const {
6463   SelectionDAG &DAG = DCI.DAG;
6464   SDValue LHS = N->getOperand(0);
6465   SDValue RHS = N->getOperand(1);
6466 
6467   EVT VT = N->getValueType(0);
6468   if (VT == MVT::i1) {
6469     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
6470     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
6471         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
6472       SDValue Src = LHS.getOperand(0);
6473       if (Src != RHS.getOperand(0))
6474         return SDValue();
6475 
6476       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6477       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6478       if (!CLHS || !CRHS)
6479         return SDValue();
6480 
6481       // Only 10 bits are used.
6482       static const uint32_t MaxMask = 0x3ff;
6483 
6484       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
6485       SDLoc DL(N);
6486       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6487                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
6488     }
6489 
6490     return SDValue();
6491   }
6492 
6493   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
6494   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
6495       LHS.getOpcode() == AMDGPUISD::PERM &&
6496       isa<ConstantSDNode>(LHS.getOperand(2))) {
6497     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
6498     if (!Sel)
6499       return SDValue();
6500 
6501     Sel |= LHS.getConstantOperandVal(2);
6502     SDLoc DL(N);
6503     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
6504                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
6505   }
6506 
6507   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
6508   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6509   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
6510       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
6511     uint32_t LHSMask = getPermuteMask(DAG, LHS);
6512     uint32_t RHSMask = getPermuteMask(DAG, RHS);
6513     if (LHSMask != ~0u && RHSMask != ~0u) {
6514       // Canonicalize the expression in an attempt to have fewer unique masks
6515       // and therefore fewer registers used to hold the masks.
6516       if (LHSMask > RHSMask) {
6517         std::swap(LHSMask, RHSMask);
6518         std::swap(LHS, RHS);
6519       }
6520 
6521       // Select 0xc for each lane used from source operand. Zero has 0xc mask
6522       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
6523       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6524       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6525 
6526       // Check of we need to combine values from two sources within a byte.
6527       if (!(LHSUsedLanes & RHSUsedLanes) &&
6528           // If we select high and lower word keep it for SDWA.
6529           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
6530           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
6531         // Kill zero bytes selected by other mask. Zero value is 0xc.
6532         LHSMask &= ~RHSUsedLanes;
6533         RHSMask &= ~LHSUsedLanes;
6534         // Add 4 to each active LHS lane
6535         LHSMask |= LHSUsedLanes & 0x04040404;
6536         // Combine masks
6537         uint32_t Sel = LHSMask | RHSMask;
6538         SDLoc DL(N);
6539 
6540         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
6541                            LHS.getOperand(0), RHS.getOperand(0),
6542                            DAG.getConstant(Sel, DL, MVT::i32));
6543       }
6544     }
6545   }
6546 
6547   if (VT != MVT::i64)
6548     return SDValue();
6549 
6550   // TODO: This could be a generic combine with a predicate for extracting the
6551   // high half of an integer being free.
6552 
6553   // (or i64:x, (zero_extend i32:y)) ->
6554   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
6555   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
6556       RHS.getOpcode() != ISD::ZERO_EXTEND)
6557     std::swap(LHS, RHS);
6558 
6559   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
6560     SDValue ExtSrc = RHS.getOperand(0);
6561     EVT SrcVT = ExtSrc.getValueType();
6562     if (SrcVT == MVT::i32) {
6563       SDLoc SL(N);
6564       SDValue LowLHS, HiBits;
6565       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
6566       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
6567 
6568       DCI.AddToWorklist(LowOr.getNode());
6569       DCI.AddToWorklist(HiBits.getNode());
6570 
6571       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
6572                                 LowOr, HiBits);
6573       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
6574     }
6575   }
6576 
6577   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
6578   if (CRHS) {
6579     if (SDValue Split
6580           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
6581       return Split;
6582   }
6583 
6584   return SDValue();
6585 }
6586 
6587 SDValue SITargetLowering::performXorCombine(SDNode *N,
6588                                             DAGCombinerInfo &DCI) const {
6589   EVT VT = N->getValueType(0);
6590   if (VT != MVT::i64)
6591     return SDValue();
6592 
6593   SDValue LHS = N->getOperand(0);
6594   SDValue RHS = N->getOperand(1);
6595 
6596   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6597   if (CRHS) {
6598     if (SDValue Split
6599           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
6600       return Split;
6601   }
6602 
6603   return SDValue();
6604 }
6605 
6606 // Instructions that will be lowered with a final instruction that zeros the
6607 // high result bits.
6608 // XXX - probably only need to list legal operations.
6609 static bool fp16SrcZerosHighBits(unsigned Opc) {
6610   switch (Opc) {
6611   case ISD::FADD:
6612   case ISD::FSUB:
6613   case ISD::FMUL:
6614   case ISD::FDIV:
6615   case ISD::FREM:
6616   case ISD::FMA:
6617   case ISD::FMAD:
6618   case ISD::FCANONICALIZE:
6619   case ISD::FP_ROUND:
6620   case ISD::UINT_TO_FP:
6621   case ISD::SINT_TO_FP:
6622   case ISD::FABS:
6623     // Fabs is lowered to a bit operation, but it's an and which will clear the
6624     // high bits anyway.
6625   case ISD::FSQRT:
6626   case ISD::FSIN:
6627   case ISD::FCOS:
6628   case ISD::FPOWI:
6629   case ISD::FPOW:
6630   case ISD::FLOG:
6631   case ISD::FLOG2:
6632   case ISD::FLOG10:
6633   case ISD::FEXP:
6634   case ISD::FEXP2:
6635   case ISD::FCEIL:
6636   case ISD::FTRUNC:
6637   case ISD::FRINT:
6638   case ISD::FNEARBYINT:
6639   case ISD::FROUND:
6640   case ISD::FFLOOR:
6641   case ISD::FMINNUM:
6642   case ISD::FMAXNUM:
6643   case AMDGPUISD::FRACT:
6644   case AMDGPUISD::CLAMP:
6645   case AMDGPUISD::COS_HW:
6646   case AMDGPUISD::SIN_HW:
6647   case AMDGPUISD::FMIN3:
6648   case AMDGPUISD::FMAX3:
6649   case AMDGPUISD::FMED3:
6650   case AMDGPUISD::FMAD_FTZ:
6651   case AMDGPUISD::RCP:
6652   case AMDGPUISD::RSQ:
6653   case AMDGPUISD::RCP_IFLAG:
6654   case AMDGPUISD::LDEXP:
6655     return true;
6656   default:
6657     // fcopysign, select and others may be lowered to 32-bit bit operations
6658     // which don't zero the high bits.
6659     return false;
6660   }
6661 }
6662 
6663 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
6664                                                    DAGCombinerInfo &DCI) const {
6665   if (!Subtarget->has16BitInsts() ||
6666       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6667     return SDValue();
6668 
6669   EVT VT = N->getValueType(0);
6670   if (VT != MVT::i32)
6671     return SDValue();
6672 
6673   SDValue Src = N->getOperand(0);
6674   if (Src.getValueType() != MVT::i16)
6675     return SDValue();
6676 
6677   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
6678   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
6679   if (Src.getOpcode() == ISD::BITCAST) {
6680     SDValue BCSrc = Src.getOperand(0);
6681     if (BCSrc.getValueType() == MVT::f16 &&
6682         fp16SrcZerosHighBits(BCSrc.getOpcode()))
6683       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
6684   }
6685 
6686   return SDValue();
6687 }
6688 
6689 SDValue SITargetLowering::performClassCombine(SDNode *N,
6690                                               DAGCombinerInfo &DCI) const {
6691   SelectionDAG &DAG = DCI.DAG;
6692   SDValue Mask = N->getOperand(1);
6693 
6694   // fp_class x, 0 -> false
6695   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
6696     if (CMask->isNullValue())
6697       return DAG.getConstant(0, SDLoc(N), MVT::i1);
6698   }
6699 
6700   if (N->getOperand(0).isUndef())
6701     return DAG.getUNDEF(MVT::i1);
6702 
6703   return SDValue();
6704 }
6705 
6706 SDValue SITargetLowering::performRcpCombine(SDNode *N,
6707                                             DAGCombinerInfo &DCI) const {
6708   EVT VT = N->getValueType(0);
6709   SDValue N0 = N->getOperand(0);
6710 
6711   if (N0.isUndef())
6712     return N0;
6713 
6714   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
6715                          N0.getOpcode() == ISD::SINT_TO_FP)) {
6716     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
6717                            N->getFlags());
6718   }
6719 
6720   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
6721 }
6722 
6723 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
6724   if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
6725     return true;
6726 
6727   return DAG.isKnownNeverNaN(Op);
6728 }
6729 
6730 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op,
6731                             const GCNSubtarget *ST, unsigned MaxDepth=5) {
6732   // If source is a result of another standard FP operation it is already in
6733   // canonical form.
6734 
6735   switch (Op.getOpcode()) {
6736   default:
6737     break;
6738 
6739   // These will flush denorms if required.
6740   case ISD::FADD:
6741   case ISD::FSUB:
6742   case ISD::FMUL:
6743   case ISD::FSQRT:
6744   case ISD::FCEIL:
6745   case ISD::FFLOOR:
6746   case ISD::FMA:
6747   case ISD::FMAD:
6748 
6749   case ISD::FCANONICALIZE:
6750     return true;
6751 
6752   case ISD::FP_ROUND:
6753     return Op.getValueType().getScalarType() != MVT::f16 ||
6754            ST->hasFP16Denormals();
6755 
6756   case ISD::FP_EXTEND:
6757     return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 ||
6758            ST->hasFP16Denormals();
6759 
6760   case ISD::FP16_TO_FP:
6761   case ISD::FP_TO_FP16:
6762     return ST->hasFP16Denormals();
6763 
6764   // It can/will be lowered or combined as a bit operation.
6765   // Need to check their input recursively to handle.
6766   case ISD::FNEG:
6767   case ISD::FABS:
6768     return (MaxDepth > 0) &&
6769            isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1);
6770 
6771   case ISD::FSIN:
6772   case ISD::FCOS:
6773   case ISD::FSINCOS:
6774     return Op.getValueType().getScalarType() != MVT::f16;
6775 
6776   // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms.
6777   // For such targets need to check their input recursively.
6778   case ISD::FMINNUM:
6779   case ISD::FMAXNUM:
6780   case ISD::FMINNAN:
6781   case ISD::FMAXNAN:
6782 
6783     if (ST->supportsMinMaxDenormModes() &&
6784         DAG.isKnownNeverNaN(Op.getOperand(0)) &&
6785         DAG.isKnownNeverNaN(Op.getOperand(1)))
6786       return true;
6787 
6788     return (MaxDepth > 0) &&
6789            isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) &&
6790            isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1);
6791 
6792   case ISD::ConstantFP: {
6793     auto F = cast<ConstantFPSDNode>(Op)->getValueAPF();
6794     return !F.isDenormal() && !(F.isNaN() && F.isSignaling());
6795   }
6796   }
6797   return false;
6798 }
6799 
6800 // Constant fold canonicalize.
6801 SDValue SITargetLowering::performFCanonicalizeCombine(
6802   SDNode *N,
6803   DAGCombinerInfo &DCI) const {
6804   SelectionDAG &DAG = DCI.DAG;
6805   ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
6806 
6807   if (!CFP) {
6808     SDValue N0 = N->getOperand(0);
6809     EVT VT = N0.getValueType().getScalarType();
6810     auto ST = getSubtarget();
6811 
6812     if (((VT == MVT::f32 && ST->hasFP32Denormals()) ||
6813          (VT == MVT::f64 && ST->hasFP64Denormals()) ||
6814          (VT == MVT::f16 && ST->hasFP16Denormals())) &&
6815         DAG.isKnownNeverNaN(N0))
6816       return N0;
6817 
6818     bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
6819 
6820     if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) &&
6821         isCanonicalized(DAG, N0, ST))
6822       return N0;
6823 
6824     return SDValue();
6825   }
6826 
6827   const APFloat &C = CFP->getValueAPF();
6828 
6829   // Flush denormals to 0 if not enabled.
6830   if (C.isDenormal()) {
6831     EVT VT = N->getValueType(0);
6832     EVT SVT = VT.getScalarType();
6833     if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
6834       return DAG.getConstantFP(0.0, SDLoc(N), VT);
6835 
6836     if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
6837       return DAG.getConstantFP(0.0, SDLoc(N), VT);
6838 
6839     if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
6840       return DAG.getConstantFP(0.0, SDLoc(N), VT);
6841   }
6842 
6843   if (C.isNaN()) {
6844     EVT VT = N->getValueType(0);
6845     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
6846     if (C.isSignaling()) {
6847       // Quiet a signaling NaN.
6848       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6849     }
6850 
6851     // Make sure it is the canonical NaN bitpattern.
6852     //
6853     // TODO: Can we use -1 as the canonical NaN value since it's an inline
6854     // immediate?
6855     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
6856       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6857   }
6858 
6859   return N->getOperand(0);
6860 }
6861 
6862 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
6863   switch (Opc) {
6864   case ISD::FMAXNUM:
6865     return AMDGPUISD::FMAX3;
6866   case ISD::SMAX:
6867     return AMDGPUISD::SMAX3;
6868   case ISD::UMAX:
6869     return AMDGPUISD::UMAX3;
6870   case ISD::FMINNUM:
6871     return AMDGPUISD::FMIN3;
6872   case ISD::SMIN:
6873     return AMDGPUISD::SMIN3;
6874   case ISD::UMIN:
6875     return AMDGPUISD::UMIN3;
6876   default:
6877     llvm_unreachable("Not a min/max opcode");
6878   }
6879 }
6880 
6881 SDValue SITargetLowering::performIntMed3ImmCombine(
6882   SelectionDAG &DAG, const SDLoc &SL,
6883   SDValue Op0, SDValue Op1, bool Signed) const {
6884   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
6885   if (!K1)
6886     return SDValue();
6887 
6888   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
6889   if (!K0)
6890     return SDValue();
6891 
6892   if (Signed) {
6893     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
6894       return SDValue();
6895   } else {
6896     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
6897       return SDValue();
6898   }
6899 
6900   EVT VT = K0->getValueType(0);
6901   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
6902   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
6903     return DAG.getNode(Med3Opc, SL, VT,
6904                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
6905   }
6906 
6907   // If there isn't a 16-bit med3 operation, convert to 32-bit.
6908   MVT NVT = MVT::i32;
6909   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6910 
6911   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
6912   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
6913   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
6914 
6915   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
6916   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
6917 }
6918 
6919 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
6920   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
6921     return C;
6922 
6923   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
6924     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
6925       return C;
6926   }
6927 
6928   return nullptr;
6929 }
6930 
6931 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
6932                                                   const SDLoc &SL,
6933                                                   SDValue Op0,
6934                                                   SDValue Op1) const {
6935   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
6936   if (!K1)
6937     return SDValue();
6938 
6939   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
6940   if (!K0)
6941     return SDValue();
6942 
6943   // Ordered >= (although NaN inputs should have folded away by now).
6944   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
6945   if (Cmp == APFloat::cmpGreaterThan)
6946     return SDValue();
6947 
6948   // TODO: Check IEEE bit enabled?
6949   EVT VT = Op0.getValueType();
6950   if (Subtarget->enableDX10Clamp()) {
6951     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
6952     // hardware fmed3 behavior converting to a min.
6953     // FIXME: Should this be allowing -0.0?
6954     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
6955       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
6956   }
6957 
6958   // med3 for f16 is only available on gfx9+, and not available for v2f16.
6959   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
6960     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
6961     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
6962     // then give the other result, which is different from med3 with a NaN
6963     // input.
6964     SDValue Var = Op0.getOperand(0);
6965     if (!isKnownNeverSNan(DAG, Var))
6966       return SDValue();
6967 
6968     return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
6969                        Var, SDValue(K0, 0), SDValue(K1, 0));
6970   }
6971 
6972   return SDValue();
6973 }
6974 
6975 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
6976                                                DAGCombinerInfo &DCI) const {
6977   SelectionDAG &DAG = DCI.DAG;
6978 
6979   EVT VT = N->getValueType(0);
6980   unsigned Opc = N->getOpcode();
6981   SDValue Op0 = N->getOperand(0);
6982   SDValue Op1 = N->getOperand(1);
6983 
6984   // Only do this if the inner op has one use since this will just increases
6985   // register pressure for no benefit.
6986 
6987 
6988   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
6989       !VT.isVector() && VT != MVT::f64 &&
6990       ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
6991     // max(max(a, b), c) -> max3(a, b, c)
6992     // min(min(a, b), c) -> min3(a, b, c)
6993     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
6994       SDLoc DL(N);
6995       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
6996                          DL,
6997                          N->getValueType(0),
6998                          Op0.getOperand(0),
6999                          Op0.getOperand(1),
7000                          Op1);
7001     }
7002 
7003     // Try commuted.
7004     // max(a, max(b, c)) -> max3(a, b, c)
7005     // min(a, min(b, c)) -> min3(a, b, c)
7006     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
7007       SDLoc DL(N);
7008       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
7009                          DL,
7010                          N->getValueType(0),
7011                          Op0,
7012                          Op1.getOperand(0),
7013                          Op1.getOperand(1));
7014     }
7015   }
7016 
7017   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
7018   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
7019     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
7020       return Med3;
7021   }
7022 
7023   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
7024     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
7025       return Med3;
7026   }
7027 
7028   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
7029   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
7030        (Opc == AMDGPUISD::FMIN_LEGACY &&
7031         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
7032       (VT == MVT::f32 || VT == MVT::f64 ||
7033        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
7034        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
7035       Op0.hasOneUse()) {
7036     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
7037       return Res;
7038   }
7039 
7040   return SDValue();
7041 }
7042 
7043 static bool isClampZeroToOne(SDValue A, SDValue B) {
7044   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
7045     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
7046       // FIXME: Should this be allowing -0.0?
7047       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
7048              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
7049     }
7050   }
7051 
7052   return false;
7053 }
7054 
7055 // FIXME: Should only worry about snans for version with chain.
7056 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
7057                                               DAGCombinerInfo &DCI) const {
7058   EVT VT = N->getValueType(0);
7059   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
7060   // NaNs. With a NaN input, the order of the operands may change the result.
7061 
7062   SelectionDAG &DAG = DCI.DAG;
7063   SDLoc SL(N);
7064 
7065   SDValue Src0 = N->getOperand(0);
7066   SDValue Src1 = N->getOperand(1);
7067   SDValue Src2 = N->getOperand(2);
7068 
7069   if (isClampZeroToOne(Src0, Src1)) {
7070     // const_a, const_b, x -> clamp is safe in all cases including signaling
7071     // nans.
7072     // FIXME: Should this be allowing -0.0?
7073     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
7074   }
7075 
7076   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
7077   // handling no dx10-clamp?
7078   if (Subtarget->enableDX10Clamp()) {
7079     // If NaNs is clamped to 0, we are free to reorder the inputs.
7080 
7081     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
7082       std::swap(Src0, Src1);
7083 
7084     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
7085       std::swap(Src1, Src2);
7086 
7087     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
7088       std::swap(Src0, Src1);
7089 
7090     if (isClampZeroToOne(Src1, Src2))
7091       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
7092   }
7093 
7094   return SDValue();
7095 }
7096 
7097 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
7098                                                  DAGCombinerInfo &DCI) const {
7099   SDValue Src0 = N->getOperand(0);
7100   SDValue Src1 = N->getOperand(1);
7101   if (Src0.isUndef() && Src1.isUndef())
7102     return DCI.DAG.getUNDEF(N->getValueType(0));
7103   return SDValue();
7104 }
7105 
7106 SDValue SITargetLowering::performExtractVectorEltCombine(
7107   SDNode *N, DAGCombinerInfo &DCI) const {
7108   SDValue Vec = N->getOperand(0);
7109   SelectionDAG &DAG = DCI.DAG;
7110 
7111   EVT VecVT = Vec.getValueType();
7112   EVT EltVT = VecVT.getVectorElementType();
7113 
7114   if ((Vec.getOpcode() == ISD::FNEG ||
7115        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
7116     SDLoc SL(N);
7117     EVT EltVT = N->getValueType(0);
7118     SDValue Idx = N->getOperand(1);
7119     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7120                               Vec.getOperand(0), Idx);
7121     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
7122   }
7123 
7124   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
7125   //    =>
7126   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
7127   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
7128   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
7129   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
7130     SDLoc SL(N);
7131     EVT EltVT = N->getValueType(0);
7132     SDValue Idx = N->getOperand(1);
7133     unsigned Opc = Vec.getOpcode();
7134 
7135     switch(Opc) {
7136     default:
7137       return SDValue();
7138       // TODO: Support other binary operations.
7139     case ISD::FADD:
7140     case ISD::ADD:
7141     case ISD::UMIN:
7142     case ISD::UMAX:
7143     case ISD::SMIN:
7144     case ISD::SMAX:
7145     case ISD::FMAXNUM:
7146     case ISD::FMINNUM:
7147       return DAG.getNode(Opc, SL, EltVT,
7148                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7149                                      Vec.getOperand(0), Idx),
7150                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7151                                      Vec.getOperand(1), Idx));
7152     }
7153   }
7154 
7155   if (!DCI.isBeforeLegalize())
7156     return SDValue();
7157 
7158   unsigned VecSize = VecVT.getSizeInBits();
7159   unsigned EltSize = EltVT.getSizeInBits();
7160 
7161   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
7162   // elements. This exposes more load reduction opportunities by replacing
7163   // multiple small extract_vector_elements with a single 32-bit extract.
7164   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
7165   if (EltSize <= 16 &&
7166       EltVT.isByteSized() &&
7167       VecSize > 32 &&
7168       VecSize % 32 == 0 &&
7169       Idx) {
7170     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
7171 
7172     unsigned BitIndex = Idx->getZExtValue() * EltSize;
7173     unsigned EltIdx = BitIndex / 32;
7174     unsigned LeftoverBitIdx = BitIndex % 32;
7175     SDLoc SL(N);
7176 
7177     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
7178     DCI.AddToWorklist(Cast.getNode());
7179 
7180     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
7181                               DAG.getConstant(EltIdx, SL, MVT::i32));
7182     DCI.AddToWorklist(Elt.getNode());
7183     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
7184                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
7185     DCI.AddToWorklist(Srl.getNode());
7186 
7187     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
7188     DCI.AddToWorklist(Trunc.getNode());
7189     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
7190   }
7191 
7192   return SDValue();
7193 }
7194 
7195 static bool convertBuildVectorCastElt(SelectionDAG &DAG,
7196                                       SDValue &Lo, SDValue &Hi) {
7197   if (Hi.getOpcode() == ISD::BITCAST &&
7198       Hi.getOperand(0).getValueType() == MVT::f16 &&
7199       (isa<ConstantSDNode>(Lo) || Lo.isUndef())) {
7200     Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo);
7201     Hi = Hi.getOperand(0);
7202     return true;
7203   }
7204 
7205   return false;
7206 }
7207 
7208 SDValue SITargetLowering::performBuildVectorCombine(
7209   SDNode *N, DAGCombinerInfo &DCI) const {
7210   SDLoc SL(N);
7211 
7212   if (!isTypeLegal(MVT::v2i16))
7213     return SDValue();
7214   SelectionDAG &DAG = DCI.DAG;
7215   EVT VT = N->getValueType(0);
7216 
7217   if (VT == MVT::v2i16) {
7218     SDValue Lo = N->getOperand(0);
7219     SDValue Hi = N->getOperand(1);
7220 
7221     // v2i16 build_vector (const|undef), (bitcast f16:$x)
7222     // -> bitcast (v2f16 build_vector const|undef, $x
7223     if (convertBuildVectorCastElt(DAG, Lo, Hi)) {
7224       SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi  });
7225       return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
7226     }
7227 
7228     if (convertBuildVectorCastElt(DAG, Hi, Lo)) {
7229       SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo  });
7230       return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
7231     }
7232   }
7233 
7234   return SDValue();
7235 }
7236 
7237 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
7238                                           const SDNode *N0,
7239                                           const SDNode *N1) const {
7240   EVT VT = N0->getValueType(0);
7241 
7242   // Only do this if we are not trying to support denormals. v_mad_f32 does not
7243   // support denormals ever.
7244   if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
7245       (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
7246     return ISD::FMAD;
7247 
7248   const TargetOptions &Options = DAG.getTarget().Options;
7249   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
7250        (N0->getFlags().hasAllowContract() &&
7251         N1->getFlags().hasAllowContract())) &&
7252       isFMAFasterThanFMulAndFAdd(VT)) {
7253     return ISD::FMA;
7254   }
7255 
7256   return 0;
7257 }
7258 
7259 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
7260                            EVT VT,
7261                            SDValue N0, SDValue N1, SDValue N2,
7262                            bool Signed) {
7263   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
7264   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
7265   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
7266   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
7267 }
7268 
7269 SDValue SITargetLowering::performAddCombine(SDNode *N,
7270                                             DAGCombinerInfo &DCI) const {
7271   SelectionDAG &DAG = DCI.DAG;
7272   EVT VT = N->getValueType(0);
7273   SDLoc SL(N);
7274   SDValue LHS = N->getOperand(0);
7275   SDValue RHS = N->getOperand(1);
7276 
7277   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
7278       && Subtarget->hasMad64_32() &&
7279       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
7280       VT.getScalarSizeInBits() <= 64) {
7281     if (LHS.getOpcode() != ISD::MUL)
7282       std::swap(LHS, RHS);
7283 
7284     SDValue MulLHS = LHS.getOperand(0);
7285     SDValue MulRHS = LHS.getOperand(1);
7286     SDValue AddRHS = RHS;
7287 
7288     // TODO: Maybe restrict if SGPR inputs.
7289     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
7290         numBitsUnsigned(MulRHS, DAG) <= 32) {
7291       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
7292       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
7293       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
7294       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
7295     }
7296 
7297     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
7298       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
7299       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
7300       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
7301       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
7302     }
7303 
7304     return SDValue();
7305   }
7306 
7307   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
7308     return SDValue();
7309 
7310   // add x, zext (setcc) => addcarry x, 0, setcc
7311   // add x, sext (setcc) => subcarry x, 0, setcc
7312   unsigned Opc = LHS.getOpcode();
7313   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
7314       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
7315     std::swap(RHS, LHS);
7316 
7317   Opc = RHS.getOpcode();
7318   switch (Opc) {
7319   default: break;
7320   case ISD::ZERO_EXTEND:
7321   case ISD::SIGN_EXTEND:
7322   case ISD::ANY_EXTEND: {
7323     auto Cond = RHS.getOperand(0);
7324     if (!isBoolSGPR(Cond))
7325       break;
7326     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
7327     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
7328     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
7329     return DAG.getNode(Opc, SL, VTList, Args);
7330   }
7331   case ISD::ADDCARRY: {
7332     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
7333     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7334     if (!C || C->getZExtValue() != 0) break;
7335     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
7336     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
7337   }
7338   }
7339   return SDValue();
7340 }
7341 
7342 SDValue SITargetLowering::performSubCombine(SDNode *N,
7343                                             DAGCombinerInfo &DCI) const {
7344   SelectionDAG &DAG = DCI.DAG;
7345   EVT VT = N->getValueType(0);
7346 
7347   if (VT != MVT::i32)
7348     return SDValue();
7349 
7350   SDLoc SL(N);
7351   SDValue LHS = N->getOperand(0);
7352   SDValue RHS = N->getOperand(1);
7353 
7354   unsigned Opc = LHS.getOpcode();
7355   if (Opc != ISD::SUBCARRY)
7356     std::swap(RHS, LHS);
7357 
7358   if (LHS.getOpcode() == ISD::SUBCARRY) {
7359     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
7360     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
7361     if (!C || C->getZExtValue() != 0)
7362       return SDValue();
7363     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
7364     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
7365   }
7366   return SDValue();
7367 }
7368 
7369 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
7370   DAGCombinerInfo &DCI) const {
7371 
7372   if (N->getValueType(0) != MVT::i32)
7373     return SDValue();
7374 
7375   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7376   if (!C || C->getZExtValue() != 0)
7377     return SDValue();
7378 
7379   SelectionDAG &DAG = DCI.DAG;
7380   SDValue LHS = N->getOperand(0);
7381 
7382   // addcarry (add x, y), 0, cc => addcarry x, y, cc
7383   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
7384   unsigned LHSOpc = LHS.getOpcode();
7385   unsigned Opc = N->getOpcode();
7386   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
7387       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
7388     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
7389     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
7390   }
7391   return SDValue();
7392 }
7393 
7394 SDValue SITargetLowering::performFAddCombine(SDNode *N,
7395                                              DAGCombinerInfo &DCI) const {
7396   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7397     return SDValue();
7398 
7399   SelectionDAG &DAG = DCI.DAG;
7400   EVT VT = N->getValueType(0);
7401 
7402   SDLoc SL(N);
7403   SDValue LHS = N->getOperand(0);
7404   SDValue RHS = N->getOperand(1);
7405 
7406   // These should really be instruction patterns, but writing patterns with
7407   // source modiifiers is a pain.
7408 
7409   // fadd (fadd (a, a), b) -> mad 2.0, a, b
7410   if (LHS.getOpcode() == ISD::FADD) {
7411     SDValue A = LHS.getOperand(0);
7412     if (A == LHS.getOperand(1)) {
7413       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7414       if (FusedOp != 0) {
7415         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7416         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
7417       }
7418     }
7419   }
7420 
7421   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
7422   if (RHS.getOpcode() == ISD::FADD) {
7423     SDValue A = RHS.getOperand(0);
7424     if (A == RHS.getOperand(1)) {
7425       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7426       if (FusedOp != 0) {
7427         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7428         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
7429       }
7430     }
7431   }
7432 
7433   return SDValue();
7434 }
7435 
7436 SDValue SITargetLowering::performFSubCombine(SDNode *N,
7437                                              DAGCombinerInfo &DCI) const {
7438   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7439     return SDValue();
7440 
7441   SelectionDAG &DAG = DCI.DAG;
7442   SDLoc SL(N);
7443   EVT VT = N->getValueType(0);
7444   assert(!VT.isVector());
7445 
7446   // Try to get the fneg to fold into the source modifier. This undoes generic
7447   // DAG combines and folds them into the mad.
7448   //
7449   // Only do this if we are not trying to support denormals. v_mad_f32 does
7450   // not support denormals ever.
7451   SDValue LHS = N->getOperand(0);
7452   SDValue RHS = N->getOperand(1);
7453   if (LHS.getOpcode() == ISD::FADD) {
7454     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
7455     SDValue A = LHS.getOperand(0);
7456     if (A == LHS.getOperand(1)) {
7457       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7458       if (FusedOp != 0){
7459         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7460         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7461 
7462         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
7463       }
7464     }
7465   }
7466 
7467   if (RHS.getOpcode() == ISD::FADD) {
7468     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
7469 
7470     SDValue A = RHS.getOperand(0);
7471     if (A == RHS.getOperand(1)) {
7472       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7473       if (FusedOp != 0){
7474         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
7475         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
7476       }
7477     }
7478   }
7479 
7480   return SDValue();
7481 }
7482 
7483 SDValue SITargetLowering::performFMACombine(SDNode *N,
7484                                             DAGCombinerInfo &DCI) const {
7485   SelectionDAG &DAG = DCI.DAG;
7486   EVT VT = N->getValueType(0);
7487   SDLoc SL(N);
7488 
7489   if (!Subtarget->hasDLInsts() || VT != MVT::f32)
7490     return SDValue();
7491 
7492   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
7493   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
7494   SDValue Op1 = N->getOperand(0);
7495   SDValue Op2 = N->getOperand(1);
7496   SDValue FMA = N->getOperand(2);
7497 
7498   if (FMA.getOpcode() != ISD::FMA ||
7499       Op1.getOpcode() != ISD::FP_EXTEND ||
7500       Op2.getOpcode() != ISD::FP_EXTEND)
7501     return SDValue();
7502 
7503   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
7504   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
7505   // is sufficient to allow generaing fdot2.
7506   const TargetOptions &Options = DAG.getTarget().Options;
7507   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
7508       (N->getFlags().hasAllowContract() &&
7509        FMA->getFlags().hasAllowContract())) {
7510     Op1 = Op1.getOperand(0);
7511     Op2 = Op2.getOperand(0);
7512     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7513         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7514       return SDValue();
7515 
7516     SDValue Vec1 = Op1.getOperand(0);
7517     SDValue Idx1 = Op1.getOperand(1);
7518     SDValue Vec2 = Op2.getOperand(0);
7519 
7520     SDValue FMAOp1 = FMA.getOperand(0);
7521     SDValue FMAOp2 = FMA.getOperand(1);
7522     SDValue FMAAcc = FMA.getOperand(2);
7523 
7524     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
7525         FMAOp2.getOpcode() != ISD::FP_EXTEND)
7526       return SDValue();
7527 
7528     FMAOp1 = FMAOp1.getOperand(0);
7529     FMAOp2 = FMAOp2.getOperand(0);
7530     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7531         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7532       return SDValue();
7533 
7534     SDValue Vec3 = FMAOp1.getOperand(0);
7535     SDValue Vec4 = FMAOp2.getOperand(0);
7536     SDValue Idx2 = FMAOp1.getOperand(1);
7537 
7538     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
7539         // Idx1 and Idx2 cannot be the same.
7540         Idx1 == Idx2)
7541       return SDValue();
7542 
7543     if (Vec1 == Vec2 || Vec3 == Vec4)
7544       return SDValue();
7545 
7546     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
7547       return SDValue();
7548 
7549     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
7550         (Vec1 == Vec4 && Vec2 == Vec3))
7551       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc);
7552   }
7553   return SDValue();
7554 }
7555 
7556 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
7557                                               DAGCombinerInfo &DCI) const {
7558   SelectionDAG &DAG = DCI.DAG;
7559   SDLoc SL(N);
7560 
7561   SDValue LHS = N->getOperand(0);
7562   SDValue RHS = N->getOperand(1);
7563   EVT VT = LHS.getValueType();
7564   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
7565 
7566   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
7567   if (!CRHS) {
7568     CRHS = dyn_cast<ConstantSDNode>(LHS);
7569     if (CRHS) {
7570       std::swap(LHS, RHS);
7571       CC = getSetCCSwappedOperands(CC);
7572     }
7573   }
7574 
7575   if (CRHS) {
7576     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
7577         isBoolSGPR(LHS.getOperand(0))) {
7578       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
7579       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
7580       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
7581       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
7582       if ((CRHS->isAllOnesValue() &&
7583            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
7584           (CRHS->isNullValue() &&
7585            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
7586         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7587                            DAG.getConstant(-1, SL, MVT::i1));
7588       if ((CRHS->isAllOnesValue() &&
7589            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
7590           (CRHS->isNullValue() &&
7591            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
7592         return LHS.getOperand(0);
7593     }
7594 
7595     uint64_t CRHSVal = CRHS->getZExtValue();
7596     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
7597         LHS.getOpcode() == ISD::SELECT &&
7598         isa<ConstantSDNode>(LHS.getOperand(1)) &&
7599         isa<ConstantSDNode>(LHS.getOperand(2)) &&
7600         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
7601         isBoolSGPR(LHS.getOperand(0))) {
7602       // Given CT != FT:
7603       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
7604       // setcc (select cc, CT, CF), CF, ne => cc
7605       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
7606       // setcc (select cc, CT, CF), CT, eq => cc
7607       uint64_t CT = LHS.getConstantOperandVal(1);
7608       uint64_t CF = LHS.getConstantOperandVal(2);
7609 
7610       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
7611           (CT == CRHSVal && CC == ISD::SETNE))
7612         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7613                            DAG.getConstant(-1, SL, MVT::i1));
7614       if ((CF == CRHSVal && CC == ISD::SETNE) ||
7615           (CT == CRHSVal && CC == ISD::SETEQ))
7616         return LHS.getOperand(0);
7617     }
7618   }
7619 
7620   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
7621                                            VT != MVT::f16))
7622     return SDValue();
7623 
7624   // Match isinf pattern
7625   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
7626   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
7627     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
7628     if (!CRHS)
7629       return SDValue();
7630 
7631     const APFloat &APF = CRHS->getValueAPF();
7632     if (APF.isInfinity() && !APF.isNegative()) {
7633       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
7634       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
7635                          DAG.getConstant(Mask, SL, MVT::i32));
7636     }
7637   }
7638 
7639   return SDValue();
7640 }
7641 
7642 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
7643                                                      DAGCombinerInfo &DCI) const {
7644   SelectionDAG &DAG = DCI.DAG;
7645   SDLoc SL(N);
7646   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
7647 
7648   SDValue Src = N->getOperand(0);
7649   SDValue Srl = N->getOperand(0);
7650   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
7651     Srl = Srl.getOperand(0);
7652 
7653   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
7654   if (Srl.getOpcode() == ISD::SRL) {
7655     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
7656     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
7657     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
7658 
7659     if (const ConstantSDNode *C =
7660         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
7661       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
7662                                EVT(MVT::i32));
7663 
7664       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
7665       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
7666         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
7667                            MVT::f32, Srl);
7668       }
7669     }
7670   }
7671 
7672   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
7673 
7674   KnownBits Known;
7675   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
7676                                         !DCI.isBeforeLegalizeOps());
7677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7678   if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
7679       TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
7680     DCI.CommitTargetLoweringOpt(TLO);
7681   }
7682 
7683   return SDValue();
7684 }
7685 
7686 SDValue SITargetLowering::performClampCombine(SDNode *N,
7687                                               DAGCombinerInfo &DCI) const {
7688   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
7689   if (!CSrc)
7690     return SDValue();
7691 
7692   const APFloat &F = CSrc->getValueAPF();
7693   APFloat Zero = APFloat::getZero(F.getSemantics());
7694   APFloat::cmpResult Cmp0 = F.compare(Zero);
7695   if (Cmp0 == APFloat::cmpLessThan ||
7696       (Cmp0 == APFloat::cmpUnordered && Subtarget->enableDX10Clamp())) {
7697     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
7698   }
7699 
7700   APFloat One(F.getSemantics(), "1.0");
7701   APFloat::cmpResult Cmp1 = F.compare(One);
7702   if (Cmp1 == APFloat::cmpGreaterThan)
7703     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
7704 
7705   return SDValue(CSrc, 0);
7706 }
7707 
7708 
7709 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
7710                                             DAGCombinerInfo &DCI) const {
7711   switch (N->getOpcode()) {
7712   default:
7713     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7714   case ISD::ADD:
7715     return performAddCombine(N, DCI);
7716   case ISD::SUB:
7717     return performSubCombine(N, DCI);
7718   case ISD::ADDCARRY:
7719   case ISD::SUBCARRY:
7720     return performAddCarrySubCarryCombine(N, DCI);
7721   case ISD::FADD:
7722     return performFAddCombine(N, DCI);
7723   case ISD::FSUB:
7724     return performFSubCombine(N, DCI);
7725   case ISD::SETCC:
7726     return performSetCCCombine(N, DCI);
7727   case ISD::FMAXNUM:
7728   case ISD::FMINNUM:
7729   case ISD::SMAX:
7730   case ISD::SMIN:
7731   case ISD::UMAX:
7732   case ISD::UMIN:
7733   case AMDGPUISD::FMIN_LEGACY:
7734   case AMDGPUISD::FMAX_LEGACY: {
7735     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
7736         getTargetMachine().getOptLevel() > CodeGenOpt::None)
7737       return performMinMaxCombine(N, DCI);
7738     break;
7739   }
7740   case ISD::FMA:
7741     return performFMACombine(N, DCI);
7742   case ISD::LOAD: {
7743     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
7744       return Widended;
7745     LLVM_FALLTHROUGH;
7746   }
7747   case ISD::STORE:
7748   case ISD::ATOMIC_LOAD:
7749   case ISD::ATOMIC_STORE:
7750   case ISD::ATOMIC_CMP_SWAP:
7751   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
7752   case ISD::ATOMIC_SWAP:
7753   case ISD::ATOMIC_LOAD_ADD:
7754   case ISD::ATOMIC_LOAD_SUB:
7755   case ISD::ATOMIC_LOAD_AND:
7756   case ISD::ATOMIC_LOAD_OR:
7757   case ISD::ATOMIC_LOAD_XOR:
7758   case ISD::ATOMIC_LOAD_NAND:
7759   case ISD::ATOMIC_LOAD_MIN:
7760   case ISD::ATOMIC_LOAD_MAX:
7761   case ISD::ATOMIC_LOAD_UMIN:
7762   case ISD::ATOMIC_LOAD_UMAX:
7763   case AMDGPUISD::ATOMIC_INC:
7764   case AMDGPUISD::ATOMIC_DEC:
7765   case AMDGPUISD::ATOMIC_LOAD_FADD:
7766   case AMDGPUISD::ATOMIC_LOAD_FMIN:
7767   case AMDGPUISD::ATOMIC_LOAD_FMAX:  // TODO: Target mem intrinsics.
7768     if (DCI.isBeforeLegalize())
7769       break;
7770     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
7771   case ISD::AND:
7772     return performAndCombine(N, DCI);
7773   case ISD::OR:
7774     return performOrCombine(N, DCI);
7775   case ISD::XOR:
7776     return performXorCombine(N, DCI);
7777   case ISD::ZERO_EXTEND:
7778     return performZeroExtendCombine(N, DCI);
7779   case AMDGPUISD::FP_CLASS:
7780     return performClassCombine(N, DCI);
7781   case ISD::FCANONICALIZE:
7782     return performFCanonicalizeCombine(N, DCI);
7783   case AMDGPUISD::RCP:
7784     return performRcpCombine(N, DCI);
7785   case AMDGPUISD::FRACT:
7786   case AMDGPUISD::RSQ:
7787   case AMDGPUISD::RCP_LEGACY:
7788   case AMDGPUISD::RSQ_LEGACY:
7789   case AMDGPUISD::RCP_IFLAG:
7790   case AMDGPUISD::RSQ_CLAMP:
7791   case AMDGPUISD::LDEXP: {
7792     SDValue Src = N->getOperand(0);
7793     if (Src.isUndef())
7794       return Src;
7795     break;
7796   }
7797   case ISD::SINT_TO_FP:
7798   case ISD::UINT_TO_FP:
7799     return performUCharToFloatCombine(N, DCI);
7800   case AMDGPUISD::CVT_F32_UBYTE0:
7801   case AMDGPUISD::CVT_F32_UBYTE1:
7802   case AMDGPUISD::CVT_F32_UBYTE2:
7803   case AMDGPUISD::CVT_F32_UBYTE3:
7804     return performCvtF32UByteNCombine(N, DCI);
7805   case AMDGPUISD::FMED3:
7806     return performFMed3Combine(N, DCI);
7807   case AMDGPUISD::CVT_PKRTZ_F16_F32:
7808     return performCvtPkRTZCombine(N, DCI);
7809   case AMDGPUISD::CLAMP:
7810     return performClampCombine(N, DCI);
7811   case ISD::SCALAR_TO_VECTOR: {
7812     SelectionDAG &DAG = DCI.DAG;
7813     EVT VT = N->getValueType(0);
7814 
7815     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
7816     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
7817       SDLoc SL(N);
7818       SDValue Src = N->getOperand(0);
7819       EVT EltVT = Src.getValueType();
7820       if (EltVT == MVT::f16)
7821         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
7822 
7823       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
7824       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
7825     }
7826 
7827     break;
7828   }
7829   case ISD::EXTRACT_VECTOR_ELT:
7830     return performExtractVectorEltCombine(N, DCI);
7831   case ISD::BUILD_VECTOR:
7832     return performBuildVectorCombine(N, DCI);
7833   }
7834   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7835 }
7836 
7837 /// Helper function for adjustWritemask
7838 static unsigned SubIdx2Lane(unsigned Idx) {
7839   switch (Idx) {
7840   default: return 0;
7841   case AMDGPU::sub0: return 0;
7842   case AMDGPU::sub1: return 1;
7843   case AMDGPU::sub2: return 2;
7844   case AMDGPU::sub3: return 3;
7845   }
7846 }
7847 
7848 /// Adjust the writemask of MIMG instructions
7849 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
7850                                           SelectionDAG &DAG) const {
7851   unsigned Opcode = Node->getMachineOpcode();
7852 
7853   // Subtract 1 because the vdata output is not a MachineSDNode operand.
7854   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
7855   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
7856     return Node; // not implemented for D16
7857 
7858   SDNode *Users[4] = { nullptr };
7859   unsigned Lane = 0;
7860   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
7861   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
7862   unsigned NewDmask = 0;
7863   bool HasChain = Node->getNumValues() > 1;
7864 
7865   if (OldDmask == 0) {
7866     // These are folded out, but on the chance it happens don't assert.
7867     return Node;
7868   }
7869 
7870   // Try to figure out the used register components
7871   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
7872        I != E; ++I) {
7873 
7874     // Don't look at users of the chain.
7875     if (I.getUse().getResNo() != 0)
7876       continue;
7877 
7878     // Abort if we can't understand the usage
7879     if (!I->isMachineOpcode() ||
7880         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
7881       return Node;
7882 
7883     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
7884     // Note that subregs are packed, i.e. Lane==0 is the first bit set
7885     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
7886     // set, etc.
7887     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
7888 
7889     // Set which texture component corresponds to the lane.
7890     unsigned Comp;
7891     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
7892       Comp = countTrailingZeros(Dmask);
7893       Dmask &= ~(1 << Comp);
7894     }
7895 
7896     // Abort if we have more than one user per component
7897     if (Users[Lane])
7898       return Node;
7899 
7900     Users[Lane] = *I;
7901     NewDmask |= 1 << Comp;
7902   }
7903 
7904   // Abort if there's no change
7905   if (NewDmask == OldDmask)
7906     return Node;
7907 
7908   unsigned BitsSet = countPopulation(NewDmask);
7909 
7910   int NewOpcode = AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), BitsSet);
7911   assert(NewOpcode != -1 &&
7912          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
7913          "failed to find equivalent MIMG op");
7914 
7915   // Adjust the writemask in the node
7916   SmallVector<SDValue, 12> Ops;
7917   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
7918   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
7919   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
7920 
7921   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
7922 
7923   MVT ResultVT = BitsSet == 1 ?
7924     SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet);
7925   SDVTList NewVTList = HasChain ?
7926     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
7927 
7928 
7929   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
7930                                               NewVTList, Ops);
7931 
7932   if (HasChain) {
7933     // Update chain.
7934     NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end());
7935     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
7936   }
7937 
7938   if (BitsSet == 1) {
7939     assert(Node->hasNUsesOfValue(1, 0));
7940     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
7941                                       SDLoc(Node), Users[Lane]->getValueType(0),
7942                                       SDValue(NewNode, 0));
7943     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
7944     return nullptr;
7945   }
7946 
7947   // Update the users of the node with the new indices
7948   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
7949     SDNode *User = Users[i];
7950     if (!User)
7951       continue;
7952 
7953     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
7954     DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
7955 
7956     switch (Idx) {
7957     default: break;
7958     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
7959     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
7960     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
7961     }
7962   }
7963 
7964   DAG.RemoveDeadNode(Node);
7965   return nullptr;
7966 }
7967 
7968 static bool isFrameIndexOp(SDValue Op) {
7969   if (Op.getOpcode() == ISD::AssertZext)
7970     Op = Op.getOperand(0);
7971 
7972   return isa<FrameIndexSDNode>(Op);
7973 }
7974 
7975 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
7976 /// with frame index operands.
7977 /// LLVM assumes that inputs are to these instructions are registers.
7978 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
7979                                                         SelectionDAG &DAG) const {
7980   if (Node->getOpcode() == ISD::CopyToReg) {
7981     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
7982     SDValue SrcVal = Node->getOperand(2);
7983 
7984     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
7985     // to try understanding copies to physical registers.
7986     if (SrcVal.getValueType() == MVT::i1 &&
7987         TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
7988       SDLoc SL(Node);
7989       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
7990       SDValue VReg = DAG.getRegister(
7991         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
7992 
7993       SDNode *Glued = Node->getGluedNode();
7994       SDValue ToVReg
7995         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
7996                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
7997       SDValue ToResultReg
7998         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
7999                            VReg, ToVReg.getValue(1));
8000       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
8001       DAG.RemoveDeadNode(Node);
8002       return ToResultReg.getNode();
8003     }
8004   }
8005 
8006   SmallVector<SDValue, 8> Ops;
8007   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
8008     if (!isFrameIndexOp(Node->getOperand(i))) {
8009       Ops.push_back(Node->getOperand(i));
8010       continue;
8011     }
8012 
8013     SDLoc DL(Node);
8014     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
8015                                      Node->getOperand(i).getValueType(),
8016                                      Node->getOperand(i)), 0));
8017   }
8018 
8019   return DAG.UpdateNodeOperands(Node, Ops);
8020 }
8021 
8022 /// Fold the instructions after selecting them.
8023 /// Returns null if users were already updated.
8024 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
8025                                           SelectionDAG &DAG) const {
8026   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8027   unsigned Opcode = Node->getMachineOpcode();
8028 
8029   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
8030       !TII->isGather4(Opcode)) {
8031     return adjustWritemask(Node, DAG);
8032   }
8033 
8034   if (Opcode == AMDGPU::INSERT_SUBREG ||
8035       Opcode == AMDGPU::REG_SEQUENCE) {
8036     legalizeTargetIndependentNode(Node, DAG);
8037     return Node;
8038   }
8039 
8040   switch (Opcode) {
8041   case AMDGPU::V_DIV_SCALE_F32:
8042   case AMDGPU::V_DIV_SCALE_F64: {
8043     // Satisfy the operand register constraint when one of the inputs is
8044     // undefined. Ordinarily each undef value will have its own implicit_def of
8045     // a vreg, so force these to use a single register.
8046     SDValue Src0 = Node->getOperand(0);
8047     SDValue Src1 = Node->getOperand(1);
8048     SDValue Src2 = Node->getOperand(2);
8049 
8050     if ((Src0.isMachineOpcode() &&
8051          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
8052         (Src0 == Src1 || Src0 == Src2))
8053       break;
8054 
8055     MVT VT = Src0.getValueType().getSimpleVT();
8056     const TargetRegisterClass *RC = getRegClassFor(VT);
8057 
8058     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
8059     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
8060 
8061     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
8062                                       UndefReg, Src0, SDValue());
8063 
8064     // src0 must be the same register as src1 or src2, even if the value is
8065     // undefined, so make sure we don't violate this constraint.
8066     if (Src0.isMachineOpcode() &&
8067         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
8068       if (Src1.isMachineOpcode() &&
8069           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
8070         Src0 = Src1;
8071       else if (Src2.isMachineOpcode() &&
8072                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
8073         Src0 = Src2;
8074       else {
8075         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
8076         Src0 = UndefReg;
8077         Src1 = UndefReg;
8078       }
8079     } else
8080       break;
8081 
8082     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
8083     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
8084       Ops.push_back(Node->getOperand(I));
8085 
8086     Ops.push_back(ImpDef.getValue(1));
8087     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
8088   }
8089   default:
8090     break;
8091   }
8092 
8093   return Node;
8094 }
8095 
8096 /// Assign the register class depending on the number of
8097 /// bits set in the writemask
8098 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8099                                                      SDNode *Node) const {
8100   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8101 
8102   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
8103 
8104   if (TII->isVOP3(MI.getOpcode())) {
8105     // Make sure constant bus requirements are respected.
8106     TII->legalizeOperandsVOP3(MRI, MI);
8107     return;
8108   }
8109 
8110   // Replace unused atomics with the no return version.
8111   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
8112   if (NoRetAtomicOp != -1) {
8113     if (!Node->hasAnyUseOfValue(0)) {
8114       MI.setDesc(TII->get(NoRetAtomicOp));
8115       MI.RemoveOperand(0);
8116       return;
8117     }
8118 
8119     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
8120     // instruction, because the return type of these instructions is a vec2 of
8121     // the memory type, so it can be tied to the input operand.
8122     // This means these instructions always have a use, so we need to add a
8123     // special case to check if the atomic has only one extract_subreg use,
8124     // which itself has no uses.
8125     if ((Node->hasNUsesOfValue(1, 0) &&
8126          Node->use_begin()->isMachineOpcode() &&
8127          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
8128          !Node->use_begin()->hasAnyUseOfValue(0))) {
8129       unsigned Def = MI.getOperand(0).getReg();
8130 
8131       // Change this into a noret atomic.
8132       MI.setDesc(TII->get(NoRetAtomicOp));
8133       MI.RemoveOperand(0);
8134 
8135       // If we only remove the def operand from the atomic instruction, the
8136       // extract_subreg will be left with a use of a vreg without a def.
8137       // So we need to insert an implicit_def to avoid machine verifier
8138       // errors.
8139       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
8140               TII->get(AMDGPU::IMPLICIT_DEF), Def);
8141     }
8142     return;
8143   }
8144 }
8145 
8146 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
8147                               uint64_t Val) {
8148   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
8149   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
8150 }
8151 
8152 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
8153                                                 const SDLoc &DL,
8154                                                 SDValue Ptr) const {
8155   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8156 
8157   // Build the half of the subregister with the constants before building the
8158   // full 128-bit register. If we are building multiple resource descriptors,
8159   // this will allow CSEing of the 2-component register.
8160   const SDValue Ops0[] = {
8161     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
8162     buildSMovImm32(DAG, DL, 0),
8163     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
8164     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
8165     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
8166   };
8167 
8168   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
8169                                                 MVT::v2i32, Ops0), 0);
8170 
8171   // Combine the constants and the pointer.
8172   const SDValue Ops1[] = {
8173     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
8174     Ptr,
8175     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
8176     SubRegHi,
8177     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
8178   };
8179 
8180   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
8181 }
8182 
8183 /// Return a resource descriptor with the 'Add TID' bit enabled
8184 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
8185 ///        of the resource descriptor) to create an offset, which is added to
8186 ///        the resource pointer.
8187 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
8188                                            SDValue Ptr, uint32_t RsrcDword1,
8189                                            uint64_t RsrcDword2And3) const {
8190   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
8191   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
8192   if (RsrcDword1) {
8193     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
8194                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
8195                     0);
8196   }
8197 
8198   SDValue DataLo = buildSMovImm32(DAG, DL,
8199                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
8200   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
8201 
8202   const SDValue Ops[] = {
8203     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
8204     PtrLo,
8205     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
8206     PtrHi,
8207     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
8208     DataLo,
8209     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
8210     DataHi,
8211     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
8212   };
8213 
8214   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
8215 }
8216 
8217 //===----------------------------------------------------------------------===//
8218 //                         SI Inline Assembly Support
8219 //===----------------------------------------------------------------------===//
8220 
8221 std::pair<unsigned, const TargetRegisterClass *>
8222 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
8223                                                StringRef Constraint,
8224                                                MVT VT) const {
8225   const TargetRegisterClass *RC = nullptr;
8226   if (Constraint.size() == 1) {
8227     switch (Constraint[0]) {
8228     default:
8229       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8230     case 's':
8231     case 'r':
8232       switch (VT.getSizeInBits()) {
8233       default:
8234         return std::make_pair(0U, nullptr);
8235       case 32:
8236       case 16:
8237         RC = &AMDGPU::SReg_32_XM0RegClass;
8238         break;
8239       case 64:
8240         RC = &AMDGPU::SGPR_64RegClass;
8241         break;
8242       case 128:
8243         RC = &AMDGPU::SReg_128RegClass;
8244         break;
8245       case 256:
8246         RC = &AMDGPU::SReg_256RegClass;
8247         break;
8248       case 512:
8249         RC = &AMDGPU::SReg_512RegClass;
8250         break;
8251       }
8252       break;
8253     case 'v':
8254       switch (VT.getSizeInBits()) {
8255       default:
8256         return std::make_pair(0U, nullptr);
8257       case 32:
8258       case 16:
8259         RC = &AMDGPU::VGPR_32RegClass;
8260         break;
8261       case 64:
8262         RC = &AMDGPU::VReg_64RegClass;
8263         break;
8264       case 96:
8265         RC = &AMDGPU::VReg_96RegClass;
8266         break;
8267       case 128:
8268         RC = &AMDGPU::VReg_128RegClass;
8269         break;
8270       case 256:
8271         RC = &AMDGPU::VReg_256RegClass;
8272         break;
8273       case 512:
8274         RC = &AMDGPU::VReg_512RegClass;
8275         break;
8276       }
8277       break;
8278     }
8279     // We actually support i128, i16 and f16 as inline parameters
8280     // even if they are not reported as legal
8281     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
8282                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
8283       return std::make_pair(0U, RC);
8284   }
8285 
8286   if (Constraint.size() > 1) {
8287     if (Constraint[1] == 'v') {
8288       RC = &AMDGPU::VGPR_32RegClass;
8289     } else if (Constraint[1] == 's') {
8290       RC = &AMDGPU::SGPR_32RegClass;
8291     }
8292 
8293     if (RC) {
8294       uint32_t Idx;
8295       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
8296       if (!Failed && Idx < RC->getNumRegs())
8297         return std::make_pair(RC->getRegister(Idx), RC);
8298     }
8299   }
8300   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8301 }
8302 
8303 SITargetLowering::ConstraintType
8304 SITargetLowering::getConstraintType(StringRef Constraint) const {
8305   if (Constraint.size() == 1) {
8306     switch (Constraint[0]) {
8307     default: break;
8308     case 's':
8309     case 'v':
8310       return C_RegisterClass;
8311     }
8312   }
8313   return TargetLowering::getConstraintType(Constraint);
8314 }
8315 
8316 // Figure out which registers should be reserved for stack access. Only after
8317 // the function is legalized do we know all of the non-spill stack objects or if
8318 // calls are present.
8319 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
8320   MachineRegisterInfo &MRI = MF.getRegInfo();
8321   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8322   const MachineFrameInfo &MFI = MF.getFrameInfo();
8323   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
8324 
8325   if (Info->isEntryFunction()) {
8326     // Callable functions have fixed registers used for stack access.
8327     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
8328   }
8329 
8330   // We have to assume the SP is needed in case there are calls in the function
8331   // during lowering. Calls are only detected after the function is
8332   // lowered. We're about to reserve registers, so don't bother using it if we
8333   // aren't really going to use it.
8334   bool NeedSP = !Info->isEntryFunction() ||
8335     MFI.hasVarSizedObjects() ||
8336     MFI.hasCalls();
8337 
8338   if (NeedSP) {
8339     unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
8340     Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
8341 
8342     assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
8343     assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
8344                                Info->getStackPtrOffsetReg()));
8345     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
8346   }
8347 
8348   MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
8349   MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
8350   MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
8351                      Info->getScratchWaveOffsetReg());
8352 
8353   Info->limitOccupancy(MF);
8354 
8355   TargetLoweringBase::finalizeLowering(MF);
8356 }
8357 
8358 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
8359                                                      KnownBits &Known,
8360                                                      const APInt &DemandedElts,
8361                                                      const SelectionDAG &DAG,
8362                                                      unsigned Depth) const {
8363   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
8364                                                 DAG, Depth);
8365 
8366   if (getSubtarget()->enableHugePrivateBuffer())
8367     return;
8368 
8369   // Technically it may be possible to have a dispatch with a single workitem
8370   // that uses the full private memory size, but that's not really useful. We
8371   // can't use vaddr in MUBUF instructions if we don't know the address
8372   // calculation won't overflow, so assume the sign bit is never set.
8373   Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);
8374 }
8375 
8376 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
8377   FunctionLoweringInfo * FLI, DivergenceAnalysis * DA) const
8378 {
8379   switch (N->getOpcode()) {
8380     case ISD::Register:
8381     case ISD::CopyFromReg:
8382     {
8383       const RegisterSDNode *R = nullptr;
8384       if (N->getOpcode() == ISD::Register) {
8385         R = dyn_cast<RegisterSDNode>(N);
8386       }
8387       else {
8388         R = dyn_cast<RegisterSDNode>(N->getOperand(1));
8389       }
8390       if (R)
8391       {
8392         const MachineFunction * MF = FLI->MF;
8393         const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
8394         const MachineRegisterInfo &MRI = MF->getRegInfo();
8395         const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
8396         unsigned Reg = R->getReg();
8397         if (TRI.isPhysicalRegister(Reg))
8398           return TRI.isVGPR(MRI, Reg);
8399 
8400         if (MRI.isLiveIn(Reg)) {
8401           // workitem.id.x workitem.id.y workitem.id.z
8402           // Any VGPR formal argument is also considered divergent
8403           if (TRI.isVGPR(MRI, Reg))
8404               return true;
8405           // Formal arguments of non-entry functions
8406           // are conservatively considered divergent
8407           else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
8408             return true;
8409         }
8410         return !DA || DA->isDivergent(FLI->getValueFromVirtualReg(Reg));
8411       }
8412     }
8413     break;
8414     case ISD::LOAD: {
8415       const LoadSDNode *L = dyn_cast<LoadSDNode>(N);
8416       if (L->getMemOperand()->getAddrSpace() ==
8417           Subtarget->getAMDGPUAS().PRIVATE_ADDRESS)
8418         return true;
8419     } break;
8420     case ISD::CALLSEQ_END:
8421     return true;
8422     break;
8423     case ISD::INTRINSIC_WO_CHAIN:
8424     {
8425 
8426     }
8427       return AMDGPU::isIntrinsicSourceOfDivergence(
8428       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
8429     case ISD::INTRINSIC_W_CHAIN:
8430       return AMDGPU::isIntrinsicSourceOfDivergence(
8431       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
8432     // In some cases intrinsics that are a source of divergence have been
8433     // lowered to AMDGPUISD so we also need to check those too.
8434     case AMDGPUISD::INTERP_MOV:
8435     case AMDGPUISD::INTERP_P1:
8436     case AMDGPUISD::INTERP_P2:
8437       return true;
8438   }
8439   return false;
8440 }
8441