1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Custom DAG lowering for SI
13 //===----------------------------------------------------------------------===//
17 #define _USE_MATH_DEFINES
22 #include "AMDGPUIntrinsicInfo.h"
23 #include "AMDGPUSubtarget.h"
24 #include "SIDefines.h"
25 #include "SIISelLowering.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/CodeGen/CallingConvLower.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/Analysis.h"
36 #include "llvm/IR/DiagnosticInfo.h"
37 #include "llvm/IR/Function.h"
41 static cl::opt<bool> EnableVGPRIndexMode(
42 "amdgpu-vgpr-index-mode",
43 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
47 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
48 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
49 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
50 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
51 return AMDGPU::SGPR0 + Reg;
54 llvm_unreachable("Cannot allocate sgpr");
57 SITargetLowering::SITargetLowering(const TargetMachine &TM,
58 const SISubtarget &STI)
59 : AMDGPUTargetLowering(TM, STI) {
60 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
61 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
63 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
64 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
66 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
67 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
68 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
70 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
71 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
73 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
74 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
76 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
77 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
79 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
80 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
82 if (Subtarget->has16BitInsts()) {
83 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
84 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
87 computeRegisterProperties(STI.getRegisterInfo());
89 // We need to custom lower vector stores from local memory
90 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
91 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
92 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
93 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
94 setOperationAction(ISD::LOAD, MVT::i1, Custom);
96 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
97 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
98 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
99 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
100 setOperationAction(ISD::STORE, MVT::i1, Custom);
102 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
103 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
104 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
105 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
106 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
107 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
108 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
109 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
110 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
111 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
114 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
115 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
116 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
118 setOperationAction(ISD::SELECT, MVT::i1, Promote);
119 setOperationAction(ISD::SELECT, MVT::i64, Custom);
120 setOperationAction(ISD::SELECT, MVT::f64, Promote);
121 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
123 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
124 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
125 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
126 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
127 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
129 setOperationAction(ISD::SETCC, MVT::i1, Promote);
130 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
131 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
132 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
134 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
135 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
137 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
138 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
139 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
140 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
141 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
142 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
143 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
145 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
146 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
147 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
149 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
150 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
151 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
152 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
153 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
154 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
156 // We only support LOAD/STORE and vector manipulation ops for vectors
157 // with > 4 elements.
158 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) {
159 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
163 case ISD::BUILD_VECTOR:
165 case ISD::EXTRACT_VECTOR_ELT:
166 case ISD::INSERT_VECTOR_ELT:
167 case ISD::INSERT_SUBVECTOR:
168 case ISD::EXTRACT_SUBVECTOR:
169 case ISD::SCALAR_TO_VECTOR:
171 case ISD::CONCAT_VECTORS:
172 setOperationAction(Op, VT, Custom);
175 setOperationAction(Op, VT, Expand);
181 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
182 // is expanded to avoid having two separate loops in case the index is a VGPR.
184 // Most operations are naturally 32-bit vector operations. We only support
185 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
186 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
187 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
188 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
190 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
191 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
193 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
194 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
196 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
197 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
200 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
201 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
202 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
203 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
205 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
206 // and output demarshalling
207 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
208 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
210 // We can't return success/failure, only the old value,
211 // let LLVM add the comparison
212 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
213 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
215 if (getSubtarget()->hasFlatAddressSpace()) {
216 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
217 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
220 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
221 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
223 // On SI this is s_memtime and s_memrealtime on VI.
224 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
225 setOperationAction(ISD::TRAP, MVT::Other, Custom);
227 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
228 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
230 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
231 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
232 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
233 setOperationAction(ISD::FRINT, MVT::f64, Legal);
236 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
238 setOperationAction(ISD::FSIN, MVT::f32, Custom);
239 setOperationAction(ISD::FCOS, MVT::f32, Custom);
240 setOperationAction(ISD::FDIV, MVT::f32, Custom);
241 setOperationAction(ISD::FDIV, MVT::f64, Custom);
243 if (Subtarget->has16BitInsts()) {
244 setOperationAction(ISD::Constant, MVT::i16, Legal);
246 setOperationAction(ISD::SMIN, MVT::i16, Legal);
247 setOperationAction(ISD::SMAX, MVT::i16, Legal);
249 setOperationAction(ISD::UMIN, MVT::i16, Legal);
250 setOperationAction(ISD::UMAX, MVT::i16, Legal);
252 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
253 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
255 setOperationAction(ISD::ROTR, MVT::i16, Promote);
256 setOperationAction(ISD::ROTL, MVT::i16, Promote);
258 setOperationAction(ISD::SDIV, MVT::i16, Promote);
259 setOperationAction(ISD::UDIV, MVT::i16, Promote);
260 setOperationAction(ISD::SREM, MVT::i16, Promote);
261 setOperationAction(ISD::UREM, MVT::i16, Promote);
263 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
264 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
266 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
267 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
268 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
269 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
271 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
273 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
275 setOperationAction(ISD::LOAD, MVT::i16, Custom);
277 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
279 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
280 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
281 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
282 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
284 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
285 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
286 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
287 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
289 // F16 - Constant Actions.
290 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
292 // F16 - Load/Store Actions.
293 setOperationAction(ISD::LOAD, MVT::f16, Promote);
294 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
295 setOperationAction(ISD::STORE, MVT::f16, Promote);
296 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
298 // F16 - VOP1 Actions.
299 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
300 setOperationAction(ISD::FCOS, MVT::f16, Promote);
301 setOperationAction(ISD::FSIN, MVT::f16, Promote);
302 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
303 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
304 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
305 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
307 // F16 - VOP2 Actions.
308 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
309 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
310 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
311 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
312 setOperationAction(ISD::FDIV, MVT::f16, Custom);
314 // F16 - VOP3 Actions.
315 setOperationAction(ISD::FMA, MVT::f16, Legal);
316 if (!Subtarget->hasFP16Denormals())
317 setOperationAction(ISD::FMAD, MVT::f16, Legal);
320 setTargetDAGCombine(ISD::FADD);
321 setTargetDAGCombine(ISD::FSUB);
322 setTargetDAGCombine(ISD::FMINNUM);
323 setTargetDAGCombine(ISD::FMAXNUM);
324 setTargetDAGCombine(ISD::SMIN);
325 setTargetDAGCombine(ISD::SMAX);
326 setTargetDAGCombine(ISD::UMIN);
327 setTargetDAGCombine(ISD::UMAX);
328 setTargetDAGCombine(ISD::SETCC);
329 setTargetDAGCombine(ISD::AND);
330 setTargetDAGCombine(ISD::OR);
331 setTargetDAGCombine(ISD::XOR);
332 setTargetDAGCombine(ISD::SINT_TO_FP);
333 setTargetDAGCombine(ISD::UINT_TO_FP);
334 setTargetDAGCombine(ISD::FCANONICALIZE);
336 // All memory operations. Some folding on the pointer operand is done to help
337 // matching the constant offsets in the addressing modes.
338 setTargetDAGCombine(ISD::LOAD);
339 setTargetDAGCombine(ISD::STORE);
340 setTargetDAGCombine(ISD::ATOMIC_LOAD);
341 setTargetDAGCombine(ISD::ATOMIC_STORE);
342 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
343 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
344 setTargetDAGCombine(ISD::ATOMIC_SWAP);
345 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
346 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
347 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
348 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
349 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
350 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
351 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
352 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
353 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
354 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
356 setSchedulingPreference(Sched::RegPressure);
359 const SISubtarget *SITargetLowering::getSubtarget() const {
360 return static_cast<const SISubtarget *>(Subtarget);
363 //===----------------------------------------------------------------------===//
364 // TargetLowering queries
365 //===----------------------------------------------------------------------===//
367 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
369 unsigned IntrID) const {
371 case Intrinsic::amdgcn_atomic_inc:
372 case Intrinsic::amdgcn_atomic_dec:
373 Info.opc = ISD::INTRINSIC_W_CHAIN;
374 Info.memVT = MVT::getVT(CI.getType());
375 Info.ptrVal = CI.getOperand(0);
379 Info.writeMem = true;
386 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
388 // SI has some legal vector types, but no legal vector operations. Say no
389 // shuffles are legal in order to prefer scalarizing some vector operations.
393 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
394 // Flat instructions do not have offsets, and only have the register
396 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
399 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
400 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
401 // additionally can do r + r + i with addr64. 32-bit has more addressing
402 // mode options. Depending on the resource constant, it can also do
403 // (i64 r0) + (i32 r1) * (i14 i).
405 // Private arrays end up using a scratch buffer most of the time, so also
406 // assume those use MUBUF instructions. Scratch loads / stores are currently
407 // implemented as mubuf instructions with offen bit set, so slightly
408 // different than the normal addr64.
409 if (!isUInt<12>(AM.BaseOffs))
412 // FIXME: Since we can split immediate into soffset and immediate offset,
413 // would it make sense to allow any immediate?
416 case 0: // r + i or just i, depending on HasBaseReg.
419 return true; // We have r + r or r + i.
426 // Allow 2 * r as r + r
427 // Or 2 * r + i is allowed as r + r + i.
429 default: // Don't allow n * r
434 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
435 const AddrMode &AM, Type *Ty,
437 // No global is ever allowed as a base.
442 case AMDGPUAS::GLOBAL_ADDRESS: {
443 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
444 // Assume the we will use FLAT for all global memory accesses
446 // FIXME: This assumption is currently wrong. On VI we still use
447 // MUBUF instructions for the r + i addressing mode. As currently
448 // implemented, the MUBUF instructions only work on buffer < 4GB.
449 // It may be possible to support > 4GB buffers with MUBUF instructions,
450 // by setting the stride value in the resource descriptor which would
451 // increase the size limit to (stride * 4GB). However, this is risky,
452 // because it has never been validated.
453 return isLegalFlatAddressingMode(AM);
456 return isLegalMUBUFAddressingMode(AM);
458 case AMDGPUAS::CONSTANT_ADDRESS: {
459 // If the offset isn't a multiple of 4, it probably isn't going to be
460 // correctly aligned.
461 // FIXME: Can we get the real alignment here?
462 if (AM.BaseOffs % 4 != 0)
463 return isLegalMUBUFAddressingMode(AM);
465 // There are no SMRD extloads, so if we have to do a small type access we
466 // will use a MUBUF load.
467 // FIXME?: We also need to do this if unaligned, but we don't know the
469 if (DL.getTypeStoreSize(Ty) < 4)
470 return isLegalMUBUFAddressingMode(AM);
472 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
473 // SMRD instructions have an 8-bit, dword offset on SI.
474 if (!isUInt<8>(AM.BaseOffs / 4))
476 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
477 // On CI+, this can also be a 32-bit literal constant offset. If it fits
478 // in 8-bits, it can use a smaller encoding.
479 if (!isUInt<32>(AM.BaseOffs / 4))
481 } else if (Subtarget->getGeneration() == SISubtarget::VOLCANIC_ISLANDS) {
482 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
483 if (!isUInt<20>(AM.BaseOffs))
486 llvm_unreachable("unhandled generation");
488 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
491 if (AM.Scale == 1 && AM.HasBaseReg)
497 case AMDGPUAS::PRIVATE_ADDRESS:
498 return isLegalMUBUFAddressingMode(AM);
500 case AMDGPUAS::LOCAL_ADDRESS:
501 case AMDGPUAS::REGION_ADDRESS: {
502 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
504 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
505 // an 8-bit dword offset but we don't know the alignment here.
506 if (!isUInt<16>(AM.BaseOffs))
509 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
512 if (AM.Scale == 1 && AM.HasBaseReg)
517 case AMDGPUAS::FLAT_ADDRESS:
518 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
519 // For an unknown address space, this usually means that this is for some
520 // reason being used for pure arithmetic, and not based on some addressing
521 // computation. We don't have instructions that compute pointers with any
522 // addressing modes, so treat them as having no offset like flat
524 return isLegalFlatAddressingMode(AM);
527 llvm_unreachable("unhandled address space");
531 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
534 bool *IsFast) const {
538 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
539 // which isn't a simple VT.
540 // Until MVT is extended to handle this, simply check for the size and
541 // rely on the condition below: allow accesses if the size is a multiple of 4.
542 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
543 VT.getStoreSize() > 16)) {
547 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
548 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
549 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
550 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
551 // with adjacent offsets.
552 bool AlignedBy4 = (Align % 4 == 0);
554 *IsFast = AlignedBy4;
559 // FIXME: We have to be conservative here and assume that flat operations
560 // will access scratch. If we had access to the IR function, then we
561 // could determine if any private memory was used in the function.
562 if (!Subtarget->hasUnalignedScratchAccess() &&
563 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
564 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
568 if (Subtarget->hasUnalignedBufferAccess()) {
569 // If we have an uniform constant load, it still requires using a slow
570 // buffer instruction if unaligned.
572 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) ?
573 (Align % 4 == 0) : true;
579 // Smaller than dword value must be aligned.
580 if (VT.bitsLT(MVT::i32))
583 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
584 // byte-address are ignored, thus forcing Dword alignment.
585 // This applies to private, global, and constant memory.
589 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
592 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
593 unsigned SrcAlign, bool IsMemset,
596 MachineFunction &MF) const {
597 // FIXME: Should account for address space here.
599 // The default fallback uses the private pointer size as a guess for a type to
600 // use. Make sure we switch these to 64-bit accesses.
602 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
605 if (Size >= 8 && DstAlign >= 4)
612 static bool isFlatGlobalAddrSpace(unsigned AS) {
613 return AS == AMDGPUAS::GLOBAL_ADDRESS ||
614 AS == AMDGPUAS::FLAT_ADDRESS ||
615 AS == AMDGPUAS::CONSTANT_ADDRESS;
618 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
619 unsigned DestAS) const {
620 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
623 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
624 const MemSDNode *MemNode = cast<MemSDNode>(N);
625 const Value *Ptr = MemNode->getMemOperand()->getValue();
626 const Instruction *I = dyn_cast<Instruction>(Ptr);
627 return I && I->getMetadata("amdgpu.noclobber");
630 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
631 unsigned DestAS) const {
632 // Flat -> private/local is a simple truncate.
633 // Flat -> global is no-op
634 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
637 return isNoopAddrSpaceCast(SrcAS, DestAS);
640 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
641 const MemSDNode *MemNode = cast<MemSDNode>(N);
642 const Value *Ptr = MemNode->getMemOperand()->getValue();
644 // UndefValue means this is a load of a kernel input. These are uniform.
645 // Sometimes LDS instructions have constant pointers.
646 // If Ptr is null, then that means this mem operand contains a
647 // PseudoSourceValue like GOT.
648 if (!Ptr || isa<UndefValue>(Ptr) || isa<Argument>(Ptr) ||
649 isa<Constant>(Ptr) || isa<GlobalValue>(Ptr))
652 const Instruction *I = dyn_cast<Instruction>(Ptr);
653 return I && I->getMetadata("amdgpu.uniform");
656 TargetLoweringBase::LegalizeTypeAction
657 SITargetLowering::getPreferredVectorAction(EVT VT) const {
658 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
659 return TypeSplitVector;
661 return TargetLoweringBase::getPreferredVectorAction(VT);
664 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
666 // FIXME: Could be smarter if called for vector constants.
670 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
671 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
676 // These operations are done with 32-bit instructions anyway.
688 // SimplifySetCC uses this function to determine whether or not it should
689 // create setcc with i1 operands. We don't have instructions for i1 setcc.
690 if (VT == MVT::i1 && Op == ISD::SETCC)
693 return TargetLowering::isTypeDesirableForOp(Op, VT);
696 SDValue SITargetLowering::LowerParameterPtr(SelectionDAG &DAG,
697 const SDLoc &SL, SDValue Chain,
698 unsigned Offset) const {
699 const DataLayout &DL = DAG.getDataLayout();
700 MachineFunction &MF = DAG.getMachineFunction();
701 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
702 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
704 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
705 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
706 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
707 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
708 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
709 DAG.getConstant(Offset, SL, PtrVT));
712 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
713 const SDLoc &SL, SDValue Chain,
714 unsigned Offset, bool Signed,
715 const ISD::InputArg *Arg) const {
716 const DataLayout &DL = DAG.getDataLayout();
717 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
718 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
719 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
721 unsigned Align = DL.getABITypeAlignment(Ty);
723 SDValue Ptr = LowerParameterPtr(DAG, SL, Chain, Offset);
724 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
725 MachineMemOperand::MONonTemporal |
726 MachineMemOperand::MODereferenceable |
727 MachineMemOperand::MOInvariant);
730 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
732 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
733 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
736 if (MemVT.isFloatingPoint())
737 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
739 Val = DAG.getSExtOrTrunc(Val, SL, VT);
741 Val = DAG.getZExtOrTrunc(Val, SL, VT);
743 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
746 SDValue SITargetLowering::LowerFormalArguments(
747 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
748 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
749 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
750 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
752 MachineFunction &MF = DAG.getMachineFunction();
753 FunctionType *FType = MF.getFunction()->getFunctionType();
754 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
755 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
757 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
758 const Function *Fn = MF.getFunction();
759 DiagnosticInfoUnsupported NoGraphicsHSA(
760 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
761 DAG.getContext()->diagnose(NoGraphicsHSA);
762 return DAG.getEntryNode();
765 // Create stack objects that are used for emitting debugger prologue if
766 // "amdgpu-debugger-emit-prologue" attribute was specified.
767 if (ST.debuggerEmitPrologue())
768 createDebuggerPrologueStackObjects(MF);
770 SmallVector<ISD::InputArg, 16> Splits;
771 BitVector Skipped(Ins.size());
773 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
774 const ISD::InputArg &Arg = Ins[i];
776 // First check if it's a PS input addr
777 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
778 !Arg.Flags.isByVal() && PSInputNum <= 15) {
780 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
781 // We can safely skip PS inputs
787 Info->markPSInputAllocated(PSInputNum);
789 Info->PSInputEna |= 1 << PSInputNum;
794 if (AMDGPU::isShader(CallConv)) {
795 // Second split vertices into their elements
796 if (Arg.VT.isVector()) {
797 ISD::InputArg NewArg = Arg;
798 NewArg.Flags.setSplit();
799 NewArg.VT = Arg.VT.getVectorElementType();
801 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
802 // three or five element vertex only needs three or five registers,
803 // NOT four or eight.
804 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
805 unsigned NumElements = ParamType->getVectorNumElements();
807 for (unsigned j = 0; j != NumElements; ++j) {
808 Splits.push_back(NewArg);
809 NewArg.PartOffset += NewArg.VT.getStoreSize();
812 Splits.push_back(Arg);
817 SmallVector<CCValAssign, 16> ArgLocs;
818 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
821 // At least one interpolation mode must be enabled or else the GPU will hang.
823 // Check PSInputAddr instead of PSInputEna. The idea is that if the user set
824 // PSInputAddr, the user wants to enable some bits after the compilation
825 // based on run-time states. Since we can't know what the final PSInputEna
826 // will look like, so we shouldn't do anything here and the user should take
827 // responsibility for the correct programming.
829 // Otherwise, the following restrictions apply:
830 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
831 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
833 if (CallConv == CallingConv::AMDGPU_PS &&
834 ((Info->getPSInputAddr() & 0x7F) == 0 ||
835 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11)))) {
836 CCInfo.AllocateReg(AMDGPU::VGPR0);
837 CCInfo.AllocateReg(AMDGPU::VGPR1);
838 Info->markPSInputAllocated(0);
839 Info->PSInputEna |= 1;
842 if (!AMDGPU::isShader(CallConv)) {
843 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
845 assert(!Info->hasDispatchPtr() &&
846 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
847 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
848 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
849 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
850 !Info->hasWorkItemIDZ());
853 if (Info->hasPrivateMemoryInputPtr()) {
854 unsigned PrivateMemoryPtrReg = Info->addPrivateMemoryPtr(*TRI);
855 MF.addLiveIn(PrivateMemoryPtrReg, &AMDGPU::SReg_64RegClass);
856 CCInfo.AllocateReg(PrivateMemoryPtrReg);
859 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
860 if (Info->hasPrivateSegmentBuffer()) {
861 unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
862 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
863 CCInfo.AllocateReg(PrivateSegmentBufferReg);
866 if (Info->hasDispatchPtr()) {
867 unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
868 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
869 CCInfo.AllocateReg(DispatchPtrReg);
872 if (Info->hasQueuePtr()) {
873 unsigned QueuePtrReg = Info->addQueuePtr(*TRI);
874 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
875 CCInfo.AllocateReg(QueuePtrReg);
878 if (Info->hasKernargSegmentPtr()) {
879 unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
880 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
881 CCInfo.AllocateReg(InputPtrReg);
884 if (Info->hasDispatchID()) {
885 unsigned DispatchIDReg = Info->addDispatchID(*TRI);
886 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
887 CCInfo.AllocateReg(DispatchIDReg);
890 if (Info->hasFlatScratchInit()) {
891 unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI);
892 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
893 CCInfo.AllocateReg(FlatScratchInitReg);
896 if (!AMDGPU::isShader(CallConv))
897 analyzeFormalArgumentsCompute(CCInfo, Ins);
899 AnalyzeFormalArguments(CCInfo, Splits);
901 SmallVector<SDValue, 16> Chains;
903 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
905 const ISD::InputArg &Arg = Ins[i];
907 InVals.push_back(DAG.getUNDEF(Arg.VT));
911 CCValAssign &VA = ArgLocs[ArgIdx++];
912 MVT VT = VA.getLocVT();
916 EVT MemVT = VA.getLocVT();
917 const unsigned Offset = Subtarget->getExplicitKernelArgOffset(MF) +
918 VA.getLocMemOffset();
919 // The first 36 bytes of the input buffer contains information about
920 // thread group and global sizes.
921 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain,
922 Offset, Ins[i].Flags.isSExt(),
924 Chains.push_back(Arg.getValue(1));
927 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
928 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
929 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
930 // On SI local pointers are just offsets into LDS, so they are always
931 // less than 16-bits. On CI and newer they could potentially be
932 // real pointers, so we can't guarantee their size.
933 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
934 DAG.getValueType(MVT::i16));
937 InVals.push_back(Arg);
938 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
941 assert(VA.isRegLoc() && "Parameter must be in a register!");
943 unsigned Reg = VA.getLocReg();
945 if (VT == MVT::i64) {
946 // For now assume it is a pointer
947 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
948 &AMDGPU::SGPR_64RegClass);
949 Reg = MF.addLiveIn(Reg, &AMDGPU::SGPR_64RegClass);
950 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
951 InVals.push_back(Copy);
955 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
957 Reg = MF.addLiveIn(Reg, RC);
958 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
960 if (Arg.VT.isVector()) {
962 // Build a vector from the registers
963 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
964 unsigned NumElements = ParamType->getVectorNumElements();
966 SmallVector<SDValue, 4> Regs;
968 for (unsigned j = 1; j != NumElements; ++j) {
969 Reg = ArgLocs[ArgIdx++].getLocReg();
970 Reg = MF.addLiveIn(Reg, RC);
972 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
973 Regs.push_back(Copy);
976 // Fill up the missing vector elements
977 NumElements = Arg.VT.getVectorNumElements() - NumElements;
978 Regs.append(NumElements, DAG.getUNDEF(VT));
980 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
984 InVals.push_back(Val);
987 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
988 // these from the dispatch pointer.
990 // Start adding system SGPRs.
991 if (Info->hasWorkGroupIDX()) {
992 unsigned Reg = Info->addWorkGroupIDX();
993 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
994 CCInfo.AllocateReg(Reg);
997 if (Info->hasWorkGroupIDY()) {
998 unsigned Reg = Info->addWorkGroupIDY();
999 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1000 CCInfo.AllocateReg(Reg);
1003 if (Info->hasWorkGroupIDZ()) {
1004 unsigned Reg = Info->addWorkGroupIDZ();
1005 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1006 CCInfo.AllocateReg(Reg);
1009 if (Info->hasWorkGroupInfo()) {
1010 unsigned Reg = Info->addWorkGroupInfo();
1011 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1012 CCInfo.AllocateReg(Reg);
1015 if (Info->hasPrivateSegmentWaveByteOffset()) {
1016 // Scratch wave offset passed in system SGPR.
1017 unsigned PrivateSegmentWaveByteOffsetReg;
1019 if (AMDGPU::isShader(CallConv)) {
1020 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1021 Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1023 PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset();
1025 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1026 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1029 // Now that we've figured out where the scratch register inputs are, see if
1030 // should reserve the arguments and use them directly.
1031 bool HasStackObjects = MF.getFrameInfo().hasStackObjects();
1032 // Record that we know we have non-spill stack objects so we don't need to
1033 // check all stack objects later.
1034 if (HasStackObjects)
1035 Info->setHasNonSpillStackObjects(true);
1037 // Everything live out of a block is spilled with fast regalloc, so it's
1038 // almost certain that spilling will be required.
1039 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
1040 HasStackObjects = true;
1042 if (ST.isAmdCodeObjectV2(MF)) {
1043 if (HasStackObjects) {
1044 // If we have stack objects, we unquestionably need the private buffer
1045 // resource. For the Code Object V2 ABI, this will be the first 4 user
1046 // SGPR inputs. We can reserve those and use them directly.
1048 unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
1049 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1050 Info->setScratchRSrcReg(PrivateSegmentBufferReg);
1052 unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
1053 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1054 Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1056 unsigned ReservedBufferReg
1057 = TRI->reservedPrivateSegmentBufferReg(MF);
1058 unsigned ReservedOffsetReg
1059 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1061 // We tentatively reserve the last registers (skipping the last two
1062 // which may contain VCC). After register allocation, we'll replace
1063 // these with the ones immediately after those which were really
1064 // allocated. In the prologue copies will be inserted from the argument
1065 // to these reserved registers.
1066 Info->setScratchRSrcReg(ReservedBufferReg);
1067 Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1070 unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
1072 // Without HSA, relocations are used for the scratch pointer and the
1073 // buffer resource setup is always inserted in the prologue. Scratch wave
1074 // offset is still in an input SGPR.
1075 Info->setScratchRSrcReg(ReservedBufferReg);
1077 if (HasStackObjects) {
1078 unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
1079 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1080 Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1082 unsigned ReservedOffsetReg
1083 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1084 Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1088 if (Info->hasWorkItemIDX()) {
1089 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
1090 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1091 CCInfo.AllocateReg(Reg);
1094 if (Info->hasWorkItemIDY()) {
1095 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
1096 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1097 CCInfo.AllocateReg(Reg);
1100 if (Info->hasWorkItemIDZ()) {
1101 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
1102 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1103 CCInfo.AllocateReg(Reg);
1109 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1113 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1115 const SmallVectorImpl<ISD::OutputArg> &Outs,
1116 const SmallVectorImpl<SDValue> &OutVals,
1117 const SDLoc &DL, SelectionDAG &DAG) const {
1118 MachineFunction &MF = DAG.getMachineFunction();
1119 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1121 if (!AMDGPU::isShader(CallConv))
1122 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1125 Info->setIfReturnsVoid(Outs.size() == 0);
1127 SmallVector<ISD::OutputArg, 48> Splits;
1128 SmallVector<SDValue, 48> SplitVals;
1130 // Split vectors into their elements.
1131 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1132 const ISD::OutputArg &Out = Outs[i];
1134 if (Out.VT.isVector()) {
1135 MVT VT = Out.VT.getVectorElementType();
1136 ISD::OutputArg NewOut = Out;
1137 NewOut.Flags.setSplit();
1140 // We want the original number of vector elements here, e.g.
1141 // three or five, not four or eight.
1142 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1144 for (unsigned j = 0; j != NumElements; ++j) {
1145 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1146 DAG.getConstant(j, DL, MVT::i32));
1147 SplitVals.push_back(Elem);
1148 Splits.push_back(NewOut);
1149 NewOut.PartOffset += NewOut.VT.getStoreSize();
1152 SplitVals.push_back(OutVals[i]);
1153 Splits.push_back(Out);
1157 // CCValAssign - represent the assignment of the return value to a location.
1158 SmallVector<CCValAssign, 48> RVLocs;
1160 // CCState - Info about the registers and stack slots.
1161 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1164 // Analyze outgoing return values.
1165 AnalyzeReturn(CCInfo, Splits);
1168 SmallVector<SDValue, 48> RetOps;
1169 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1171 // Copy the result values into the output registers.
1172 for (unsigned i = 0, realRVLocIdx = 0;
1174 ++i, ++realRVLocIdx) {
1175 CCValAssign &VA = RVLocs[i];
1176 assert(VA.isRegLoc() && "Can only return in registers!");
1178 SDValue Arg = SplitVals[realRVLocIdx];
1180 // Copied from other backends.
1181 switch (VA.getLocInfo()) {
1182 default: llvm_unreachable("Unknown loc info!");
1183 case CCValAssign::Full:
1185 case CCValAssign::BCvt:
1186 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1190 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1191 Flag = Chain.getValue(1);
1192 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1195 // Update chain and glue.
1198 RetOps.push_back(Flag);
1200 unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN;
1201 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1204 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1205 SelectionDAG &DAG) const {
1206 unsigned Reg = StringSwitch<unsigned>(RegName)
1207 .Case("m0", AMDGPU::M0)
1208 .Case("exec", AMDGPU::EXEC)
1209 .Case("exec_lo", AMDGPU::EXEC_LO)
1210 .Case("exec_hi", AMDGPU::EXEC_HI)
1211 .Case("flat_scratch", AMDGPU::FLAT_SCR)
1212 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1213 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1214 .Default(AMDGPU::NoRegister);
1216 if (Reg == AMDGPU::NoRegister) {
1217 report_fatal_error(Twine("invalid register name \""
1218 + StringRef(RegName) + "\"."));
1222 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1223 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1224 report_fatal_error(Twine("invalid register \""
1225 + StringRef(RegName) + "\" for subtarget."));
1230 case AMDGPU::EXEC_LO:
1231 case AMDGPU::EXEC_HI:
1232 case AMDGPU::FLAT_SCR_LO:
1233 case AMDGPU::FLAT_SCR_HI:
1234 if (VT.getSizeInBits() == 32)
1238 case AMDGPU::FLAT_SCR:
1239 if (VT.getSizeInBits() == 64)
1243 llvm_unreachable("missing register type checking");
1246 report_fatal_error(Twine("invalid type for register \""
1247 + StringRef(RegName) + "\"."));
1250 // If kill is not the last instruction, split the block so kill is always a
1251 // proper terminator.
1252 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1253 MachineBasicBlock *BB) const {
1254 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1256 MachineBasicBlock::iterator SplitPoint(&MI);
1259 if (SplitPoint == BB->end()) {
1260 // Don't bother with a new block.
1261 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1265 MachineFunction *MF = BB->getParent();
1266 MachineBasicBlock *SplitBB
1267 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1269 MF->insert(++MachineFunction::iterator(BB), SplitBB);
1270 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1272 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1273 BB->addSuccessor(SplitBB);
1275 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1279 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1280 // wavefront. If the value is uniform and just happens to be in a VGPR, this
1281 // will only do one iteration. In the worst case, this will loop 64 times.
1283 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1284 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1285 const SIInstrInfo *TII,
1286 MachineRegisterInfo &MRI,
1287 MachineBasicBlock &OrigBB,
1288 MachineBasicBlock &LoopBB,
1290 const MachineOperand &IdxReg,
1294 unsigned InitSaveExecReg,
1296 bool UseGPRIdxMode) {
1297 MachineBasicBlock::iterator I = LoopBB.begin();
1299 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1300 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1301 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1302 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1304 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1310 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1311 .addReg(InitSaveExecReg)
1316 // Read the next variant <- also loop target.
1317 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1318 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1320 // Compare the just read M0 value to all possible Idx values.
1321 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1322 .addReg(CurrentIdxReg)
1323 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1325 if (UseGPRIdxMode) {
1328 IdxReg = CurrentIdxReg;
1330 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1331 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1332 .addReg(CurrentIdxReg, RegState::Kill)
1336 MachineInstr *SetIdx =
1337 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1338 .addReg(IdxReg, RegState::Kill);
1339 SetIdx->getOperand(2).setIsUndef();
1341 // Move index from VCC into M0
1343 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1344 .addReg(CurrentIdxReg, RegState::Kill);
1346 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1347 .addReg(CurrentIdxReg, RegState::Kill)
1352 // Update EXEC, save the original EXEC value to VCC.
1353 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1354 .addReg(CondReg, RegState::Kill);
1356 MRI.setSimpleHint(NewExec, CondReg);
1358 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1359 MachineInstr *InsertPt =
1360 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1361 .addReg(AMDGPU::EXEC)
1364 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1367 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1368 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1371 return InsertPt->getIterator();
1374 // This has slightly sub-optimal regalloc when the source vector is killed by
1375 // the read. The register allocator does not understand that the kill is
1376 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
1377 // subregister from it, using 1 more VGPR than necessary. This was saved when
1378 // this was expanded after register allocation.
1379 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1380 MachineBasicBlock &MBB,
1382 unsigned InitResultReg,
1385 bool UseGPRIdxMode) {
1386 MachineFunction *MF = MBB.getParent();
1387 MachineRegisterInfo &MRI = MF->getRegInfo();
1388 const DebugLoc &DL = MI.getDebugLoc();
1389 MachineBasicBlock::iterator I(&MI);
1391 unsigned DstReg = MI.getOperand(0).getReg();
1392 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1393 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1395 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1397 // Save the EXEC mask
1398 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1399 .addReg(AMDGPU::EXEC);
1401 // To insert the loop we need to split the block. Move everything after this
1402 // point to a new block, and insert a new empty block between the two.
1403 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1404 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1405 MachineFunction::iterator MBBI(MBB);
1408 MF->insert(MBBI, LoopBB);
1409 MF->insert(MBBI, RemainderBB);
1411 LoopBB->addSuccessor(LoopBB);
1412 LoopBB->addSuccessor(RemainderBB);
1414 // Move the rest of the block into a new block.
1415 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1416 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1418 MBB.addSuccessor(LoopBB);
1420 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1422 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1423 InitResultReg, DstReg, PhiReg, TmpExec,
1424 Offset, UseGPRIdxMode);
1426 MachineBasicBlock::iterator First = RemainderBB->begin();
1427 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1433 // Returns subreg index, offset
1434 static std::pair<unsigned, int>
1435 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1436 const TargetRegisterClass *SuperRC,
1439 int NumElts = SuperRC->getSize() / 4;
1441 // Skip out of bounds offsets, or else we would end up using an undefined
1443 if (Offset >= NumElts || Offset < 0)
1444 return std::make_pair(AMDGPU::sub0, Offset);
1446 return std::make_pair(AMDGPU::sub0 + Offset, 0);
1449 // Return true if the index is an SGPR and was set.
1450 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1451 MachineRegisterInfo &MRI,
1455 bool IsIndirectSrc) {
1456 MachineBasicBlock *MBB = MI.getParent();
1457 const DebugLoc &DL = MI.getDebugLoc();
1458 MachineBasicBlock::iterator I(&MI);
1460 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1461 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1463 assert(Idx->getReg() != AMDGPU::NoRegister);
1465 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1468 if (UseGPRIdxMode) {
1469 unsigned IdxMode = IsIndirectSrc ?
1470 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1472 MachineInstr *SetOn =
1473 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1477 SetOn->getOperand(3).setIsUndef();
1479 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1480 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1483 MachineInstr *SetOn =
1484 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1485 .addReg(Tmp, RegState::Kill)
1488 SetOn->getOperand(3).setIsUndef();
1495 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1498 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1506 // Control flow needs to be inserted if indexing with a VGPR.
1507 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1508 MachineBasicBlock &MBB,
1509 const SISubtarget &ST) {
1510 const SIInstrInfo *TII = ST.getInstrInfo();
1511 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1512 MachineFunction *MF = MBB.getParent();
1513 MachineRegisterInfo &MRI = MF->getRegInfo();
1515 unsigned Dst = MI.getOperand(0).getReg();
1516 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1517 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1519 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1522 std::tie(SubReg, Offset)
1523 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1525 bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode;
1527 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1528 MachineBasicBlock::iterator I(&MI);
1529 const DebugLoc &DL = MI.getDebugLoc();
1531 if (UseGPRIdxMode) {
1532 // TODO: Look at the uses to avoid the copy. This may require rescheduling
1533 // to avoid interfering with other uses, so probably requires a new
1534 // optimization pass.
1535 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1536 .addReg(SrcReg, RegState::Undef, SubReg)
1537 .addReg(SrcReg, RegState::Implicit)
1538 .addReg(AMDGPU::M0, RegState::Implicit);
1539 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1541 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1542 .addReg(SrcReg, RegState::Undef, SubReg)
1543 .addReg(SrcReg, RegState::Implicit);
1546 MI.eraseFromParent();
1552 const DebugLoc &DL = MI.getDebugLoc();
1553 MachineBasicBlock::iterator I(&MI);
1555 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1556 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1558 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1560 if (UseGPRIdxMode) {
1561 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1562 .addImm(0) // Reset inside loop.
1563 .addImm(VGPRIndexMode::SRC0_ENABLE);
1564 SetOn->getOperand(3).setIsUndef();
1566 // Disable again after the loop.
1567 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1570 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1571 MachineBasicBlock *LoopBB = InsPt->getParent();
1573 if (UseGPRIdxMode) {
1574 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1575 .addReg(SrcReg, RegState::Undef, SubReg)
1576 .addReg(SrcReg, RegState::Implicit)
1577 .addReg(AMDGPU::M0, RegState::Implicit);
1579 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1580 .addReg(SrcReg, RegState::Undef, SubReg)
1581 .addReg(SrcReg, RegState::Implicit);
1584 MI.eraseFromParent();
1589 static unsigned getMOVRELDPseudo(const TargetRegisterClass *VecRC) {
1590 switch (VecRC->getSize()) {
1592 return AMDGPU::V_MOVRELD_B32_V1;
1594 return AMDGPU::V_MOVRELD_B32_V2;
1596 return AMDGPU::V_MOVRELD_B32_V4;
1598 return AMDGPU::V_MOVRELD_B32_V8;
1600 return AMDGPU::V_MOVRELD_B32_V16;
1602 llvm_unreachable("unsupported size for MOVRELD pseudos");
1606 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1607 MachineBasicBlock &MBB,
1608 const SISubtarget &ST) {
1609 const SIInstrInfo *TII = ST.getInstrInfo();
1610 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1611 MachineFunction *MF = MBB.getParent();
1612 MachineRegisterInfo &MRI = MF->getRegInfo();
1614 unsigned Dst = MI.getOperand(0).getReg();
1615 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1616 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1617 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1618 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1619 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1621 // This can be an immediate, but will be folded later.
1622 assert(Val->getReg());
1625 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1628 bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode;
1630 if (Idx->getReg() == AMDGPU::NoRegister) {
1631 MachineBasicBlock::iterator I(&MI);
1632 const DebugLoc &DL = MI.getDebugLoc();
1634 assert(Offset == 0);
1636 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1637 .addOperand(*SrcVec)
1641 MI.eraseFromParent();
1645 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1646 MachineBasicBlock::iterator I(&MI);
1647 const DebugLoc &DL = MI.getDebugLoc();
1649 if (UseGPRIdxMode) {
1650 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1651 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
1653 .addReg(Dst, RegState::ImplicitDefine)
1654 .addReg(SrcVec->getReg(), RegState::Implicit)
1655 .addReg(AMDGPU::M0, RegState::Implicit);
1657 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1659 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1661 BuildMI(MBB, I, DL, MovRelDesc)
1662 .addReg(Dst, RegState::Define)
1663 .addReg(SrcVec->getReg())
1665 .addImm(SubReg - AMDGPU::sub0);
1668 MI.eraseFromParent();
1673 MRI.clearKillFlags(Val->getReg());
1675 const DebugLoc &DL = MI.getDebugLoc();
1677 if (UseGPRIdxMode) {
1678 MachineBasicBlock::iterator I(&MI);
1680 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1681 .addImm(0) // Reset inside loop.
1682 .addImm(VGPRIndexMode::DST_ENABLE);
1683 SetOn->getOperand(3).setIsUndef();
1685 // Disable again after the loop.
1686 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1689 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
1691 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
1692 Offset, UseGPRIdxMode);
1693 MachineBasicBlock *LoopBB = InsPt->getParent();
1695 if (UseGPRIdxMode) {
1696 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1697 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
1698 .addOperand(*Val) // src0
1699 .addReg(Dst, RegState::ImplicitDefine)
1700 .addReg(PhiReg, RegState::Implicit)
1701 .addReg(AMDGPU::M0, RegState::Implicit);
1703 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1705 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
1706 .addReg(Dst, RegState::Define)
1709 .addImm(SubReg - AMDGPU::sub0);
1712 MI.eraseFromParent();
1717 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1718 MachineInstr &MI, MachineBasicBlock *BB) const {
1720 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1721 MachineFunction *MF = BB->getParent();
1722 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1724 if (TII->isMIMG(MI)) {
1725 if (!MI.memoperands_empty())
1727 // Add a memoperand for mimg instructions so that they aren't assumed to
1728 // be ordered memory instuctions.
1730 MachinePointerInfo PtrInfo(MFI->getImagePSV());
1731 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
1733 Flags |= MachineMemOperand::MOStore;
1736 Flags |= MachineMemOperand::MOLoad;
1738 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
1739 MI.addMemOperand(*MF, MMO);
1743 switch (MI.getOpcode()) {
1744 case AMDGPU::SI_INIT_M0: {
1745 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
1746 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1747 .addOperand(MI.getOperand(0));
1748 MI.eraseFromParent();
1751 case AMDGPU::GET_GROUPSTATICSIZE: {
1752 DebugLoc DL = MI.getDebugLoc();
1753 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
1754 .addOperand(MI.getOperand(0))
1755 .addImm(MFI->getLDSSize());
1756 MI.eraseFromParent();
1759 case AMDGPU::SI_INDIRECT_SRC_V1:
1760 case AMDGPU::SI_INDIRECT_SRC_V2:
1761 case AMDGPU::SI_INDIRECT_SRC_V4:
1762 case AMDGPU::SI_INDIRECT_SRC_V8:
1763 case AMDGPU::SI_INDIRECT_SRC_V16:
1764 return emitIndirectSrc(MI, *BB, *getSubtarget());
1765 case AMDGPU::SI_INDIRECT_DST_V1:
1766 case AMDGPU::SI_INDIRECT_DST_V2:
1767 case AMDGPU::SI_INDIRECT_DST_V4:
1768 case AMDGPU::SI_INDIRECT_DST_V8:
1769 case AMDGPU::SI_INDIRECT_DST_V16:
1770 return emitIndirectDst(MI, *BB, *getSubtarget());
1771 case AMDGPU::SI_KILL:
1772 return splitKillBlock(MI, BB);
1773 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
1774 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
1776 unsigned Dst = MI.getOperand(0).getReg();
1777 unsigned Src0 = MI.getOperand(1).getReg();
1778 unsigned Src1 = MI.getOperand(2).getReg();
1779 const DebugLoc &DL = MI.getDebugLoc();
1780 unsigned SrcCond = MI.getOperand(3).getReg();
1782 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1783 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1785 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
1786 .addReg(Src0, 0, AMDGPU::sub0)
1787 .addReg(Src1, 0, AMDGPU::sub0)
1789 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
1790 .addReg(Src0, 0, AMDGPU::sub1)
1791 .addReg(Src1, 0, AMDGPU::sub1)
1794 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
1796 .addImm(AMDGPU::sub0)
1798 .addImm(AMDGPU::sub1);
1799 MI.eraseFromParent();
1802 case AMDGPU::SI_BR_UNDEF: {
1803 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1804 const DebugLoc &DL = MI.getDebugLoc();
1805 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
1806 .addOperand(MI.getOperand(0));
1807 Br->getOperand(1).setIsUndef(true); // read undef SCC
1808 MI.eraseFromParent();
1812 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
1816 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1817 // This currently forces unfolding various combinations of fsub into fma with
1818 // free fneg'd operands. As long as we have fast FMA (controlled by
1819 // isFMAFasterThanFMulAndFAdd), we should perform these.
1821 // When fma is quarter rate, for f64 where add / sub are at best half rate,
1822 // most of these combines appear to be cycle neutral but save on instruction
1823 // count / code size.
1827 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
1829 if (!VT.isVector()) {
1832 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
1835 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
1836 // TODO: Should i16 be used always if legal? For now it would force VALU
1838 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
1841 // Answering this is somewhat tricky and depends on the specific device which
1842 // have different rates for fma or all f64 operations.
1844 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
1845 // regardless of which device (although the number of cycles differs between
1846 // devices), so it is always profitable for f64.
1848 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
1849 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
1850 // which we can always do even without fused FP ops since it returns the same
1851 // result as the separate operations and since it is always full
1852 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
1853 // however does not support denormals, so we do report fma as faster if we have
1854 // a fast fma device and require denormals.
1856 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
1857 VT = VT.getScalarType();
1862 switch (VT.getSimpleVT().SimpleTy) {
1864 // This is as fast on some subtargets. However, we always have full rate f32
1865 // mad available which returns the same result as the separate operations
1866 // which we should prefer over fma. We can't use this if we want to support
1867 // denormals, so only report this in these cases.
1868 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
1872 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
1880 //===----------------------------------------------------------------------===//
1881 // Custom DAG Lowering Operations
1882 //===----------------------------------------------------------------------===//
1884 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1885 switch (Op.getOpcode()) {
1886 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1887 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1889 SDValue Result = LowerLOAD(Op, DAG);
1890 assert((!Result.getNode() ||
1891 Result.getNode()->getNumValues() == 2) &&
1892 "Load should return a value and a chain");
1898 return LowerTrig(Op, DAG);
1899 case ISD::SELECT: return LowerSELECT(Op, DAG);
1900 case ISD::FDIV: return LowerFDIV(Op, DAG);
1901 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
1902 case ISD::STORE: return LowerSTORE(Op, DAG);
1903 case ISD::GlobalAddress: {
1904 MachineFunction &MF = DAG.getMachineFunction();
1905 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1906 return LowerGlobalAddress(MFI, Op, DAG);
1908 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1909 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1910 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
1911 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
1912 case ISD::TRAP: return lowerTRAP(Op, DAG);
1914 return lowerFP_ROUND(Op, DAG);
1919 /// \brief Helper function for LowerBRCOND
1920 static SDNode *findUser(SDValue Value, unsigned Opcode) {
1922 SDNode *Parent = Value.getNode();
1923 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
1926 if (I.getUse().get() != Value)
1929 if (I->getOpcode() == Opcode)
1935 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
1936 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
1937 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
1938 case AMDGPUIntrinsic::amdgcn_if:
1939 case AMDGPUIntrinsic::amdgcn_else:
1940 case AMDGPUIntrinsic::amdgcn_end_cf:
1941 case AMDGPUIntrinsic::amdgcn_loop:
1948 if (Intr->getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
1949 switch (cast<ConstantSDNode>(Intr->getOperand(0))->getZExtValue()) {
1950 case AMDGPUIntrinsic::amdgcn_break:
1951 case AMDGPUIntrinsic::amdgcn_if_break:
1952 case AMDGPUIntrinsic::amdgcn_else_break:
1962 void SITargetLowering::createDebuggerPrologueStackObjects(
1963 MachineFunction &MF) const {
1964 // Create stack objects that are used for emitting debugger prologue.
1966 // Debugger prologue writes work group IDs and work item IDs to scratch memory
1967 // at fixed location in the following format:
1968 // offset 0: work group ID x
1969 // offset 4: work group ID y
1970 // offset 8: work group ID z
1971 // offset 16: work item ID x
1972 // offset 20: work item ID y
1973 // offset 24: work item ID z
1974 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1977 // For each dimension:
1978 for (unsigned i = 0; i < 3; ++i) {
1979 // Create fixed stack object for work group ID.
1980 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
1981 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
1982 // Create fixed stack object for work item ID.
1983 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
1984 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
1988 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
1989 const Triple &TT = getTargetMachine().getTargetTriple();
1990 return GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
1991 AMDGPU::shouldEmitConstantsToTextSection(TT);
1994 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
1995 return (GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
1996 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
1997 !shouldEmitFixup(GV) &&
1998 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2001 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2002 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2005 /// This transforms the control flow intrinsics to get the branch destination as
2006 /// last parameter, also switches branch target with BR if the need arise
2007 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2008 SelectionDAG &DAG) const {
2012 SDNode *Intr = BRCOND.getOperand(1).getNode();
2013 SDValue Target = BRCOND.getOperand(2);
2014 SDNode *BR = nullptr;
2015 SDNode *SetCC = nullptr;
2017 if (Intr->getOpcode() == ISD::SETCC) {
2018 // As long as we negate the condition everything is fine
2020 Intr = SetCC->getOperand(0).getNode();
2023 // Get the target from BR if we don't negate the condition
2024 BR = findUser(BRCOND, ISD::BR);
2025 Target = BR->getOperand(1);
2028 // FIXME: This changes the types of the intrinsics instead of introducing new
2029 // nodes with the correct types.
2030 // e.g. llvm.amdgcn.loop
2032 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2033 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2035 if (!isCFIntrinsic(Intr)) {
2036 // This is a uniform branch so we don't need to legalize.
2040 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2041 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2044 (SetCC->getConstantOperandVal(1) == 1 &&
2045 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
2048 // operands of the new intrinsic call
2049 SmallVector<SDValue, 4> Ops;
2051 Ops.push_back(BRCOND.getOperand(0));
2053 Ops.append(Intr->op_begin() + (HaveChain ? 1 : 0), Intr->op_end());
2054 Ops.push_back(Target);
2056 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2058 // build the new intrinsic call
2059 SDNode *Result = DAG.getNode(
2060 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
2061 DAG.getVTList(Res), Ops).getNode();
2066 BRCOND.getOperand(0)
2069 Result = DAG.getMergeValues(Ops, DL).getNode();
2073 // Give the branch instruction our target
2076 BRCOND.getOperand(2)
2078 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2079 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2080 BR = NewBR.getNode();
2083 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2085 // Copy the intrinsic results to registers
2086 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2087 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2091 Chain = DAG.getCopyToReg(
2093 CopyToReg->getOperand(1),
2094 SDValue(Result, i - 1),
2097 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2100 // Remove the old intrinsic from the chain
2101 DAG.ReplaceAllUsesOfValueWith(
2102 SDValue(Intr, Intr->getNumValues() - 1),
2103 Intr->getOperand(0));
2108 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2112 return Op.getValueType().bitsLE(VT) ?
2113 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2114 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2117 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2118 assert(Op.getValueType() == MVT::f16 &&
2119 "Do not know how to custom lower FP_ROUND for non-f16 type");
2121 SDValue Src = Op.getOperand(0);
2122 EVT SrcVT = Src.getValueType();
2123 if (SrcVT != MVT::f64)
2128 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2129 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2130 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2133 SDValue SITargetLowering::getSegmentAperture(unsigned AS,
2134 SelectionDAG &DAG) const {
2136 MachineFunction &MF = DAG.getMachineFunction();
2137 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2138 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2139 assert(UserSGPR != AMDGPU::NoRegister);
2141 SDValue QueuePtr = CreateLiveInRegister(
2142 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2144 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2145 // private_segment_aperture_base_hi.
2146 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
2148 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr,
2149 DAG.getConstant(StructOffset, SL, MVT::i64));
2151 // TODO: Use custom target PseudoSourceValue.
2152 // TODO: We should use the value from the IR intrinsic call, but it might not
2153 // be available and how do we get it?
2154 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2155 AMDGPUAS::CONSTANT_ADDRESS));
2157 MachinePointerInfo PtrInfo(V, StructOffset);
2158 return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, PtrInfo,
2159 MinAlign(64, StructOffset),
2160 MachineMemOperand::MODereferenceable |
2161 MachineMemOperand::MOInvariant);
2164 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2165 SelectionDAG &DAG) const {
2167 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2169 SDValue Src = ASC->getOperand(0);
2171 // FIXME: Really support non-0 null pointers.
2172 SDValue SegmentNullPtr = DAG.getConstant(-1, SL, MVT::i32);
2173 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2175 // flat -> local/private
2176 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2177 if (ASC->getDestAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2178 ASC->getDestAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
2179 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2180 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2182 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2183 NonNull, Ptr, SegmentNullPtr);
2187 // local/private -> flat
2188 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2189 if (ASC->getSrcAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2190 ASC->getSrcAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
2192 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2194 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG);
2196 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2198 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2199 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2204 // global <-> flat are no-ops and never emitted.
2206 const MachineFunction &MF = DAG.getMachineFunction();
2207 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2208 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2209 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2211 return DAG.getUNDEF(ASC->getValueType(0));
2215 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2216 // We can fold offsets for anything that doesn't require a GOT relocation.
2217 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
2218 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
2219 !shouldEmitGOTReloc(GA->getGlobal());
2222 static SDValue buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2223 SDLoc DL, unsigned Offset, EVT PtrVT,
2224 unsigned GAFlags = SIInstrInfo::MO_NONE) {
2225 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2226 // lowered to the following code sequence:
2228 // For constant address space:
2229 // s_getpc_b64 s[0:1]
2230 // s_add_u32 s0, s0, $symbol
2231 // s_addc_u32 s1, s1, 0
2233 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2234 // a fixup or relocation is emitted to replace $symbol with a literal
2235 // constant, which is a pc-relative offset from the encoding of the $symbol
2236 // operand to the global variable.
2238 // For global address space:
2239 // s_getpc_b64 s[0:1]
2240 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2241 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2243 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2244 // fixups or relocations are emitted to replace $symbol@*@lo and
2245 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2246 // which is a 64-bit pc-relative offset from the encoding of the $symbol
2247 // operand to the global variable.
2249 // What we want here is an offset from the value returned by s_getpc
2250 // (which is the address of the s_add_u32 instruction) to the global
2251 // variable, but since the encoding of $symbol starts 4 bytes after the start
2252 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2253 // small. This requires us to add 4 to the global variable offset in order to
2254 // compute the correct address.
2255 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2257 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2258 GAFlags == SIInstrInfo::MO_NONE ?
2259 GAFlags : GAFlags + 1);
2260 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2263 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2265 SelectionDAG &DAG) const {
2266 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2268 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS &&
2269 GSD->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS)
2270 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2273 const GlobalValue *GV = GSD->getGlobal();
2274 EVT PtrVT = Op.getValueType();
2276 if (shouldEmitFixup(GV))
2277 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2278 else if (shouldEmitPCReloc(GV))
2279 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2280 SIInstrInfo::MO_REL32);
2282 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2283 SIInstrInfo::MO_GOTPCREL32);
2285 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2286 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
2287 const DataLayout &DataLayout = DAG.getDataLayout();
2288 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2289 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2290 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2292 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2293 MachineMemOperand::MODereferenceable |
2294 MachineMemOperand::MOInvariant);
2297 SDValue SITargetLowering::lowerTRAP(SDValue Op,
2298 SelectionDAG &DAG) const {
2299 const MachineFunction &MF = DAG.getMachineFunction();
2300 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(),
2301 "trap handler not supported",
2304 DAG.getContext()->diagnose(NoTrap);
2308 // FIXME: This should really be selected to s_trap, but that requires
2309 // setting up the trap handler for it o do anything.
2310 return DAG.getNode(AMDGPUISD::ENDPGM, SDLoc(Op), MVT::Other,
2314 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2315 const SDLoc &DL, SDValue V) const {
2316 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2317 // the destination register.
2319 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2320 // so we will end up with redundant moves to m0.
2322 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2324 // A Null SDValue creates a glue result.
2325 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2327 return SDValue(M0, 0);
2330 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2333 unsigned Offset) const {
2335 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
2336 DAG.getEntryNode(), Offset, false);
2337 // The local size values will have the hi 16-bits as zero.
2338 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2339 DAG.getValueType(VT));
2342 static SDValue emitNonHSAIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) {
2343 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2344 "non-hsa intrinsic with hsa target",
2346 DAG.getContext()->diagnose(BadIntrin);
2347 return DAG.getUNDEF(VT);
2350 static SDValue emitRemovedIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) {
2351 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2352 "intrinsic not supported on subtarget",
2354 DAG.getContext()->diagnose(BadIntrin);
2355 return DAG.getUNDEF(VT);
2358 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2359 SelectionDAG &DAG) const {
2360 MachineFunction &MF = DAG.getMachineFunction();
2361 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2362 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2364 EVT VT = Op.getValueType();
2366 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2368 // TODO: Should this propagate fast-math-flags?
2370 switch (IntrinsicID) {
2371 case Intrinsic::amdgcn_implicit_buffer_ptr: {
2372 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2373 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2375 case Intrinsic::amdgcn_dispatch_ptr:
2376 case Intrinsic::amdgcn_queue_ptr: {
2377 if (!Subtarget->isAmdCodeObjectV2(MF)) {
2378 DiagnosticInfoUnsupported BadIntrin(
2379 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2381 DAG.getContext()->diagnose(BadIntrin);
2382 return DAG.getUNDEF(VT);
2385 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2386 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2387 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2388 TRI->getPreloadedValue(MF, Reg), VT);
2390 case Intrinsic::amdgcn_implicitarg_ptr: {
2391 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2392 return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2394 case Intrinsic::amdgcn_kernarg_segment_ptr: {
2396 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2397 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2399 case Intrinsic::amdgcn_dispatch_id: {
2400 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2401 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2403 case Intrinsic::amdgcn_rcp:
2404 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2405 case Intrinsic::amdgcn_rsq:
2406 case AMDGPUIntrinsic::AMDGPU_rsq: // Legacy name
2407 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2408 case Intrinsic::amdgcn_rsq_legacy: {
2409 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2410 return emitRemovedIntrinsicError(DAG, DL, VT);
2412 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2414 case Intrinsic::amdgcn_rcp_legacy: {
2415 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2416 return emitRemovedIntrinsicError(DAG, DL, VT);
2417 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2419 case Intrinsic::amdgcn_rsq_clamp: {
2420 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2421 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2423 Type *Type = VT.getTypeForEVT(*DAG.getContext());
2424 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2425 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2427 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2428 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2429 DAG.getConstantFP(Max, DL, VT));
2430 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2431 DAG.getConstantFP(Min, DL, VT));
2433 case Intrinsic::r600_read_ngroups_x:
2434 if (Subtarget->isAmdHsaOS())
2435 return emitNonHSAIntrinsicError(DAG, DL, VT);
2437 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2438 SI::KernelInputOffsets::NGROUPS_X, false);
2439 case Intrinsic::r600_read_ngroups_y:
2440 if (Subtarget->isAmdHsaOS())
2441 return emitNonHSAIntrinsicError(DAG, DL, VT);
2443 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2444 SI::KernelInputOffsets::NGROUPS_Y, false);
2445 case Intrinsic::r600_read_ngroups_z:
2446 if (Subtarget->isAmdHsaOS())
2447 return emitNonHSAIntrinsicError(DAG, DL, VT);
2449 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2450 SI::KernelInputOffsets::NGROUPS_Z, false);
2451 case Intrinsic::r600_read_global_size_x:
2452 if (Subtarget->isAmdHsaOS())
2453 return emitNonHSAIntrinsicError(DAG, DL, VT);
2455 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2456 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2457 case Intrinsic::r600_read_global_size_y:
2458 if (Subtarget->isAmdHsaOS())
2459 return emitNonHSAIntrinsicError(DAG, DL, VT);
2461 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2462 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2463 case Intrinsic::r600_read_global_size_z:
2464 if (Subtarget->isAmdHsaOS())
2465 return emitNonHSAIntrinsicError(DAG, DL, VT);
2467 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2468 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2469 case Intrinsic::r600_read_local_size_x:
2470 if (Subtarget->isAmdHsaOS())
2471 return emitNonHSAIntrinsicError(DAG, DL, VT);
2473 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2474 SI::KernelInputOffsets::LOCAL_SIZE_X);
2475 case Intrinsic::r600_read_local_size_y:
2476 if (Subtarget->isAmdHsaOS())
2477 return emitNonHSAIntrinsicError(DAG, DL, VT);
2479 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2480 SI::KernelInputOffsets::LOCAL_SIZE_Y);
2481 case Intrinsic::r600_read_local_size_z:
2482 if (Subtarget->isAmdHsaOS())
2483 return emitNonHSAIntrinsicError(DAG, DL, VT);
2485 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2486 SI::KernelInputOffsets::LOCAL_SIZE_Z);
2487 case Intrinsic::amdgcn_workgroup_id_x:
2488 case Intrinsic::r600_read_tgid_x:
2489 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2490 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2491 case Intrinsic::amdgcn_workgroup_id_y:
2492 case Intrinsic::r600_read_tgid_y:
2493 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2494 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2495 case Intrinsic::amdgcn_workgroup_id_z:
2496 case Intrinsic::r600_read_tgid_z:
2497 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2498 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2499 case Intrinsic::amdgcn_workitem_id_x:
2500 case Intrinsic::r600_read_tidig_x:
2501 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2502 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2503 case Intrinsic::amdgcn_workitem_id_y:
2504 case Intrinsic::r600_read_tidig_y:
2505 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2506 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2507 case Intrinsic::amdgcn_workitem_id_z:
2508 case Intrinsic::r600_read_tidig_z:
2509 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2510 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2511 case AMDGPUIntrinsic::SI_load_const: {
2517 MachineMemOperand *MMO = MF.getMachineMemOperand(
2518 MachinePointerInfo(),
2519 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2520 MachineMemOperand::MOInvariant,
2521 VT.getStoreSize(), 4);
2522 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2523 Op->getVTList(), Ops, VT, MMO);
2525 case AMDGPUIntrinsic::amdgcn_fdiv_fast: {
2526 return lowerFDIV_FAST(Op, DAG);
2528 case AMDGPUIntrinsic::SI_vs_load_input:
2529 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
2534 case AMDGPUIntrinsic::SI_fs_constant: {
2535 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
2536 SDValue Glue = M0.getValue(1);
2537 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
2538 DAG.getConstant(2, DL, MVT::i32), // P0
2539 Op.getOperand(1), Op.getOperand(2), Glue);
2541 case AMDGPUIntrinsic::SI_packf16:
2542 if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
2543 return DAG.getUNDEF(MVT::i32);
2545 case AMDGPUIntrinsic::SI_fs_interp: {
2546 SDValue IJ = Op.getOperand(4);
2547 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
2548 DAG.getConstant(0, DL, MVT::i32));
2549 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
2550 DAG.getConstant(1, DL, MVT::i32));
2551 I = DAG.getNode(ISD::BITCAST, DL, MVT::f32, I);
2552 J = DAG.getNode(ISD::BITCAST, DL, MVT::f32, J);
2553 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
2554 SDValue Glue = M0.getValue(1);
2555 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
2556 DAG.getVTList(MVT::f32, MVT::Glue),
2557 I, Op.getOperand(1), Op.getOperand(2), Glue);
2558 Glue = SDValue(P1.getNode(), 1);
2559 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
2560 Op.getOperand(1), Op.getOperand(2), Glue);
2562 case Intrinsic::amdgcn_interp_mov: {
2563 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2564 SDValue Glue = M0.getValue(1);
2565 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
2566 Op.getOperand(2), Op.getOperand(3), Glue);
2568 case Intrinsic::amdgcn_interp_p1: {
2569 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2570 SDValue Glue = M0.getValue(1);
2571 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2572 Op.getOperand(2), Op.getOperand(3), Glue);
2574 case Intrinsic::amdgcn_interp_p2: {
2575 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2576 SDValue Glue = SDValue(M0.getNode(), 1);
2577 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2578 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2581 case Intrinsic::amdgcn_sin:
2582 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
2584 case Intrinsic::amdgcn_cos:
2585 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
2587 case Intrinsic::amdgcn_log_clamp: {
2588 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2591 DiagnosticInfoUnsupported BadIntrin(
2592 *MF.getFunction(), "intrinsic not supported on subtarget",
2594 DAG.getContext()->diagnose(BadIntrin);
2595 return DAG.getUNDEF(VT);
2597 case Intrinsic::amdgcn_ldexp:
2598 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
2599 Op.getOperand(1), Op.getOperand(2));
2601 case Intrinsic::amdgcn_fract:
2602 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
2604 case Intrinsic::amdgcn_class:
2605 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
2606 Op.getOperand(1), Op.getOperand(2));
2607 case Intrinsic::amdgcn_div_fmas:
2608 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
2609 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
2612 case Intrinsic::amdgcn_div_fixup:
2613 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
2614 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2616 case Intrinsic::amdgcn_trig_preop:
2617 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
2618 Op.getOperand(1), Op.getOperand(2));
2619 case Intrinsic::amdgcn_div_scale: {
2620 // 3rd parameter required to be a constant.
2621 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2623 return DAG.getUNDEF(VT);
2625 // Translate to the operands expected by the machine instruction. The
2626 // first parameter must be the same as the first instruction.
2627 SDValue Numerator = Op.getOperand(1);
2628 SDValue Denominator = Op.getOperand(2);
2630 // Note this order is opposite of the machine instruction's operations,
2631 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
2632 // intrinsic has the numerator as the first operand to match a normal
2633 // division operation.
2635 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
2637 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
2638 Denominator, Numerator);
2640 case Intrinsic::amdgcn_icmp: {
2641 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2642 int CondCode = CD->getSExtValue();
2644 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
2645 CondCode >= ICmpInst::Predicate::BAD_ICMP_PREDICATE)
2646 return DAG.getUNDEF(VT);
2648 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
2649 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
2650 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2651 Op.getOperand(2), DAG.getCondCode(CCOpcode));
2653 case Intrinsic::amdgcn_fcmp: {
2654 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2655 int CondCode = CD->getSExtValue();
2657 if (CondCode <= FCmpInst::Predicate::FCMP_FALSE ||
2658 CondCode >= FCmpInst::Predicate::FCMP_TRUE)
2659 return DAG.getUNDEF(VT);
2661 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
2662 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
2663 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2664 Op.getOperand(2), DAG.getCondCode(CCOpcode));
2666 case Intrinsic::amdgcn_fmul_legacy:
2667 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
2668 Op.getOperand(1), Op.getOperand(2));
2669 case Intrinsic::amdgcn_sffbh:
2670 case AMDGPUIntrinsic::AMDGPU_flbit_i32: // Legacy name.
2671 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
2673 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2677 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2678 SelectionDAG &DAG) const {
2679 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2682 case Intrinsic::amdgcn_atomic_inc:
2683 case Intrinsic::amdgcn_atomic_dec: {
2684 MemSDNode *M = cast<MemSDNode>(Op);
2685 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
2686 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
2688 M->getOperand(0), // Chain
2689 M->getOperand(2), // Ptr
2690 M->getOperand(3) // Value
2693 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
2694 M->getMemoryVT(), M->getMemOperand());
2696 case Intrinsic::amdgcn_buffer_load:
2697 case Intrinsic::amdgcn_buffer_load_format: {
2699 Op.getOperand(0), // Chain
2700 Op.getOperand(2), // rsrc
2701 Op.getOperand(3), // vindex
2702 Op.getOperand(4), // offset
2703 Op.getOperand(5), // glc
2704 Op.getOperand(6) // slc
2706 MachineFunction &MF = DAG.getMachineFunction();
2707 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2709 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
2710 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
2711 EVT VT = Op.getValueType();
2712 EVT IntVT = VT.changeTypeToInteger();
2714 MachineMemOperand *MMO = MF.getMachineMemOperand(
2715 MachinePointerInfo(MFI->getBufferPSV()),
2716 MachineMemOperand::MOLoad,
2717 VT.getStoreSize(), VT.getStoreSize());
2719 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
2726 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
2727 SelectionDAG &DAG) const {
2728 MachineFunction &MF = DAG.getMachineFunction();
2730 SDValue Chain = Op.getOperand(0);
2731 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2733 switch (IntrinsicID) {
2734 case AMDGPUIntrinsic::SI_sendmsg:
2735 case Intrinsic::amdgcn_s_sendmsg: {
2736 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
2737 SDValue Glue = Chain.getValue(1);
2738 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
2739 Op.getOperand(2), Glue);
2741 case Intrinsic::amdgcn_s_sendmsghalt: {
2742 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
2743 SDValue Glue = Chain.getValue(1);
2744 return DAG.getNode(AMDGPUISD::SENDMSGHALT, DL, MVT::Other, Chain,
2745 Op.getOperand(2), Glue);
2747 case AMDGPUIntrinsic::SI_tbuffer_store: {
2765 EVT VT = Op.getOperand(3).getValueType();
2767 MachineMemOperand *MMO = MF.getMachineMemOperand(
2768 MachinePointerInfo(),
2769 MachineMemOperand::MOStore,
2770 VT.getStoreSize(), 4);
2771 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
2772 Op->getVTList(), Ops, VT, MMO);
2774 case AMDGPUIntrinsic::AMDGPU_kill: {
2775 SDValue Src = Op.getOperand(2);
2776 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
2777 if (!K->isNegative())
2780 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
2781 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
2784 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
2785 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
2787 case AMDGPUIntrinsic::SI_export: {
2788 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(2));
2789 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(3));
2790 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(4));
2791 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(5));
2792 const ConstantSDNode *Compr = cast<ConstantSDNode>(Op.getOperand(6));
2794 const SDValue Ops[] = {
2796 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),
2797 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1),
2798 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8),
2799 DAG.getTargetConstant(Compr->getZExtValue(), DL, MVT::i1),
2800 Op.getOperand(7), // src0
2801 Op.getOperand(8), // src1
2802 Op.getOperand(9), // src2
2803 Op.getOperand(10) // src3
2806 unsigned Opc = Done->isNullValue() ?
2807 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
2808 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
2815 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2817 LoadSDNode *Load = cast<LoadSDNode>(Op);
2818 ISD::LoadExtType ExtType = Load->getExtensionType();
2819 EVT MemVT = Load->getMemoryVT();
2821 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
2822 // FIXME: Copied from PPC
2823 // First, load into 32 bits, then truncate to 1 bit.
2825 SDValue Chain = Load->getChain();
2826 SDValue BasePtr = Load->getBasePtr();
2827 MachineMemOperand *MMO = Load->getMemOperand();
2829 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
2831 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
2832 BasePtr, RealMemVT, MMO);
2835 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
2839 return DAG.getMergeValues(Ops, DL);
2842 if (!MemVT.isVector())
2845 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
2846 "Custom lowering for non-i32 vectors hasn't been implemented.");
2848 unsigned AS = Load->getAddressSpace();
2849 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
2850 AS, Load->getAlignment())) {
2852 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
2853 return DAG.getMergeValues(Ops, DL);
2856 MachineFunction &MF = DAG.getMachineFunction();
2857 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2858 // If there is a possibilty that flat instruction access scratch memory
2859 // then we need to use the same legalization rules we use for private.
2860 if (AS == AMDGPUAS::FLAT_ADDRESS)
2861 AS = MFI->hasFlatScratchInit() ?
2862 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
2864 unsigned NumElements = MemVT.getVectorNumElements();
2866 case AMDGPUAS::CONSTANT_ADDRESS:
2867 if (isMemOpUniform(Load))
2869 // Non-uniform loads will be selected to MUBUF instructions, so they
2870 // have the same legalization requirements as global and private
2874 case AMDGPUAS::GLOBAL_ADDRESS: {
2875 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
2876 isMemOpHasNoClobberedMemOperand(Load))
2878 // Non-uniform loads will be selected to MUBUF instructions, so they
2879 // have the same legalization requirements as global and private
2884 case AMDGPUAS::FLAT_ADDRESS:
2885 if (NumElements > 4)
2886 return SplitVectorLoad(Op, DAG);
2887 // v4 loads are supported for private and global memory.
2889 case AMDGPUAS::PRIVATE_ADDRESS: {
2890 // Depending on the setting of the private_element_size field in the
2891 // resource descriptor, we can only make private accesses up to a certain
2893 switch (Subtarget->getMaxPrivateElementSize()) {
2895 return scalarizeVectorLoad(Load, DAG);
2897 if (NumElements > 2)
2898 return SplitVectorLoad(Op, DAG);
2901 // Same as global/flat
2902 if (NumElements > 4)
2903 return SplitVectorLoad(Op, DAG);
2906 llvm_unreachable("unsupported private_element_size");
2909 case AMDGPUAS::LOCAL_ADDRESS: {
2910 if (NumElements > 2)
2911 return SplitVectorLoad(Op, DAG);
2913 if (NumElements == 2)
2916 // If properly aligned, if we split we might be able to use ds_read_b64.
2917 return SplitVectorLoad(Op, DAG);
2924 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2925 if (Op.getValueType() != MVT::i64)
2929 SDValue Cond = Op.getOperand(0);
2931 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2932 SDValue One = DAG.getConstant(1, DL, MVT::i32);
2934 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
2935 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
2937 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
2938 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
2940 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
2942 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
2943 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
2945 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
2947 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
2948 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
2951 // Catch division cases where we can use shortcuts with rcp and rsq
2953 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
2954 SelectionDAG &DAG) const {
2956 SDValue LHS = Op.getOperand(0);
2957 SDValue RHS = Op.getOperand(1);
2958 EVT VT = Op.getValueType();
2959 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
2961 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
2962 if (Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
2964 if (CLHS->isExactlyValue(1.0)) {
2965 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
2966 // the CI documentation has a worst case error of 1 ulp.
2967 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
2968 // use it as long as we aren't trying to use denormals.
2970 // v_rcp_f16 and v_rsq_f16 DO support denormals.
2972 // 1.0 / sqrt(x) -> rsq(x)
2974 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
2975 // error seems really high at 2^29 ULP.
2976 if (RHS.getOpcode() == ISD::FSQRT)
2977 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
2979 // 1.0 / x -> rcp(x)
2980 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
2983 // Same as for 1.0, but expand the sign out of the constant.
2984 if (CLHS->isExactlyValue(-1.0)) {
2985 // -1.0 / x -> rcp (fneg x)
2986 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
2987 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
2992 const SDNodeFlags *Flags = Op->getFlags();
2994 if (Unsafe || Flags->hasAllowReciprocal()) {
2995 // Turn into multiply by the reciprocal.
2996 // x / y -> x * (1.0 / y)
2998 Flags.setUnsafeAlgebra(true);
2999 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3000 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
3006 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3007 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3008 if (GlueChain->getNumValues() <= 1) {
3009 return DAG.getNode(Opcode, SL, VT, A, B);
3012 assert(GlueChain->getNumValues() == 3);
3014 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3016 default: llvm_unreachable("no chain equivalent for opcode");
3018 Opcode = AMDGPUISD::FMUL_W_CHAIN;
3022 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3023 GlueChain.getValue(2));
3026 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3027 EVT VT, SDValue A, SDValue B, SDValue C,
3028 SDValue GlueChain) {
3029 if (GlueChain->getNumValues() <= 1) {
3030 return DAG.getNode(Opcode, SL, VT, A, B, C);
3033 assert(GlueChain->getNumValues() == 3);
3035 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3037 default: llvm_unreachable("no chain equivalent for opcode");
3039 Opcode = AMDGPUISD::FMA_W_CHAIN;
3043 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3044 GlueChain.getValue(2));
3047 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3048 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3052 SDValue Src0 = Op.getOperand(0);
3053 SDValue Src1 = Op.getOperand(1);
3055 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3056 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3058 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3059 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3061 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3062 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3064 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3067 // Faster 2.5 ULP division that does not support denormals.
3068 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3070 SDValue LHS = Op.getOperand(1);
3071 SDValue RHS = Op.getOperand(2);
3073 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3075 const APFloat K0Val(BitsToFloat(0x6f800000));
3076 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3078 const APFloat K1Val(BitsToFloat(0x2f800000));
3079 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3081 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3084 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3086 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3088 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3090 // TODO: Should this propagate fast-math-flags?
3091 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3093 // rcp does not support denormals.
3094 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3096 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3098 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3101 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3102 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3106 SDValue LHS = Op.getOperand(0);
3107 SDValue RHS = Op.getOperand(1);
3109 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3111 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3113 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3115 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3118 // Denominator is scaled to not be denormal, so using rcp is ok.
3119 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3121 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3124 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3125 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3126 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3128 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3130 if (!Subtarget->hasFP32Denormals()) {
3131 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3132 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
3134 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3136 EnableDenormValue, BitField);
3139 EnableDenorm.getValue(0),
3140 EnableDenorm.getValue(1)
3143 NegDivScale0 = DAG.getMergeValues(Ops, SL);
3146 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3147 ApproxRcp, One, NegDivScale0);
3149 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3152 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3155 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3156 NumeratorScaled, Mul);
3158 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3160 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3161 NumeratorScaled, Fma3);
3163 if (!Subtarget->hasFP32Denormals()) {
3164 const SDValue DisableDenormValue =
3165 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
3166 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3172 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3173 DisableDenorm, DAG.getRoot());
3174 DAG.setRoot(OutputChain);
3177 SDValue Scale = NumeratorScaled.getValue(1);
3178 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3179 Fma4, Fma1, Fma3, Scale);
3181 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3184 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3185 if (DAG.getTarget().Options.UnsafeFPMath)
3186 return lowerFastUnsafeFDIV(Op, DAG);
3189 SDValue X = Op.getOperand(0);
3190 SDValue Y = Op.getOperand(1);
3192 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3194 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3196 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3198 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3200 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3202 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3204 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3206 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3208 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3210 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3211 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3213 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3214 NegDivScale0, Mul, DivScale1);
3218 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3219 // Workaround a hardware bug on SI where the condition output from div_scale
3222 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3224 // Figure out if the scale to use for div_fmas.
3225 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3226 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3227 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3228 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3230 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3231 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3234 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3236 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3238 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3239 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3240 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3242 Scale = DivScale1.getValue(1);
3245 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3246 Fma4, Fma3, Mul, Scale);
3248 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3251 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3252 EVT VT = Op.getValueType();
3255 return LowerFDIV32(Op, DAG);
3258 return LowerFDIV64(Op, DAG);
3261 return LowerFDIV16(Op, DAG);
3263 llvm_unreachable("Unexpected type for fdiv");
3266 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3268 StoreSDNode *Store = cast<StoreSDNode>(Op);
3269 EVT VT = Store->getMemoryVT();
3271 if (VT == MVT::i1) {
3272 return DAG.getTruncStore(Store->getChain(), DL,
3273 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3274 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3277 assert(VT.isVector() &&
3278 Store->getValue().getValueType().getScalarType() == MVT::i32);
3280 unsigned AS = Store->getAddressSpace();
3281 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3282 AS, Store->getAlignment())) {
3283 return expandUnalignedStore(Store, DAG);
3286 MachineFunction &MF = DAG.getMachineFunction();
3287 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3288 // If there is a possibilty that flat instruction access scratch memory
3289 // then we need to use the same legalization rules we use for private.
3290 if (AS == AMDGPUAS::FLAT_ADDRESS)
3291 AS = MFI->hasFlatScratchInit() ?
3292 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
3294 unsigned NumElements = VT.getVectorNumElements();
3296 case AMDGPUAS::GLOBAL_ADDRESS:
3297 case AMDGPUAS::FLAT_ADDRESS:
3298 if (NumElements > 4)
3299 return SplitVectorStore(Op, DAG);
3301 case AMDGPUAS::PRIVATE_ADDRESS: {
3302 switch (Subtarget->getMaxPrivateElementSize()) {
3304 return scalarizeVectorStore(Store, DAG);
3306 if (NumElements > 2)
3307 return SplitVectorStore(Op, DAG);
3310 if (NumElements > 4)
3311 return SplitVectorStore(Op, DAG);
3314 llvm_unreachable("unsupported private_element_size");
3317 case AMDGPUAS::LOCAL_ADDRESS: {
3318 if (NumElements > 2)
3319 return SplitVectorStore(Op, DAG);
3321 if (NumElements == 2)
3324 // If properly aligned, if we split we might be able to use ds_write_b64.
3325 return SplitVectorStore(Op, DAG);
3328 llvm_unreachable("unhandled address space");
3332 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3334 EVT VT = Op.getValueType();
3335 SDValue Arg = Op.getOperand(0);
3336 // TODO: Should this propagate fast-math-flags?
3337 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3338 DAG.getNode(ISD::FMUL, DL, VT, Arg,
3339 DAG.getConstantFP(0.5/M_PI, DL,
3342 switch (Op.getOpcode()) {
3344 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3346 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3348 llvm_unreachable("Wrong trig opcode");
3352 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3353 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3354 assert(AtomicNode->isCompareAndSwap());
3355 unsigned AS = AtomicNode->getAddressSpace();
3357 // No custom lowering required for local address space
3358 if (!isFlatGlobalAddrSpace(AS))
3361 // Non-local address space requires custom lowering for atomic compare
3362 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3364 SDValue ChainIn = Op.getOperand(0);
3365 SDValue Addr = Op.getOperand(1);
3366 SDValue Old = Op.getOperand(2);
3367 SDValue New = Op.getOperand(3);
3368 EVT VT = Op.getValueType();
3369 MVT SimpleVT = VT.getSimpleVT();
3370 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3372 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3373 SDValue Ops[] = { ChainIn, Addr, NewOld };
3375 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3376 Ops, VT, AtomicNode->getMemOperand());
3379 //===----------------------------------------------------------------------===//
3380 // Custom DAG optimizations
3381 //===----------------------------------------------------------------------===//
3383 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3384 DAGCombinerInfo &DCI) const {
3385 EVT VT = N->getValueType(0);
3386 EVT ScalarVT = VT.getScalarType();
3387 if (ScalarVT != MVT::f32)
3390 SelectionDAG &DAG = DCI.DAG;
3393 SDValue Src = N->getOperand(0);
3394 EVT SrcVT = Src.getValueType();
3396 // TODO: We could try to match extracting the higher bytes, which would be
3397 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3398 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3399 // about in practice.
3400 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3401 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3402 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3403 DCI.AddToWorklist(Cvt.getNode());
3411 /// \brief Return true if the given offset Size in bytes can be folded into
3412 /// the immediate offsets of a memory instruction for the given address space.
3413 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3414 const SISubtarget &STI) {
3416 case AMDGPUAS::GLOBAL_ADDRESS: {
3417 // MUBUF instructions a 12-bit offset in bytes.
3418 return isUInt<12>(OffsetSize);
3420 case AMDGPUAS::CONSTANT_ADDRESS: {
3421 // SMRD instructions have an 8-bit offset in dwords on SI and
3422 // a 20-bit offset in bytes on VI.
3423 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3424 return isUInt<20>(OffsetSize);
3426 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3428 case AMDGPUAS::LOCAL_ADDRESS:
3429 case AMDGPUAS::REGION_ADDRESS: {
3430 // The single offset versions have a 16-bit offset in bytes.
3431 return isUInt<16>(OffsetSize);
3433 case AMDGPUAS::PRIVATE_ADDRESS:
3434 // Indirect register addressing does not use any offsets.
3440 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3442 // This is a variant of
3443 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3445 // The normal DAG combiner will do this, but only if the add has one use since
3446 // that would increase the number of instructions.
3448 // This prevents us from seeing a constant offset that can be folded into a
3449 // memory instruction's addressing mode. If we know the resulting add offset of
3450 // a pointer can be folded into an addressing offset, we can replace the pointer
3451 // operand with the add of new constant offset. This eliminates one of the uses,
3452 // and may allow the remaining use to also be simplified.
3454 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3456 DAGCombinerInfo &DCI) const {
3457 SDValue N0 = N->getOperand(0);
3458 SDValue N1 = N->getOperand(1);
3460 if (N0.getOpcode() != ISD::ADD)
3463 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3467 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3471 // If the resulting offset is too large, we can't fold it into the addressing
3473 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
3474 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
3477 SelectionDAG &DAG = DCI.DAG;
3479 EVT VT = N->getValueType(0);
3481 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
3482 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
3484 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
3487 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
3488 DAGCombinerInfo &DCI) const {
3489 SDValue Ptr = N->getBasePtr();
3490 SelectionDAG &DAG = DCI.DAG;
3493 // TODO: We could also do this for multiplies.
3494 unsigned AS = N->getAddressSpace();
3495 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
3496 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3498 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
3500 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3501 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
3508 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
3509 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
3510 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
3511 (Opc == ISD::XOR && Val == 0);
3514 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
3515 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
3516 // integer combine opportunities since most 64-bit operations are decomposed
3517 // this way. TODO: We won't want this for SALU especially if it is an inline
3519 SDValue SITargetLowering::splitBinaryBitConstantOp(
3520 DAGCombinerInfo &DCI,
3522 unsigned Opc, SDValue LHS,
3523 const ConstantSDNode *CRHS) const {
3524 uint64_t Val = CRHS->getZExtValue();
3525 uint32_t ValLo = Lo_32(Val);
3526 uint32_t ValHi = Hi_32(Val);
3527 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3529 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
3530 bitOpWithConstantIsReducible(Opc, ValHi)) ||
3531 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
3532 // If we need to materialize a 64-bit immediate, it will be split up later
3533 // anyway. Avoid creating the harder to understand 64-bit immediate
3535 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
3541 SDValue SITargetLowering::performAndCombine(SDNode *N,
3542 DAGCombinerInfo &DCI) const {
3543 if (DCI.isBeforeLegalize())
3546 SelectionDAG &DAG = DCI.DAG;
3547 EVT VT = N->getValueType(0);
3548 SDValue LHS = N->getOperand(0);
3549 SDValue RHS = N->getOperand(1);
3552 if (VT == MVT::i64) {
3553 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3556 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
3561 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
3562 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
3563 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
3564 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
3565 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
3567 SDValue X = LHS.getOperand(0);
3568 SDValue Y = RHS.getOperand(0);
3569 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
3572 if (LCC == ISD::SETO) {
3573 if (X != LHS.getOperand(1))
3576 if (RCC == ISD::SETUNE) {
3577 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
3578 if (!C1 || !C1->isInfinity() || C1->isNegative())
3581 const uint32_t Mask = SIInstrFlags::N_NORMAL |
3582 SIInstrFlags::N_SUBNORMAL |
3583 SIInstrFlags::N_ZERO |
3584 SIInstrFlags::P_ZERO |
3585 SIInstrFlags::P_SUBNORMAL |
3586 SIInstrFlags::P_NORMAL;
3588 static_assert(((~(SIInstrFlags::S_NAN |
3589 SIInstrFlags::Q_NAN |
3590 SIInstrFlags::N_INFINITY |
3591 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
3595 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3596 X, DAG.getConstant(Mask, DL, MVT::i32));
3604 SDValue SITargetLowering::performOrCombine(SDNode *N,
3605 DAGCombinerInfo &DCI) const {
3606 SelectionDAG &DAG = DCI.DAG;
3607 SDValue LHS = N->getOperand(0);
3608 SDValue RHS = N->getOperand(1);
3610 EVT VT = N->getValueType(0);
3611 if (VT == MVT::i1) {
3612 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
3613 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
3614 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
3615 SDValue Src = LHS.getOperand(0);
3616 if (Src != RHS.getOperand(0))
3619 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
3620 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
3624 // Only 10 bits are used.
3625 static const uint32_t MaxMask = 0x3ff;
3627 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
3629 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3630 Src, DAG.getConstant(NewMask, DL, MVT::i32));
3639 // TODO: This could be a generic combine with a predicate for extracting the
3640 // high half of an integer being free.
3642 // (or i64:x, (zero_extend i32:y)) ->
3643 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
3644 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
3645 RHS.getOpcode() != ISD::ZERO_EXTEND)
3646 std::swap(LHS, RHS);
3648 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
3649 SDValue ExtSrc = RHS.getOperand(0);
3650 EVT SrcVT = ExtSrc.getValueType();
3651 if (SrcVT == MVT::i32) {
3653 SDValue LowLHS, HiBits;
3654 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
3655 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
3657 DCI.AddToWorklist(LowOr.getNode());
3658 DCI.AddToWorklist(HiBits.getNode());
3660 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3662 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3666 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3669 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
3676 SDValue SITargetLowering::performXorCombine(SDNode *N,
3677 DAGCombinerInfo &DCI) const {
3678 EVT VT = N->getValueType(0);
3682 SDValue LHS = N->getOperand(0);
3683 SDValue RHS = N->getOperand(1);
3685 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3688 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
3695 SDValue SITargetLowering::performClassCombine(SDNode *N,
3696 DAGCombinerInfo &DCI) const {
3697 SelectionDAG &DAG = DCI.DAG;
3698 SDValue Mask = N->getOperand(1);
3700 // fp_class x, 0 -> false
3701 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
3702 if (CMask->isNullValue())
3703 return DAG.getConstant(0, SDLoc(N), MVT::i1);
3706 if (N->getOperand(0).isUndef())
3707 return DAG.getUNDEF(MVT::i1);
3712 // Constant fold canonicalize.
3713 SDValue SITargetLowering::performFCanonicalizeCombine(
3715 DAGCombinerInfo &DCI) const {
3716 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
3720 SelectionDAG &DAG = DCI.DAG;
3721 const APFloat &C = CFP->getValueAPF();
3723 // Flush denormals to 0 if not enabled.
3724 if (C.isDenormal()) {
3725 EVT VT = N->getValueType(0);
3726 if (VT == MVT::f32 && !Subtarget->hasFP32Denormals())
3727 return DAG.getConstantFP(0.0, SDLoc(N), VT);
3729 if (VT == MVT::f64 && !Subtarget->hasFP64Denormals())
3730 return DAG.getConstantFP(0.0, SDLoc(N), VT);
3732 if (VT == MVT::f16 && !Subtarget->hasFP16Denormals())
3733 return DAG.getConstantFP(0.0, SDLoc(N), VT);
3737 EVT VT = N->getValueType(0);
3738 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
3739 if (C.isSignaling()) {
3740 // Quiet a signaling NaN.
3741 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
3744 // Make sure it is the canonical NaN bitpattern.
3746 // TODO: Can we use -1 as the canonical NaN value since it's an inline
3748 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
3749 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
3752 return SDValue(CFP, 0);
3755 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
3758 return AMDGPUISD::FMAX3;
3760 return AMDGPUISD::SMAX3;
3762 return AMDGPUISD::UMAX3;
3764 return AMDGPUISD::FMIN3;
3766 return AMDGPUISD::SMIN3;
3768 return AMDGPUISD::UMIN3;
3770 llvm_unreachable("Not a min/max opcode");
3774 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL,
3775 SDValue Op0, SDValue Op1, bool Signed) {
3776 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
3780 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
3785 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
3788 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
3792 EVT VT = K0->getValueType(0);
3795 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3797 SDValue Tmp1, Tmp2, Tmp3;
3798 Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
3799 Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
3800 Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
3802 if (VT == MVT::i16) {
3803 Tmp1 = DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, NVT,
3806 return DAG.getNode(ISD::TRUNCATE, SL, VT, Tmp1);
3808 return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT,
3809 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
3812 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
3813 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
3816 return DAG.isKnownNeverNaN(Op);
3819 static SDValue performFPMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL,
3820 SDValue Op0, SDValue Op1) {
3821 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
3825 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
3829 // Ordered >= (although NaN inputs should have folded away by now).
3830 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
3831 if (Cmp == APFloat::cmpGreaterThan)
3834 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
3835 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
3836 // give the other result, which is different from med3 with a NaN input.
3837 SDValue Var = Op0.getOperand(0);
3838 if (!isKnownNeverSNan(DAG, Var))
3841 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
3842 Var, SDValue(K0, 0), SDValue(K1, 0));
3845 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
3846 DAGCombinerInfo &DCI) const {
3847 SelectionDAG &DAG = DCI.DAG;
3849 unsigned Opc = N->getOpcode();
3850 SDValue Op0 = N->getOperand(0);
3851 SDValue Op1 = N->getOperand(1);
3853 // Only do this if the inner op has one use since this will just increases
3854 // register pressure for no benefit.
3856 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY) {
3857 // max(max(a, b), c) -> max3(a, b, c)
3858 // min(min(a, b), c) -> min3(a, b, c)
3859 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
3861 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
3870 // max(a, max(b, c)) -> max3(a, b, c)
3871 // min(a, min(b, c)) -> min3(a, b, c)
3872 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
3874 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
3883 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
3884 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
3885 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
3889 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
3890 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
3894 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
3895 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
3896 (Opc == AMDGPUISD::FMIN_LEGACY &&
3897 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
3898 N->getValueType(0) == MVT::f32 && Op0.hasOneUse()) {
3899 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
3906 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
3908 const SDNode *N1) const {
3909 EVT VT = N0->getValueType(0);
3911 // Only do this if we are not trying to support denormals. v_mad_f32 does not
3912 // support denormals ever.
3913 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
3914 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
3917 const TargetOptions &Options = DAG.getTarget().Options;
3918 if ((Options.AllowFPOpFusion == FPOpFusion::Fast ||
3919 Options.UnsafeFPMath ||
3920 (cast<BinaryWithFlagsSDNode>(N0)->Flags.hasUnsafeAlgebra() &&
3921 cast<BinaryWithFlagsSDNode>(N1)->Flags.hasUnsafeAlgebra())) &&
3922 isFMAFasterThanFMulAndFAdd(VT)) {
3929 SDValue SITargetLowering::performFAddCombine(SDNode *N,
3930 DAGCombinerInfo &DCI) const {
3931 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3934 SelectionDAG &DAG = DCI.DAG;
3935 EVT VT = N->getValueType(0);
3936 assert(!VT.isVector());
3939 SDValue LHS = N->getOperand(0);
3940 SDValue RHS = N->getOperand(1);
3942 // These should really be instruction patterns, but writing patterns with
3943 // source modiifiers is a pain.
3945 // fadd (fadd (a, a), b) -> mad 2.0, a, b
3946 if (LHS.getOpcode() == ISD::FADD) {
3947 SDValue A = LHS.getOperand(0);
3948 if (A == LHS.getOperand(1)) {
3949 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
3951 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
3952 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
3957 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
3958 if (RHS.getOpcode() == ISD::FADD) {
3959 SDValue A = RHS.getOperand(0);
3960 if (A == RHS.getOperand(1)) {
3961 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
3963 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
3964 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
3972 SDValue SITargetLowering::performFSubCombine(SDNode *N,
3973 DAGCombinerInfo &DCI) const {
3974 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3977 SelectionDAG &DAG = DCI.DAG;
3979 EVT VT = N->getValueType(0);
3980 assert(!VT.isVector());
3982 // Try to get the fneg to fold into the source modifier. This undoes generic
3983 // DAG combines and folds them into the mad.
3985 // Only do this if we are not trying to support denormals. v_mad_f32 does
3986 // not support denormals ever.
3987 SDValue LHS = N->getOperand(0);
3988 SDValue RHS = N->getOperand(1);
3989 if (LHS.getOpcode() == ISD::FADD) {
3990 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
3991 SDValue A = LHS.getOperand(0);
3992 if (A == LHS.getOperand(1)) {
3993 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
3995 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
3996 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3998 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4003 if (RHS.getOpcode() == ISD::FADD) {
4004 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4006 SDValue A = RHS.getOperand(0);
4007 if (A == RHS.getOperand(1)) {
4008 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4010 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4011 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4019 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4020 DAGCombinerInfo &DCI) const {
4021 SelectionDAG &DAG = DCI.DAG;
4024 SDValue LHS = N->getOperand(0);
4025 SDValue RHS = N->getOperand(1);
4026 EVT VT = LHS.getValueType();
4028 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4032 // Match isinf pattern
4033 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4034 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4035 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4036 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4040 const APFloat &APF = CRHS->getValueAPF();
4041 if (APF.isInfinity() && !APF.isNegative()) {
4042 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4043 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4044 DAG.getConstant(Mask, SL, MVT::i32));
4051 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4052 DAGCombinerInfo &DCI) const {
4053 SelectionDAG &DAG = DCI.DAG;
4055 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4057 SDValue Src = N->getOperand(0);
4058 SDValue Srl = N->getOperand(0);
4059 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4060 Srl = Srl.getOperand(0);
4062 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4063 if (Srl.getOpcode() == ISD::SRL) {
4064 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4065 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4066 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4068 if (const ConstantSDNode *C =
4069 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4070 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4073 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4074 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4075 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4081 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4083 APInt KnownZero, KnownOne;
4084 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4085 !DCI.isBeforeLegalizeOps());
4086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4087 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
4088 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
4089 DCI.CommitTargetLoweringOpt(TLO);
4095 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
4096 DAGCombinerInfo &DCI) const {
4097 switch (N->getOpcode()) {
4099 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4101 return performFAddCombine(N, DCI);
4103 return performFSubCombine(N, DCI);
4105 return performSetCCCombine(N, DCI);
4112 case AMDGPUISD::FMIN_LEGACY:
4113 case AMDGPUISD::FMAX_LEGACY: {
4114 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
4115 N->getValueType(0) != MVT::f64 &&
4116 getTargetMachine().getOptLevel() > CodeGenOpt::None)
4117 return performMinMaxCombine(N, DCI);
4122 case ISD::ATOMIC_LOAD:
4123 case ISD::ATOMIC_STORE:
4124 case ISD::ATOMIC_CMP_SWAP:
4125 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4126 case ISD::ATOMIC_SWAP:
4127 case ISD::ATOMIC_LOAD_ADD:
4128 case ISD::ATOMIC_LOAD_SUB:
4129 case ISD::ATOMIC_LOAD_AND:
4130 case ISD::ATOMIC_LOAD_OR:
4131 case ISD::ATOMIC_LOAD_XOR:
4132 case ISD::ATOMIC_LOAD_NAND:
4133 case ISD::ATOMIC_LOAD_MIN:
4134 case ISD::ATOMIC_LOAD_MAX:
4135 case ISD::ATOMIC_LOAD_UMIN:
4136 case ISD::ATOMIC_LOAD_UMAX:
4137 case AMDGPUISD::ATOMIC_INC:
4138 case AMDGPUISD::ATOMIC_DEC: { // TODO: Target mem intrinsics.
4139 if (DCI.isBeforeLegalize())
4141 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
4144 return performAndCombine(N, DCI);
4146 return performOrCombine(N, DCI);
4148 return performXorCombine(N, DCI);
4149 case AMDGPUISD::FP_CLASS:
4150 return performClassCombine(N, DCI);
4151 case ISD::FCANONICALIZE:
4152 return performFCanonicalizeCombine(N, DCI);
4153 case AMDGPUISD::FRACT:
4154 case AMDGPUISD::RCP:
4155 case AMDGPUISD::RSQ:
4156 case AMDGPUISD::RCP_LEGACY:
4157 case AMDGPUISD::RSQ_LEGACY:
4158 case AMDGPUISD::RSQ_CLAMP:
4159 case AMDGPUISD::LDEXP: {
4160 SDValue Src = N->getOperand(0);
4165 case ISD::SINT_TO_FP:
4166 case ISD::UINT_TO_FP:
4167 return performUCharToFloatCombine(N, DCI);
4168 case AMDGPUISD::CVT_F32_UBYTE0:
4169 case AMDGPUISD::CVT_F32_UBYTE1:
4170 case AMDGPUISD::CVT_F32_UBYTE2:
4171 case AMDGPUISD::CVT_F32_UBYTE3:
4172 return performCvtF32UByteNCombine(N, DCI);
4174 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4177 /// \brief Helper function for adjustWritemask
4178 static unsigned SubIdx2Lane(unsigned Idx) {
4181 case AMDGPU::sub0: return 0;
4182 case AMDGPU::sub1: return 1;
4183 case AMDGPU::sub2: return 2;
4184 case AMDGPU::sub3: return 3;
4188 /// \brief Adjust the writemask of MIMG instructions
4189 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
4190 SelectionDAG &DAG) const {
4191 SDNode *Users[4] = { };
4193 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
4194 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
4195 unsigned NewDmask = 0;
4197 // Try to figure out the used register components
4198 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
4201 // Abort if we can't understand the usage
4202 if (!I->isMachineOpcode() ||
4203 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
4206 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
4207 // Note that subregs are packed, i.e. Lane==0 is the first bit set
4208 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
4210 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
4212 // Set which texture component corresponds to the lane.
4214 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
4216 Comp = countTrailingZeros(Dmask);
4217 Dmask &= ~(1 << Comp);
4220 // Abort if we have more than one user per component
4225 NewDmask |= 1 << Comp;
4228 // Abort if there's no change
4229 if (NewDmask == OldDmask)
4232 // Adjust the writemask in the node
4233 std::vector<SDValue> Ops;
4234 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
4235 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
4236 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
4237 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
4239 // If we only got one lane, replace it with a copy
4240 // (if NewDmask has only one bit set...)
4241 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
4242 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
4244 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4245 SDLoc(), Users[Lane]->getValueType(0),
4246 SDValue(Node, 0), RC);
4247 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
4251 // Update the users of the node with the new indices
4252 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
4254 SDNode *User = Users[i];
4258 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
4259 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
4263 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
4264 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
4265 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
4270 static bool isFrameIndexOp(SDValue Op) {
4271 if (Op.getOpcode() == ISD::AssertZext)
4272 Op = Op.getOperand(0);
4274 return isa<FrameIndexSDNode>(Op);
4277 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
4278 /// with frame index operands.
4279 /// LLVM assumes that inputs are to these instructions are registers.
4280 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
4281 SelectionDAG &DAG) const {
4283 SmallVector<SDValue, 8> Ops;
4284 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
4285 if (!isFrameIndexOp(Node->getOperand(i))) {
4286 Ops.push_back(Node->getOperand(i));
4291 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
4292 Node->getOperand(i).getValueType(),
4293 Node->getOperand(i)), 0));
4296 DAG.UpdateNodeOperands(Node, Ops);
4299 /// \brief Fold the instructions after selecting them.
4300 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
4301 SelectionDAG &DAG) const {
4302 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4303 unsigned Opcode = Node->getMachineOpcode();
4305 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
4306 !TII->isGather4(Opcode))
4307 adjustWritemask(Node, DAG);
4309 if (Opcode == AMDGPU::INSERT_SUBREG ||
4310 Opcode == AMDGPU::REG_SEQUENCE) {
4311 legalizeTargetIndependentNode(Node, DAG);
4317 /// \brief Assign the register class depending on the number of
4318 /// bits set in the writemask
4319 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
4320 SDNode *Node) const {
4321 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4323 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4325 if (TII->isVOP3(MI.getOpcode())) {
4326 // Make sure constant bus requirements are respected.
4327 TII->legalizeOperandsVOP3(MRI, MI);
4331 if (TII->isMIMG(MI)) {
4332 unsigned VReg = MI.getOperand(0).getReg();
4333 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
4334 // TODO: Need mapping tables to handle other cases (register classes).
4335 if (RC != &AMDGPU::VReg_128RegClass)
4338 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
4339 unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
4340 unsigned BitsSet = 0;
4341 for (unsigned i = 0; i < 4; ++i)
4342 BitsSet += Writemask & (1 << i) ? 1 : 0;
4345 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
4346 case 2: RC = &AMDGPU::VReg_64RegClass; break;
4347 case 3: RC = &AMDGPU::VReg_96RegClass; break;
4350 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
4351 MI.setDesc(TII->get(NewOpcode));
4352 MRI.setRegClass(VReg, RC);
4356 // Replace unused atomics with the no return version.
4357 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
4358 if (NoRetAtomicOp != -1) {
4359 if (!Node->hasAnyUseOfValue(0)) {
4360 MI.setDesc(TII->get(NoRetAtomicOp));
4361 MI.RemoveOperand(0);
4365 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
4366 // instruction, because the return type of these instructions is a vec2 of
4367 // the memory type, so it can be tied to the input operand.
4368 // This means these instructions always have a use, so we need to add a
4369 // special case to check if the atomic has only one extract_subreg use,
4370 // which itself has no uses.
4371 if ((Node->hasNUsesOfValue(1, 0) &&
4372 Node->use_begin()->isMachineOpcode() &&
4373 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
4374 !Node->use_begin()->hasAnyUseOfValue(0))) {
4375 unsigned Def = MI.getOperand(0).getReg();
4377 // Change this into a noret atomic.
4378 MI.setDesc(TII->get(NoRetAtomicOp));
4379 MI.RemoveOperand(0);
4381 // If we only remove the def operand from the atomic instruction, the
4382 // extract_subreg will be left with a use of a vreg without a def.
4383 // So we need to insert an implicit_def to avoid machine verifier
4385 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
4386 TII->get(AMDGPU::IMPLICIT_DEF), Def);
4392 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
4394 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
4395 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
4398 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
4400 SDValue Ptr) const {
4401 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4403 // Build the half of the subregister with the constants before building the
4404 // full 128-bit register. If we are building multiple resource descriptors,
4405 // this will allow CSEing of the 2-component register.
4406 const SDValue Ops0[] = {
4407 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
4408 buildSMovImm32(DAG, DL, 0),
4409 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4410 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
4411 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
4414 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
4415 MVT::v2i32, Ops0), 0);
4417 // Combine the constants and the pointer.
4418 const SDValue Ops1[] = {
4419 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4421 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
4423 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
4426 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
4429 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
4430 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
4431 /// of the resource descriptor) to create an offset, which is added to
4432 /// the resource pointer.
4433 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
4434 SDValue Ptr, uint32_t RsrcDword1,
4435 uint64_t RsrcDword2And3) const {
4436 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
4437 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
4439 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
4440 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
4444 SDValue DataLo = buildSMovImm32(DAG, DL,
4445 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
4446 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
4448 const SDValue Ops[] = {
4449 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4451 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4453 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
4455 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
4457 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
4460 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
4463 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
4464 const TargetRegisterClass *RC,
4465 unsigned Reg, EVT VT) const {
4466 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
4468 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
4469 cast<RegisterSDNode>(VReg)->getReg(), VT);
4472 //===----------------------------------------------------------------------===//
4473 // SI Inline Assembly Support
4474 //===----------------------------------------------------------------------===//
4476 std::pair<unsigned, const TargetRegisterClass *>
4477 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4478 StringRef Constraint,
4480 if (!isTypeLegal(VT))
4481 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4483 if (Constraint.size() == 1) {
4484 switch (Constraint[0]) {
4487 switch (VT.getSizeInBits()) {
4489 return std::make_pair(0U, nullptr);
4492 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
4494 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
4496 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
4498 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
4502 switch (VT.getSizeInBits()) {
4504 return std::make_pair(0U, nullptr);
4507 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
4509 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
4511 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
4513 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
4515 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
4517 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
4522 if (Constraint.size() > 1) {
4523 const TargetRegisterClass *RC = nullptr;
4524 if (Constraint[1] == 'v') {
4525 RC = &AMDGPU::VGPR_32RegClass;
4526 } else if (Constraint[1] == 's') {
4527 RC = &AMDGPU::SGPR_32RegClass;
4532 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
4533 if (!Failed && Idx < RC->getNumRegs())
4534 return std::make_pair(RC->getRegister(Idx), RC);
4537 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4540 SITargetLowering::ConstraintType
4541 SITargetLowering::getConstraintType(StringRef Constraint) const {
4542 if (Constraint.size() == 1) {
4543 switch (Constraint[0]) {
4547 return C_RegisterClass;
4550 return TargetLowering::getConstraintType(Constraint);