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
21 #include "SIISelLowering.h"
23 #include "AMDGPUDiagnosticInfoUnsupported.h"
24 #include "AMDGPUIntrinsicInfo.h"
25 #include "AMDGPUSubtarget.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/CodeGen/CallingConvLower.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/ADT/SmallString.h"
39 SITargetLowering::SITargetLowering(TargetMachine &TM,
40 const AMDGPUSubtarget &STI)
41 : AMDGPUTargetLowering(TM, STI) {
42 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
43 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
45 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
46 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
48 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
49 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
51 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
52 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
53 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
55 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
56 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
58 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
59 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
61 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
62 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
64 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
65 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
67 computeRegisterProperties(STI.getRegisterInfo());
69 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
70 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
71 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
72 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
74 setOperationAction(ISD::ADD, MVT::i32, Legal);
75 setOperationAction(ISD::ADDC, MVT::i32, Legal);
76 setOperationAction(ISD::ADDE, MVT::i32, Legal);
77 setOperationAction(ISD::SUBC, MVT::i32, Legal);
78 setOperationAction(ISD::SUBE, MVT::i32, Legal);
80 setOperationAction(ISD::FSIN, MVT::f32, Custom);
81 setOperationAction(ISD::FCOS, MVT::f32, Custom);
83 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
84 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
86 // We need to custom lower vector stores from local memory
87 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
88 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
89 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
91 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
92 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
94 setOperationAction(ISD::STORE, MVT::i1, Custom);
95 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
97 setOperationAction(ISD::SELECT, MVT::i64, Custom);
98 setOperationAction(ISD::SELECT, MVT::f64, Promote);
99 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
101 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
102 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
103 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
104 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
106 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
107 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
109 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
110 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
114 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
128 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
129 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
130 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
132 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
133 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
135 for (MVT VT : MVT::integer_valuetypes()) {
139 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
142 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
144 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
145 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
146 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
147 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
149 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
150 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
151 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
152 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
155 for (MVT VT : MVT::integer_vector_valuetypes()) {
156 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
157 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
160 for (MVT VT : MVT::fp_valuetypes())
161 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
163 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
164 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
166 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
167 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
168 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
169 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
172 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand);
174 setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
175 setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand);
177 setOperationAction(ISD::LOAD, MVT::i1, Custom);
179 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
180 AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32);
182 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
183 AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32);
185 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
187 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
188 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
189 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
191 // These should use UDIVREM, so set them to expand
192 setOperationAction(ISD::UDIV, MVT::i64, Expand);
193 setOperationAction(ISD::UREM, MVT::i64, Expand);
195 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
196 setOperationAction(ISD::SELECT, MVT::i1, Promote);
198 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
201 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
203 // We only support LOAD/STORE and vector manipulation ops for vectors
204 // with > 4 elements.
205 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) {
206 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
210 case ISD::BUILD_VECTOR:
212 case ISD::EXTRACT_VECTOR_ELT:
213 case ISD::INSERT_VECTOR_ELT:
214 case ISD::INSERT_SUBVECTOR:
215 case ISD::EXTRACT_SUBVECTOR:
216 case ISD::SCALAR_TO_VECTOR:
218 case ISD::CONCAT_VECTORS:
219 setOperationAction(Op, VT, Custom);
222 setOperationAction(Op, VT, Expand);
228 // Most operations are naturally 32-bit vector operations. We only support
229 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
230 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
231 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
232 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
234 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
235 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
237 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
238 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
240 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
241 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
244 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
245 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
246 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
247 setOperationAction(ISD::FRINT, MVT::f64, Legal);
250 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
251 setOperationAction(ISD::FDIV, MVT::f32, Custom);
252 setOperationAction(ISD::FDIV, MVT::f64, Custom);
254 setTargetDAGCombine(ISD::FADD);
255 setTargetDAGCombine(ISD::FSUB);
256 setTargetDAGCombine(ISD::FMINNUM);
257 setTargetDAGCombine(ISD::FMAXNUM);
258 setTargetDAGCombine(ISD::SMIN);
259 setTargetDAGCombine(ISD::SMAX);
260 setTargetDAGCombine(ISD::UMIN);
261 setTargetDAGCombine(ISD::UMAX);
262 setTargetDAGCombine(ISD::SETCC);
263 setTargetDAGCombine(ISD::AND);
264 setTargetDAGCombine(ISD::OR);
265 setTargetDAGCombine(ISD::UINT_TO_FP);
267 // All memory operations. Some folding on the pointer operand is done to help
268 // matching the constant offsets in the addressing modes.
269 setTargetDAGCombine(ISD::LOAD);
270 setTargetDAGCombine(ISD::STORE);
271 setTargetDAGCombine(ISD::ATOMIC_LOAD);
272 setTargetDAGCombine(ISD::ATOMIC_STORE);
273 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
274 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
275 setTargetDAGCombine(ISD::ATOMIC_SWAP);
276 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
277 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
278 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
279 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
280 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
281 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
282 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
283 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
284 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
285 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
287 setSchedulingPreference(Sched::RegPressure);
290 //===----------------------------------------------------------------------===//
291 // TargetLowering queries
292 //===----------------------------------------------------------------------===//
294 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
296 // SI has some legal vector types, but no legal vector operations. Say no
297 // shuffles are legal in order to prefer scalarizing some vector operations.
301 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
302 // Flat instructions do not have offsets, and only have the register
304 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
307 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
308 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
309 // additionally can do r + r + i with addr64. 32-bit has more addressing
310 // mode options. Depending on the resource constant, it can also do
311 // (i64 r0) + (i32 r1) * (i14 i).
313 // Private arrays end up using a scratch buffer most of the time, so also
314 // assume those use MUBUF instructions. Scratch loads / stores are currently
315 // implemented as mubuf instructions with offen bit set, so slightly
316 // different than the normal addr64.
317 if (!isUInt<12>(AM.BaseOffs))
320 // FIXME: Since we can split immediate into soffset and immediate offset,
321 // would it make sense to allow any immediate?
324 case 0: // r + i or just i, depending on HasBaseReg.
327 return true; // We have r + r or r + i.
334 // Allow 2 * r as r + r
335 // Or 2 * r + i is allowed as r + r + i.
337 default: // Don't allow n * r
342 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
343 const AddrMode &AM, Type *Ty,
345 // No global is ever allowed as a base.
350 case AMDGPUAS::GLOBAL_ADDRESS: {
351 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
352 // Assume the we will use FLAT for all global memory accesses
354 // FIXME: This assumption is currently wrong. On VI we still use
355 // MUBUF instructions for the r + i addressing mode. As currently
356 // implemented, the MUBUF instructions only work on buffer < 4GB.
357 // It may be possible to support > 4GB buffers with MUBUF instructions,
358 // by setting the stride value in the resource descriptor which would
359 // increase the size limit to (stride * 4GB). However, this is risky,
360 // because it has never been validated.
361 return isLegalFlatAddressingMode(AM);
364 return isLegalMUBUFAddressingMode(AM);
366 case AMDGPUAS::CONSTANT_ADDRESS: {
367 // If the offset isn't a multiple of 4, it probably isn't going to be
368 // correctly aligned.
369 if (AM.BaseOffs % 4 != 0)
370 return isLegalMUBUFAddressingMode(AM);
372 // There are no SMRD extloads, so if we have to do a small type access we
373 // will use a MUBUF load.
374 // FIXME?: We also need to do this if unaligned, but we don't know the
376 if (DL.getTypeStoreSize(Ty) < 4)
377 return isLegalMUBUFAddressingMode(AM);
379 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
380 // SMRD instructions have an 8-bit, dword offset on SI.
381 if (!isUInt<8>(AM.BaseOffs / 4))
383 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
384 // On CI+, this can also be a 32-bit literal constant offset. If it fits
385 // in 8-bits, it can use a smaller encoding.
386 if (!isUInt<32>(AM.BaseOffs / 4))
388 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) {
389 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
390 if (!isUInt<20>(AM.BaseOffs))
393 llvm_unreachable("unhandled generation");
395 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
398 if (AM.Scale == 1 && AM.HasBaseReg)
404 case AMDGPUAS::PRIVATE_ADDRESS:
405 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
406 return isLegalMUBUFAddressingMode(AM);
408 case AMDGPUAS::LOCAL_ADDRESS:
409 case AMDGPUAS::REGION_ADDRESS: {
410 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
412 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
413 // an 8-bit dword offset but we don't know the alignment here.
414 if (!isUInt<16>(AM.BaseOffs))
417 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
420 if (AM.Scale == 1 && AM.HasBaseReg)
425 case AMDGPUAS::FLAT_ADDRESS:
426 return isLegalFlatAddressingMode(AM);
429 llvm_unreachable("unhandled address space");
433 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
436 bool *IsFast) const {
440 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
441 // which isn't a simple VT.
442 if (!VT.isSimple() || VT == MVT::Other)
445 // TODO - CI+ supports unaligned memory accesses, but this requires driver
448 // XXX - The only mention I see of this in the ISA manual is for LDS direct
449 // reads the "byte address and must be dword aligned". Is it also true for the
450 // normal loads and stores?
451 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
452 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
453 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
454 // with adjacent offsets.
455 bool AlignedBy4 = (Align % 4 == 0);
457 *IsFast = AlignedBy4;
461 // Smaller than dword value must be aligned.
462 // FIXME: This should be allowed on CI+
463 if (VT.bitsLT(MVT::i32))
466 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
467 // byte-address are ignored, thus forcing Dword alignment.
468 // This applies to private, global, and constant memory.
472 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
475 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
476 unsigned SrcAlign, bool IsMemset,
479 MachineFunction &MF) const {
480 // FIXME: Should account for address space here.
482 // The default fallback uses the private pointer size as a guess for a type to
483 // use. Make sure we switch these to 64-bit accesses.
485 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
488 if (Size >= 8 && DstAlign >= 4)
495 static bool isFlatGlobalAddrSpace(unsigned AS) {
496 return AS == AMDGPUAS::GLOBAL_ADDRESS ||
497 AS == AMDGPUAS::FLAT_ADDRESS ||
498 AS == AMDGPUAS::CONSTANT_ADDRESS;
501 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
502 unsigned DestAS) const {
503 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
507 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
508 const MemSDNode *MemNode = cast<MemSDNode>(N);
509 const Value *Ptr = MemNode->getMemOperand()->getValue();
511 // UndefValue means this is a load of a kernel input. These are uniform.
512 // Sometimes LDS instructions have constant pointers
513 if (isa<UndefValue>(Ptr) || isa<Argument>(Ptr) || isa<Constant>(Ptr) ||
514 isa<GlobalValue>(Ptr))
517 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
518 return I && I->getMetadata("amdgpu.uniform");
521 TargetLoweringBase::LegalizeTypeAction
522 SITargetLowering::getPreferredVectorAction(EVT VT) const {
523 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
524 return TypeSplitVector;
526 return TargetLoweringBase::getPreferredVectorAction(VT);
529 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
531 const SIInstrInfo *TII =
532 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
533 return TII->isInlineConstant(Imm);
536 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
537 SDLoc SL, SDValue Chain,
538 unsigned Offset, bool Signed) const {
539 const DataLayout &DL = DAG.getDataLayout();
540 MachineFunction &MF = DAG.getMachineFunction();
541 const SIRegisterInfo *TRI =
542 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
543 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
545 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
547 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
548 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
549 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
550 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
551 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
552 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
553 DAG.getConstant(Offset, SL, PtrVT));
554 SDValue PtrOffset = DAG.getUNDEF(PtrVT);
555 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
557 unsigned Align = DL.getABITypeAlignment(Ty);
559 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
560 if (MemVT.isFloatingPoint())
561 ExtTy = ISD::EXTLOAD;
563 return DAG.getLoad(ISD::UNINDEXED, ExtTy,
564 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
566 true, // isNonTemporal
571 SDValue SITargetLowering::LowerFormalArguments(
572 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
573 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
574 SmallVectorImpl<SDValue> &InVals) const {
575 const SIRegisterInfo *TRI =
576 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
578 MachineFunction &MF = DAG.getMachineFunction();
579 FunctionType *FType = MF.getFunction()->getFunctionType();
580 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
581 const AMDGPUSubtarget &ST = MF.getSubtarget<AMDGPUSubtarget>();
583 if (Subtarget->isAmdHsaOS() && Info->getShaderType() != ShaderType::COMPUTE) {
584 const Function *Fn = MF.getFunction();
585 DiagnosticInfoUnsupported NoGraphicsHSA(*Fn, "non-compute shaders with HSA");
586 DAG.getContext()->diagnose(NoGraphicsHSA);
590 // FIXME: We currently assume all calling conventions are kernels.
592 SmallVector<ISD::InputArg, 16> Splits;
593 BitVector Skipped(Ins.size());
595 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
596 const ISD::InputArg &Arg = Ins[i];
598 // First check if it's a PS input addr
599 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
600 !Arg.Flags.isByVal() && PSInputNum <= 15) {
602 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
603 // We can safely skip PS inputs
609 Info->markPSInputAllocated(PSInputNum);
611 Info->PSInputEna |= 1 << PSInputNum;
616 // Second split vertices into their elements
617 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
618 ISD::InputArg NewArg = Arg;
619 NewArg.Flags.setSplit();
620 NewArg.VT = Arg.VT.getVectorElementType();
622 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
623 // three or five element vertex only needs three or five registers,
624 // NOT four or eight.
625 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
626 unsigned NumElements = ParamType->getVectorNumElements();
628 for (unsigned j = 0; j != NumElements; ++j) {
629 Splits.push_back(NewArg);
630 NewArg.PartOffset += NewArg.VT.getStoreSize();
633 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
634 Splits.push_back(Arg);
638 SmallVector<CCValAssign, 16> ArgLocs;
639 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
642 // At least one interpolation mode must be enabled or else the GPU will hang.
644 // Check PSInputAddr instead of PSInputEna. The idea is that if the user set
645 // PSInputAddr, the user wants to enable some bits after the compilation
646 // based on run-time states. Since we can't know what the final PSInputEna
647 // will look like, so we shouldn't do anything here and the user should take
648 // responsibility for the correct programming.
649 if (Info->getShaderType() == ShaderType::PIXEL &&
650 (Info->getPSInputAddr() & 0x7F) == 0) {
651 CCInfo.AllocateReg(AMDGPU::VGPR0);
652 CCInfo.AllocateReg(AMDGPU::VGPR1);
653 Info->markPSInputAllocated(0);
654 Info->PSInputEna |= 1;
657 if (Info->getShaderType() == ShaderType::COMPUTE) {
658 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
662 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
663 if (Info->hasPrivateSegmentBuffer()) {
664 unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
665 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
666 CCInfo.AllocateReg(PrivateSegmentBufferReg);
669 if (Info->hasDispatchPtr()) {
670 unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
671 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass);
672 CCInfo.AllocateReg(DispatchPtrReg);
675 if (Info->hasKernargSegmentPtr()) {
676 unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
677 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
678 CCInfo.AllocateReg(InputPtrReg);
681 AnalyzeFormalArguments(CCInfo, Splits);
683 SmallVector<SDValue, 16> Chains;
685 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
687 const ISD::InputArg &Arg = Ins[i];
689 InVals.push_back(DAG.getUNDEF(Arg.VT));
693 CCValAssign &VA = ArgLocs[ArgIdx++];
694 MVT VT = VA.getLocVT();
698 EVT MemVT = Splits[i].VT;
699 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
700 VA.getLocMemOffset();
701 // The first 36 bytes of the input buffer contains information about
702 // thread group and global sizes.
703 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain,
704 Offset, Ins[i].Flags.isSExt());
705 Chains.push_back(Arg.getValue(1));
708 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
709 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
710 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
711 // On SI local pointers are just offsets into LDS, so they are always
712 // less than 16-bits. On CI and newer they could potentially be
713 // real pointers, so we can't guarantee their size.
714 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
715 DAG.getValueType(MVT::i16));
718 InVals.push_back(Arg);
719 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
722 assert(VA.isRegLoc() && "Parameter must be in a register!");
724 unsigned Reg = VA.getLocReg();
726 if (VT == MVT::i64) {
727 // For now assume it is a pointer
728 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
729 &AMDGPU::SReg_64RegClass);
730 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
731 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
732 InVals.push_back(Copy);
736 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
738 Reg = MF.addLiveIn(Reg, RC);
739 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
741 if (Arg.VT.isVector()) {
743 // Build a vector from the registers
744 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
745 unsigned NumElements = ParamType->getVectorNumElements();
747 SmallVector<SDValue, 4> Regs;
749 for (unsigned j = 1; j != NumElements; ++j) {
750 Reg = ArgLocs[ArgIdx++].getLocReg();
751 Reg = MF.addLiveIn(Reg, RC);
753 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
754 Regs.push_back(Copy);
757 // Fill up the missing vector elements
758 NumElements = Arg.VT.getVectorNumElements() - NumElements;
759 Regs.append(NumElements, DAG.getUNDEF(VT));
761 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
765 InVals.push_back(Val);
768 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
769 // these from the dispatch pointer.
771 // Start adding system SGPRs.
772 if (Info->hasWorkGroupIDX()) {
773 unsigned Reg = Info->addWorkGroupIDX();
774 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
775 CCInfo.AllocateReg(Reg);
777 llvm_unreachable("work group id x is always enabled");
779 if (Info->hasWorkGroupIDY()) {
780 unsigned Reg = Info->addWorkGroupIDY();
781 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
782 CCInfo.AllocateReg(Reg);
785 if (Info->hasWorkGroupIDZ()) {
786 unsigned Reg = Info->addWorkGroupIDZ();
787 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
788 CCInfo.AllocateReg(Reg);
791 if (Info->hasWorkGroupInfo()) {
792 unsigned Reg = Info->addWorkGroupInfo();
793 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
794 CCInfo.AllocateReg(Reg);
797 if (Info->hasPrivateSegmentWaveByteOffset()) {
798 // Scratch wave offset passed in system SGPR.
799 unsigned PrivateSegmentWaveByteOffsetReg
800 = Info->addPrivateSegmentWaveByteOffset();
802 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
803 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
806 // Now that we've figured out where the scratch register inputs are, see if
807 // should reserve the arguments and use them directly.
809 bool HasStackObjects = MF.getFrameInfo()->hasStackObjects();
811 if (ST.isAmdHsaOS()) {
812 // TODO: Assume we will spill without optimizations.
813 if (HasStackObjects) {
814 // If we have stack objects, we unquestionably need the private buffer
815 // resource. For the HSA ABI, this will be the first 4 user SGPR
816 // inputs. We can reserve those and use them directly.
818 unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
819 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
820 Info->setScratchRSrcReg(PrivateSegmentBufferReg);
822 unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
823 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
824 Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
826 unsigned ReservedBufferReg
827 = TRI->reservedPrivateSegmentBufferReg(MF);
828 unsigned ReservedOffsetReg
829 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
831 // We tentatively reserve the last registers (skipping the last two
832 // which may contain VCC). After register allocation, we'll replace
833 // these with the ones immediately after those which were really
834 // allocated. In the prologue copies will be inserted from the argument
835 // to these reserved registers.
836 Info->setScratchRSrcReg(ReservedBufferReg);
837 Info->setScratchWaveOffsetReg(ReservedOffsetReg);
840 unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
842 // Without HSA, relocations are used for the scratch pointer and the
843 // buffer resource setup is always inserted in the prologue. Scratch wave
844 // offset is still in an input SGPR.
845 Info->setScratchRSrcReg(ReservedBufferReg);
847 if (HasStackObjects) {
848 unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
849 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
850 Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
852 unsigned ReservedOffsetReg
853 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
854 Info->setScratchWaveOffsetReg(ReservedOffsetReg);
858 if (Info->hasWorkItemIDX()) {
859 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
860 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
861 CCInfo.AllocateReg(Reg);
863 llvm_unreachable("workitem id x should always be enabled");
865 if (Info->hasWorkItemIDY()) {
866 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
867 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
868 CCInfo.AllocateReg(Reg);
871 if (Info->hasWorkItemIDZ()) {
872 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
873 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
874 CCInfo.AllocateReg(Reg);
880 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
883 SDValue SITargetLowering::LowerReturn(SDValue Chain,
884 CallingConv::ID CallConv,
886 const SmallVectorImpl<ISD::OutputArg> &Outs,
887 const SmallVectorImpl<SDValue> &OutVals,
888 SDLoc DL, SelectionDAG &DAG) const {
889 MachineFunction &MF = DAG.getMachineFunction();
890 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
892 if (Info->getShaderType() == ShaderType::COMPUTE)
893 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
896 Info->setIfReturnsVoid(Outs.size() == 0);
898 SmallVector<ISD::OutputArg, 48> Splits;
899 SmallVector<SDValue, 48> SplitVals;
901 // Split vectors into their elements.
902 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
903 const ISD::OutputArg &Out = Outs[i];
905 if (Out.VT.isVector()) {
906 MVT VT = Out.VT.getVectorElementType();
907 ISD::OutputArg NewOut = Out;
908 NewOut.Flags.setSplit();
911 // We want the original number of vector elements here, e.g.
912 // three or five, not four or eight.
913 unsigned NumElements = Out.ArgVT.getVectorNumElements();
915 for (unsigned j = 0; j != NumElements; ++j) {
916 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
917 DAG.getConstant(j, DL, MVT::i32));
918 SplitVals.push_back(Elem);
919 Splits.push_back(NewOut);
920 NewOut.PartOffset += NewOut.VT.getStoreSize();
923 SplitVals.push_back(OutVals[i]);
924 Splits.push_back(Out);
928 // CCValAssign - represent the assignment of the return value to a location.
929 SmallVector<CCValAssign, 48> RVLocs;
931 // CCState - Info about the registers and stack slots.
932 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
935 // Analyze outgoing return values.
936 AnalyzeReturn(CCInfo, Splits);
939 SmallVector<SDValue, 48> RetOps;
940 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
942 // Copy the result values into the output registers.
943 for (unsigned i = 0, realRVLocIdx = 0;
945 ++i, ++realRVLocIdx) {
946 CCValAssign &VA = RVLocs[i];
947 assert(VA.isRegLoc() && "Can only return in registers!");
949 SDValue Arg = SplitVals[realRVLocIdx];
951 // Copied from other backends.
952 switch (VA.getLocInfo()) {
953 default: llvm_unreachable("Unknown loc info!");
954 case CCValAssign::Full:
956 case CCValAssign::BCvt:
957 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
961 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
962 Flag = Chain.getValue(1);
963 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
966 // Update chain and glue.
969 RetOps.push_back(Flag);
971 return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, RetOps);
974 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
975 MachineInstr * MI, MachineBasicBlock * BB) const {
977 switch (MI->getOpcode()) {
979 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
986 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
987 // This currently forces unfolding various combinations of fsub into fma with
988 // free fneg'd operands. As long as we have fast FMA (controlled by
989 // isFMAFasterThanFMulAndFAdd), we should perform these.
991 // When fma is quarter rate, for f64 where add / sub are at best half rate,
992 // most of these combines appear to be cycle neutral but save on instruction
993 // count / code size.
997 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
999 if (!VT.isVector()) {
1002 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
1005 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
1009 // Answering this is somewhat tricky and depends on the specific device which
1010 // have different rates for fma or all f64 operations.
1012 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
1013 // regardless of which device (although the number of cycles differs between
1014 // devices), so it is always profitable for f64.
1016 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
1017 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
1018 // which we can always do even without fused FP ops since it returns the same
1019 // result as the separate operations and since it is always full
1020 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
1021 // however does not support denormals, so we do report fma as faster if we have
1022 // a fast fma device and require denormals.
1024 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
1025 VT = VT.getScalarType();
1030 switch (VT.getSimpleVT().SimpleTy) {
1032 // This is as fast on some subtargets. However, we always have full rate f32
1033 // mad available which returns the same result as the separate operations
1034 // which we should prefer over fma. We can't use this if we want to support
1035 // denormals, so only report this in these cases.
1036 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
1046 //===----------------------------------------------------------------------===//
1047 // Custom DAG Lowering Operations
1048 //===----------------------------------------------------------------------===//
1050 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1051 switch (Op.getOpcode()) {
1052 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1053 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
1054 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1056 SDValue Result = LowerLOAD(Op, DAG);
1057 assert((!Result.getNode() ||
1058 Result.getNode()->getNumValues() == 2) &&
1059 "Load should return a value and a chain");
1065 return LowerTrig(Op, DAG);
1066 case ISD::SELECT: return LowerSELECT(Op, DAG);
1067 case ISD::FDIV: return LowerFDIV(Op, DAG);
1068 case ISD::STORE: return LowerSTORE(Op, DAG);
1069 case ISD::GlobalAddress: {
1070 MachineFunction &MF = DAG.getMachineFunction();
1071 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1072 return LowerGlobalAddress(MFI, Op, DAG);
1074 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1075 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
1080 /// \brief Helper function for LowerBRCOND
1081 static SDNode *findUser(SDValue Value, unsigned Opcode) {
1083 SDNode *Parent = Value.getNode();
1084 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
1087 if (I.getUse().get() != Value)
1090 if (I->getOpcode() == Opcode)
1096 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
1099 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
1100 unsigned FrameIndex = FINode->getIndex();
1102 // A FrameIndex node represents a 32-bit offset into scratch memory. If
1103 // the high bit of a frame index offset were to be set, this would mean
1104 // that it represented an offset of ~2GB * 64 = ~128GB from the start of the
1105 // scratch buffer, with 64 being the number of threads per wave.
1107 // If we know the machine uses less than 128GB of scratch, then we can
1108 // amrk the high bit of the FrameIndex node as known zero,
1109 // which is important, because it means in most situations we can
1110 // prove that values derived from FrameIndex nodes are non-negative.
1111 // This enables us to take advantage of more addressing modes when
1112 // accessing scratch buffers, since for scratch reads/writes, the register
1113 // offset must always be positive.
1115 SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
1116 if (Subtarget->enableHugeScratchBuffer())
1119 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
1120 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), 31)));
1123 /// This transforms the control flow intrinsics to get the branch destination as
1124 /// last parameter, also switches branch target with BR if the need arise
1125 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
1126 SelectionDAG &DAG) const {
1130 SDNode *Intr = BRCOND.getOperand(1).getNode();
1131 SDValue Target = BRCOND.getOperand(2);
1132 SDNode *BR = nullptr;
1134 if (Intr->getOpcode() == ISD::SETCC) {
1135 // As long as we negate the condition everything is fine
1136 SDNode *SetCC = Intr;
1137 assert(SetCC->getConstantOperandVal(1) == 1);
1138 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
1140 Intr = SetCC->getOperand(0).getNode();
1143 // Get the target from BR if we don't negate the condition
1144 BR = findUser(BRCOND, ISD::BR);
1145 Target = BR->getOperand(1);
1148 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
1150 // Build the result and
1151 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
1153 // operands of the new intrinsic call
1154 SmallVector<SDValue, 4> Ops;
1155 Ops.push_back(BRCOND.getOperand(0));
1156 Ops.append(Intr->op_begin() + 1, Intr->op_end());
1157 Ops.push_back(Target);
1159 // build the new intrinsic call
1160 SDNode *Result = DAG.getNode(
1161 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
1162 DAG.getVTList(Res), Ops).getNode();
1165 // Give the branch instruction our target
1168 BRCOND.getOperand(2)
1170 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
1171 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
1172 BR = NewBR.getNode();
1175 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
1177 // Copy the intrinsic results to registers
1178 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
1179 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
1183 Chain = DAG.getCopyToReg(
1185 CopyToReg->getOperand(1),
1186 SDValue(Result, i - 1),
1189 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
1192 // Remove the old intrinsic from the chain
1193 DAG.ReplaceAllUsesOfValueWith(
1194 SDValue(Intr, Intr->getNumValues() - 1),
1195 Intr->getOperand(0));
1200 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
1202 SelectionDAG &DAG) const {
1203 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
1205 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1206 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
1209 const GlobalValue *GV = GSD->getGlobal();
1210 MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
1212 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
1213 return DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT, GA);
1216 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
1218 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
1219 // so we will end up with redundant moves to m0.
1221 // We can't use S_MOV_B32, because there is no way to specify m0 as the
1222 // destination register.
1224 // We have to use them both. Machine cse will combine all the S_MOV_B32
1225 // instructions and the register coalescer eliminate the extra copies.
1226 SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
1227 return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
1228 SDValue(M0, 0), SDValue()); // Glue
1229 // A Null SDValue creates
1233 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
1236 unsigned Offset) const {
1238 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
1239 DAG.getEntryNode(), Offset, false);
1240 // The local size values will have the hi 16-bits as zero.
1241 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
1242 DAG.getValueType(VT));
1245 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1246 SelectionDAG &DAG) const {
1247 MachineFunction &MF = DAG.getMachineFunction();
1248 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
1249 const SIRegisterInfo *TRI =
1250 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
1252 EVT VT = Op.getValueType();
1254 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1256 // TODO: Should this propagate fast-math-flags?
1258 switch (IntrinsicID) {
1259 case Intrinsic::amdgcn_dispatch_ptr:
1260 if (!Subtarget->isAmdHsaOS()) {
1261 DiagnosticInfoUnsupported BadIntrin(*MF.getFunction(),
1262 "hsa intrinsic without hsa target");
1263 DAG.getContext()->diagnose(BadIntrin);
1264 return DAG.getUNDEF(VT);
1267 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
1268 TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_PTR), VT);
1270 case Intrinsic::r600_read_ngroups_x:
1271 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1272 SI::KernelInputOffsets::NGROUPS_X, false);
1273 case Intrinsic::r600_read_ngroups_y:
1274 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1275 SI::KernelInputOffsets::NGROUPS_Y, false);
1276 case Intrinsic::r600_read_ngroups_z:
1277 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1278 SI::KernelInputOffsets::NGROUPS_Z, false);
1279 case Intrinsic::r600_read_global_size_x:
1280 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1281 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
1282 case Intrinsic::r600_read_global_size_y:
1283 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1284 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
1285 case Intrinsic::r600_read_global_size_z:
1286 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1287 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
1288 case Intrinsic::r600_read_local_size_x:
1289 return lowerImplicitZextParam(DAG, Op, MVT::i16,
1290 SI::KernelInputOffsets::LOCAL_SIZE_X);
1291 case Intrinsic::r600_read_local_size_y:
1292 return lowerImplicitZextParam(DAG, Op, MVT::i16,
1293 SI::KernelInputOffsets::LOCAL_SIZE_Y);
1294 case Intrinsic::r600_read_local_size_z:
1295 return lowerImplicitZextParam(DAG, Op, MVT::i16,
1296 SI::KernelInputOffsets::LOCAL_SIZE_Z);
1297 case Intrinsic::AMDGPU_read_workdim:
1298 // Really only 2 bits.
1299 return lowerImplicitZextParam(DAG, Op, MVT::i8,
1300 getImplicitParameterOffset(MFI, GRID_DIM));
1301 case Intrinsic::r600_read_tgid_x:
1302 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1303 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
1304 case Intrinsic::r600_read_tgid_y:
1305 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1306 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
1307 case Intrinsic::r600_read_tgid_z:
1308 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1309 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
1310 case Intrinsic::r600_read_tidig_x:
1311 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1312 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
1313 case Intrinsic::r600_read_tidig_y:
1314 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1315 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
1316 case Intrinsic::r600_read_tidig_z:
1317 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1318 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
1319 case AMDGPUIntrinsic::SI_load_const: {
1325 MachineMemOperand *MMO = MF.getMachineMemOperand(
1326 MachinePointerInfo(),
1327 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1328 VT.getStoreSize(), 4);
1329 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1330 Op->getVTList(), Ops, VT, MMO);
1332 case AMDGPUIntrinsic::SI_sample:
1333 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1334 case AMDGPUIntrinsic::SI_sampleb:
1335 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1336 case AMDGPUIntrinsic::SI_sampled:
1337 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1338 case AMDGPUIntrinsic::SI_samplel:
1339 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1340 case AMDGPUIntrinsic::SI_vs_load_input:
1341 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1346 case AMDGPUIntrinsic::AMDGPU_fract:
1347 case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1348 return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1349 DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1350 case AMDGPUIntrinsic::SI_fs_constant: {
1351 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1352 SDValue Glue = M0.getValue(1);
1353 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1354 DAG.getConstant(2, DL, MVT::i32), // P0
1355 Op.getOperand(1), Op.getOperand(2), Glue);
1357 case AMDGPUIntrinsic::SI_packf16:
1358 if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
1359 return DAG.getUNDEF(MVT::i32);
1361 case AMDGPUIntrinsic::SI_fs_interp: {
1362 SDValue IJ = Op.getOperand(4);
1363 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1364 DAG.getConstant(0, DL, MVT::i32));
1365 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1366 DAG.getConstant(1, DL, MVT::i32));
1367 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1368 SDValue Glue = M0.getValue(1);
1369 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1370 DAG.getVTList(MVT::f32, MVT::Glue),
1371 I, Op.getOperand(1), Op.getOperand(2), Glue);
1372 Glue = SDValue(P1.getNode(), 1);
1373 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1374 Op.getOperand(1), Op.getOperand(2), Glue);
1376 case Intrinsic::amdgcn_interp_p1: {
1377 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
1378 SDValue Glue = M0.getValue(1);
1379 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
1380 Op.getOperand(2), Op.getOperand(3), Glue);
1382 case Intrinsic::amdgcn_interp_p2: {
1383 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
1384 SDValue Glue = SDValue(M0.getNode(), 1);
1385 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
1386 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
1390 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1394 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1395 SelectionDAG &DAG) const {
1396 MachineFunction &MF = DAG.getMachineFunction();
1398 SDValue Chain = Op.getOperand(0);
1399 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1401 switch (IntrinsicID) {
1402 case AMDGPUIntrinsic::SI_sendmsg: {
1403 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1404 SDValue Glue = Chain.getValue(1);
1405 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1406 Op.getOperand(2), Glue);
1408 case AMDGPUIntrinsic::SI_tbuffer_store: {
1426 EVT VT = Op.getOperand(3).getValueType();
1428 MachineMemOperand *MMO = MF.getMachineMemOperand(
1429 MachinePointerInfo(),
1430 MachineMemOperand::MOStore,
1431 VT.getStoreSize(), 4);
1432 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1433 Op->getVTList(), Ops, VT, MMO);
1440 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1442 LoadSDNode *Load = cast<LoadSDNode>(Op);
1444 if (Op.getValueType().isVector()) {
1445 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1446 "Custom lowering for non-i32 vectors hasn't been implemented.");
1447 unsigned NumElements = Op.getValueType().getVectorNumElements();
1448 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1450 switch (Load->getAddressSpace()) {
1452 case AMDGPUAS::CONSTANT_ADDRESS:
1453 if (isMemOpUniform(Load))
1455 // Non-uniform loads will be selected to MUBUF instructions, so they
1456 // have the same legalization requires ments as global and private
1460 case AMDGPUAS::GLOBAL_ADDRESS:
1461 case AMDGPUAS::PRIVATE_ADDRESS:
1462 if (NumElements >= 8)
1463 return SplitVectorLoad(Op, DAG);
1465 // v4 loads are supported for private and global memory.
1466 if (NumElements <= 4)
1469 case AMDGPUAS::LOCAL_ADDRESS:
1470 // If properly aligned, if we split we might be able to use ds_read_b64.
1471 return SplitVectorLoad(Op, DAG);
1475 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1478 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1480 SelectionDAG &DAG) const {
1481 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1487 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1488 if (Op.getValueType() != MVT::i64)
1492 SDValue Cond = Op.getOperand(0);
1494 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1495 SDValue One = DAG.getConstant(1, DL, MVT::i32);
1497 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1498 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1500 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1501 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1503 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1505 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1506 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1508 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1510 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1511 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1514 // Catch division cases where we can use shortcuts with rcp and rsq
1516 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1518 SDValue LHS = Op.getOperand(0);
1519 SDValue RHS = Op.getOperand(1);
1520 EVT VT = Op.getValueType();
1521 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1523 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1524 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1525 CLHS->isExactlyValue(1.0)) {
1526 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1527 // the CI documentation has a worst case error of 1 ulp.
1528 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1529 // use it as long as we aren't trying to use denormals.
1531 // 1.0 / sqrt(x) -> rsq(x)
1533 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1534 // error seems really high at 2^29 ULP.
1535 if (RHS.getOpcode() == ISD::FSQRT)
1536 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1538 // 1.0 / x -> rcp(x)
1539 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1544 // Turn into multiply by the reciprocal.
1545 // x / y -> x * (1.0 / y)
1547 Flags.setUnsafeAlgebra(true);
1548 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1549 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
1555 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1556 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1557 if (FastLowered.getNode())
1560 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1561 // selection error for now rather than do something incorrect.
1562 if (Subtarget->hasFP32Denormals())
1566 SDValue LHS = Op.getOperand(0);
1567 SDValue RHS = Op.getOperand(1);
1569 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1571 const APFloat K0Val(BitsToFloat(0x6f800000));
1572 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1574 const APFloat K1Val(BitsToFloat(0x2f800000));
1575 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1577 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1580 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1582 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1584 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1586 // TODO: Should this propagate fast-math-flags?
1588 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1590 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1592 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1594 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1597 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1598 if (DAG.getTarget().Options.UnsafeFPMath)
1599 return LowerFastFDIV(Op, DAG);
1602 SDValue X = Op.getOperand(0);
1603 SDValue Y = Op.getOperand(1);
1605 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1607 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1609 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1611 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1613 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1615 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1617 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1619 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1621 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1623 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1624 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1626 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1627 NegDivScale0, Mul, DivScale1);
1631 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1632 // Workaround a hardware bug on SI where the condition output from div_scale
1635 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1637 // Figure out if the scale to use for div_fmas.
1638 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1639 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1640 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1641 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1643 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1644 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1647 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1649 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1651 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1652 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1653 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1655 Scale = DivScale1.getValue(1);
1658 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1659 Fma4, Fma3, Mul, Scale);
1661 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1664 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1665 EVT VT = Op.getValueType();
1668 return LowerFDIV32(Op, DAG);
1671 return LowerFDIV64(Op, DAG);
1673 llvm_unreachable("Unexpected type for fdiv");
1676 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1678 StoreSDNode *Store = cast<StoreSDNode>(Op);
1679 EVT VT = Store->getMemoryVT();
1681 // These stores are legal.
1682 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1683 if (VT.isVector() && VT.getVectorNumElements() > 4)
1684 return ScalarizeVectorStore(Op, DAG);
1688 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1692 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1693 return SplitVectorStore(Op, DAG);
1696 return DAG.getTruncStore(Store->getChain(), DL,
1697 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1698 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1703 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1705 EVT VT = Op.getValueType();
1706 SDValue Arg = Op.getOperand(0);
1707 // TODO: Should this propagate fast-math-flags?
1708 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1709 DAG.getNode(ISD::FMUL, DL, VT, Arg,
1710 DAG.getConstantFP(0.5/M_PI, DL,
1713 switch (Op.getOpcode()) {
1715 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1717 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1719 llvm_unreachable("Wrong trig opcode");
1723 //===----------------------------------------------------------------------===//
1724 // Custom DAG optimizations
1725 //===----------------------------------------------------------------------===//
1727 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1728 DAGCombinerInfo &DCI) const {
1729 EVT VT = N->getValueType(0);
1730 EVT ScalarVT = VT.getScalarType();
1731 if (ScalarVT != MVT::f32)
1734 SelectionDAG &DAG = DCI.DAG;
1737 SDValue Src = N->getOperand(0);
1738 EVT SrcVT = Src.getValueType();
1740 // TODO: We could try to match extracting the higher bytes, which would be
1741 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1742 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1743 // about in practice.
1744 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1745 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1746 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1747 DCI.AddToWorklist(Cvt.getNode());
1752 // We are primarily trying to catch operations on illegal vector types
1753 // before they are expanded.
1754 // For scalars, we can use the more flexible method of checking masked bits
1755 // after legalization.
1756 if (!DCI.isBeforeLegalize() ||
1757 !SrcVT.isVector() ||
1758 SrcVT.getVectorElementType() != MVT::i8) {
1762 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1764 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1766 unsigned NElts = SrcVT.getVectorNumElements();
1767 if (!SrcVT.isSimple() && NElts != 3)
1770 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1771 // prevent a mess from expanding to v4i32 and repacking.
1772 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1773 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1774 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1775 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1776 LoadSDNode *Load = cast<LoadSDNode>(Src);
1778 unsigned AS = Load->getAddressSpace();
1779 unsigned Align = Load->getAlignment();
1780 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1781 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
1783 // Don't try to replace the load if we have to expand it due to alignment
1784 // problems. Otherwise we will end up scalarizing the load, and trying to
1785 // repack into the vector for no real reason.
1786 if (Align < ABIAlignment &&
1787 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1791 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1795 Load->getMemOperand());
1797 // Make sure successors of the original load stay after it by updating
1798 // them to use the new Chain.
1799 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1801 SmallVector<SDValue, 4> Elts;
1802 if (RegVT.isVector())
1803 DAG.ExtractVectorElements(NewLoad, Elts);
1805 Elts.push_back(NewLoad);
1807 SmallVector<SDValue, 4> Ops;
1809 unsigned EltIdx = 0;
1810 for (SDValue Elt : Elts) {
1811 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1812 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1813 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1814 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1815 DCI.AddToWorklist(Cvt.getNode());
1822 assert(Ops.size() == NElts);
1824 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1830 /// \brief Return true if the given offset Size in bytes can be folded into
1831 /// the immediate offsets of a memory instruction for the given address space.
1832 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1833 const AMDGPUSubtarget &STI) {
1835 case AMDGPUAS::GLOBAL_ADDRESS: {
1836 // MUBUF instructions a 12-bit offset in bytes.
1837 return isUInt<12>(OffsetSize);
1839 case AMDGPUAS::CONSTANT_ADDRESS: {
1840 // SMRD instructions have an 8-bit offset in dwords on SI and
1841 // a 20-bit offset in bytes on VI.
1842 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1843 return isUInt<20>(OffsetSize);
1845 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1847 case AMDGPUAS::LOCAL_ADDRESS:
1848 case AMDGPUAS::REGION_ADDRESS: {
1849 // The single offset versions have a 16-bit offset in bytes.
1850 return isUInt<16>(OffsetSize);
1852 case AMDGPUAS::PRIVATE_ADDRESS:
1853 // Indirect register addressing does not use any offsets.
1859 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1861 // This is a variant of
1862 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1864 // The normal DAG combiner will do this, but only if the add has one use since
1865 // that would increase the number of instructions.
1867 // This prevents us from seeing a constant offset that can be folded into a
1868 // memory instruction's addressing mode. If we know the resulting add offset of
1869 // a pointer can be folded into an addressing offset, we can replace the pointer
1870 // operand with the add of new constant offset. This eliminates one of the uses,
1871 // and may allow the remaining use to also be simplified.
1873 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1875 DAGCombinerInfo &DCI) const {
1876 SDValue N0 = N->getOperand(0);
1877 SDValue N1 = N->getOperand(1);
1879 if (N0.getOpcode() != ISD::ADD)
1882 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1886 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1890 // If the resulting offset is too large, we can't fold it into the addressing
1892 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1893 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1896 SelectionDAG &DAG = DCI.DAG;
1898 EVT VT = N->getValueType(0);
1900 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1901 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1903 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1906 SDValue SITargetLowering::performAndCombine(SDNode *N,
1907 DAGCombinerInfo &DCI) const {
1908 if (DCI.isBeforeLegalize())
1911 SelectionDAG &DAG = DCI.DAG;
1913 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1914 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1915 SDValue LHS = N->getOperand(0);
1916 SDValue RHS = N->getOperand(1);
1918 if (LHS.getOpcode() == ISD::SETCC &&
1919 RHS.getOpcode() == ISD::SETCC) {
1920 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1921 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1923 SDValue X = LHS.getOperand(0);
1924 SDValue Y = RHS.getOperand(0);
1925 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1928 if (LCC == ISD::SETO) {
1929 if (X != LHS.getOperand(1))
1932 if (RCC == ISD::SETUNE) {
1933 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1934 if (!C1 || !C1->isInfinity() || C1->isNegative())
1937 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1938 SIInstrFlags::N_SUBNORMAL |
1939 SIInstrFlags::N_ZERO |
1940 SIInstrFlags::P_ZERO |
1941 SIInstrFlags::P_SUBNORMAL |
1942 SIInstrFlags::P_NORMAL;
1944 static_assert(((~(SIInstrFlags::S_NAN |
1945 SIInstrFlags::Q_NAN |
1946 SIInstrFlags::N_INFINITY |
1947 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1951 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1952 X, DAG.getConstant(Mask, DL, MVT::i32));
1960 SDValue SITargetLowering::performOrCombine(SDNode *N,
1961 DAGCombinerInfo &DCI) const {
1962 SelectionDAG &DAG = DCI.DAG;
1963 SDValue LHS = N->getOperand(0);
1964 SDValue RHS = N->getOperand(1);
1966 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1967 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1968 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1969 SDValue Src = LHS.getOperand(0);
1970 if (Src != RHS.getOperand(0))
1973 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1974 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1978 // Only 10 bits are used.
1979 static const uint32_t MaxMask = 0x3ff;
1981 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1983 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1984 Src, DAG.getConstant(NewMask, DL, MVT::i32));
1990 SDValue SITargetLowering::performClassCombine(SDNode *N,
1991 DAGCombinerInfo &DCI) const {
1992 SelectionDAG &DAG = DCI.DAG;
1993 SDValue Mask = N->getOperand(1);
1995 // fp_class x, 0 -> false
1996 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1997 if (CMask->isNullValue())
1998 return DAG.getConstant(0, SDLoc(N), MVT::i1);
2004 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
2007 return AMDGPUISD::FMAX3;
2009 return AMDGPUISD::SMAX3;
2011 return AMDGPUISD::UMAX3;
2013 return AMDGPUISD::FMIN3;
2015 return AMDGPUISD::SMIN3;
2017 return AMDGPUISD::UMIN3;
2019 llvm_unreachable("Not a min/max opcode");
2023 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
2024 DAGCombinerInfo &DCI) const {
2025 SelectionDAG &DAG = DCI.DAG;
2027 unsigned Opc = N->getOpcode();
2028 SDValue Op0 = N->getOperand(0);
2029 SDValue Op1 = N->getOperand(1);
2031 // Only do this if the inner op has one use since this will just increases
2032 // register pressure for no benefit.
2034 // max(max(a, b), c)
2035 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
2037 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
2045 // max(a, max(b, c))
2046 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
2048 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
2059 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
2060 DAGCombinerInfo &DCI) const {
2061 SelectionDAG &DAG = DCI.DAG;
2064 SDValue LHS = N->getOperand(0);
2065 SDValue RHS = N->getOperand(1);
2066 EVT VT = LHS.getValueType();
2068 if (VT != MVT::f32 && VT != MVT::f64)
2071 // Match isinf pattern
2072 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
2073 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2074 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
2075 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
2079 const APFloat &APF = CRHS->getValueAPF();
2080 if (APF.isInfinity() && !APF.isNegative()) {
2081 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
2082 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
2083 DAG.getConstant(Mask, SL, MVT::i32));
2090 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
2091 DAGCombinerInfo &DCI) const {
2092 SelectionDAG &DAG = DCI.DAG;
2095 switch (N->getOpcode()) {
2097 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
2099 return performSetCCCombine(N, DCI);
2100 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
2106 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
2107 N->getValueType(0) != MVT::f64 &&
2108 getTargetMachine().getOptLevel() > CodeGenOpt::None)
2109 return performMin3Max3Combine(N, DCI);
2113 case AMDGPUISD::CVT_F32_UBYTE0:
2114 case AMDGPUISD::CVT_F32_UBYTE1:
2115 case AMDGPUISD::CVT_F32_UBYTE2:
2116 case AMDGPUISD::CVT_F32_UBYTE3: {
2117 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
2119 SDValue Src = N->getOperand(0);
2120 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
2122 APInt KnownZero, KnownOne;
2123 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2124 !DCI.isBeforeLegalizeOps());
2125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2126 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
2127 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
2128 DCI.CommitTargetLoweringOpt(TLO);
2134 case ISD::UINT_TO_FP: {
2135 return performUCharToFloatCombine(N, DCI);
2138 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2141 EVT VT = N->getValueType(0);
2145 // Only do this if we are not trying to support denormals. v_mad_f32 does
2146 // not support denormals ever.
2147 if (Subtarget->hasFP32Denormals())
2150 SDValue LHS = N->getOperand(0);
2151 SDValue RHS = N->getOperand(1);
2153 // These should really be instruction patterns, but writing patterns with
2154 // source modiifiers is a pain.
2156 // fadd (fadd (a, a), b) -> mad 2.0, a, b
2157 if (LHS.getOpcode() == ISD::FADD) {
2158 SDValue A = LHS.getOperand(0);
2159 if (A == LHS.getOperand(1)) {
2160 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2161 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
2165 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
2166 if (RHS.getOpcode() == ISD::FADD) {
2167 SDValue A = RHS.getOperand(0);
2168 if (A == RHS.getOperand(1)) {
2169 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2170 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
2177 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2180 EVT VT = N->getValueType(0);
2182 // Try to get the fneg to fold into the source modifier. This undoes generic
2183 // DAG combines and folds them into the mad.
2185 // Only do this if we are not trying to support denormals. v_mad_f32 does
2186 // not support denormals ever.
2187 if (VT == MVT::f32 &&
2188 !Subtarget->hasFP32Denormals()) {
2189 SDValue LHS = N->getOperand(0);
2190 SDValue RHS = N->getOperand(1);
2191 if (LHS.getOpcode() == ISD::FADD) {
2192 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
2194 SDValue A = LHS.getOperand(0);
2195 if (A == LHS.getOperand(1)) {
2196 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2197 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
2199 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
2203 if (RHS.getOpcode() == ISD::FADD) {
2204 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
2206 SDValue A = RHS.getOperand(0);
2207 if (A == RHS.getOperand(1)) {
2208 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
2209 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
2220 case ISD::ATOMIC_LOAD:
2221 case ISD::ATOMIC_STORE:
2222 case ISD::ATOMIC_CMP_SWAP:
2223 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2224 case ISD::ATOMIC_SWAP:
2225 case ISD::ATOMIC_LOAD_ADD:
2226 case ISD::ATOMIC_LOAD_SUB:
2227 case ISD::ATOMIC_LOAD_AND:
2228 case ISD::ATOMIC_LOAD_OR:
2229 case ISD::ATOMIC_LOAD_XOR:
2230 case ISD::ATOMIC_LOAD_NAND:
2231 case ISD::ATOMIC_LOAD_MIN:
2232 case ISD::ATOMIC_LOAD_MAX:
2233 case ISD::ATOMIC_LOAD_UMIN:
2234 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
2235 if (DCI.isBeforeLegalize())
2238 MemSDNode *MemNode = cast<MemSDNode>(N);
2239 SDValue Ptr = MemNode->getBasePtr();
2241 // TODO: We could also do this for multiplies.
2242 unsigned AS = MemNode->getAddressSpace();
2243 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
2244 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
2246 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
2248 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
2249 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
2255 return performAndCombine(N, DCI);
2257 return performOrCombine(N, DCI);
2258 case AMDGPUISD::FP_CLASS:
2259 return performClassCombine(N, DCI);
2261 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
2264 /// \brief Analyze the possible immediate value Op
2266 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
2267 /// and the immediate value if it's a literal immediate
2268 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
2270 const SIInstrInfo *TII =
2271 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2273 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
2274 if (TII->isInlineConstant(Node->getAPIntValue()))
2277 uint64_t Val = Node->getZExtValue();
2278 return isUInt<32>(Val) ? Val : -1;
2281 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
2282 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
2285 if (Node->getValueType(0) == MVT::f32)
2286 return FloatToBits(Node->getValueAPF().convertToFloat());
2294 /// \brief Helper function for adjustWritemask
2295 static unsigned SubIdx2Lane(unsigned Idx) {
2298 case AMDGPU::sub0: return 0;
2299 case AMDGPU::sub1: return 1;
2300 case AMDGPU::sub2: return 2;
2301 case AMDGPU::sub3: return 3;
2305 /// \brief Adjust the writemask of MIMG instructions
2306 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
2307 SelectionDAG &DAG) const {
2308 SDNode *Users[4] = { };
2310 unsigned OldDmask = Node->getConstantOperandVal(0);
2311 unsigned NewDmask = 0;
2313 // Try to figure out the used register components
2314 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
2317 // Abort if we can't understand the usage
2318 if (!I->isMachineOpcode() ||
2319 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
2322 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
2323 // Note that subregs are packed, i.e. Lane==0 is the first bit set
2324 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
2326 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
2328 // Set which texture component corresponds to the lane.
2330 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
2332 Comp = countTrailingZeros(Dmask);
2333 Dmask &= ~(1 << Comp);
2336 // Abort if we have more than one user per component
2341 NewDmask |= 1 << Comp;
2344 // Abort if there's no change
2345 if (NewDmask == OldDmask)
2348 // Adjust the writemask in the node
2349 std::vector<SDValue> Ops;
2350 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
2351 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
2352 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
2354 // If we only got one lane, replace it with a copy
2355 // (if NewDmask has only one bit set...)
2356 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
2357 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
2359 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
2360 SDLoc(), Users[Lane]->getValueType(0),
2361 SDValue(Node, 0), RC);
2362 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2366 // Update the users of the node with the new indices
2367 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2369 SDNode *User = Users[i];
2373 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2374 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2378 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2379 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2380 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2385 static bool isFrameIndexOp(SDValue Op) {
2386 if (Op.getOpcode() == ISD::AssertZext)
2387 Op = Op.getOperand(0);
2389 return isa<FrameIndexSDNode>(Op);
2392 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2393 /// with frame index operands.
2394 /// LLVM assumes that inputs are to these instructions are registers.
2395 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2396 SelectionDAG &DAG) const {
2398 SmallVector<SDValue, 8> Ops;
2399 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2400 if (!isFrameIndexOp(Node->getOperand(i))) {
2401 Ops.push_back(Node->getOperand(i));
2406 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2407 Node->getOperand(i).getValueType(),
2408 Node->getOperand(i)), 0));
2411 DAG.UpdateNodeOperands(Node, Ops);
2414 /// \brief Fold the instructions after selecting them.
2415 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2416 SelectionDAG &DAG) const {
2417 const SIInstrInfo *TII =
2418 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2420 if (TII->isMIMG(Node->getMachineOpcode()))
2421 adjustWritemask(Node, DAG);
2423 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2424 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2425 legalizeTargetIndependentNode(Node, DAG);
2431 /// \brief Assign the register class depending on the number of
2432 /// bits set in the writemask
2433 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2434 SDNode *Node) const {
2435 const SIInstrInfo *TII =
2436 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2438 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2440 if (TII->isVOP3(MI->getOpcode())) {
2441 // Make sure constant bus requirements are respected.
2442 TII->legalizeOperandsVOP3(MRI, MI);
2446 if (TII->isMIMG(*MI)) {
2447 unsigned VReg = MI->getOperand(0).getReg();
2448 unsigned Writemask = MI->getOperand(1).getImm();
2449 unsigned BitsSet = 0;
2450 for (unsigned i = 0; i < 4; ++i)
2451 BitsSet += Writemask & (1 << i) ? 1 : 0;
2453 const TargetRegisterClass *RC;
2456 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
2457 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2458 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2461 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2462 MI->setDesc(TII->get(NewOpcode));
2463 MRI.setRegClass(VReg, RC);
2467 // Replace unused atomics with the no return version.
2468 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2469 if (NoRetAtomicOp != -1) {
2470 if (!Node->hasAnyUseOfValue(0)) {
2471 MI->setDesc(TII->get(NoRetAtomicOp));
2472 MI->RemoveOperand(0);
2479 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2480 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2481 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2484 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2486 SDValue Ptr) const {
2487 const SIInstrInfo *TII =
2488 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2490 // Build the half of the subregister with the constants before building the
2491 // full 128-bit register. If we are building multiple resource descriptors,
2492 // this will allow CSEing of the 2-component register.
2493 const SDValue Ops0[] = {
2494 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2495 buildSMovImm32(DAG, DL, 0),
2496 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2497 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2498 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2501 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2502 MVT::v2i32, Ops0), 0);
2504 // Combine the constants and the pointer.
2505 const SDValue Ops1[] = {
2506 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2508 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2510 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2513 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2516 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2517 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
2518 /// of the resource descriptor) to create an offset, which is added to
2519 /// the resource pointer.
2520 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2523 uint32_t RsrcDword1,
2524 uint64_t RsrcDword2And3) const {
2525 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2526 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2528 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2529 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2533 SDValue DataLo = buildSMovImm32(DAG, DL,
2534 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2535 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2537 const SDValue Ops[] = {
2538 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2540 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2542 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2544 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2546 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2549 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2552 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2553 const TargetRegisterClass *RC,
2554 unsigned Reg, EVT VT) const {
2555 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2557 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2558 cast<RegisterSDNode>(VReg)->getReg(), VT);
2561 //===----------------------------------------------------------------------===//
2562 // SI Inline Assembly Support
2563 //===----------------------------------------------------------------------===//
2565 std::pair<unsigned, const TargetRegisterClass *>
2566 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2567 StringRef Constraint,
2570 if (Constraint.size() == 1) {
2571 switch (Constraint[0]) {
2574 switch (VT.getSizeInBits()) {
2576 return std::make_pair(0U, nullptr);
2578 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2580 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2582 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
2584 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
2588 switch (VT.getSizeInBits()) {
2590 return std::make_pair(0U, nullptr);
2592 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
2594 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
2596 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
2598 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
2600 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
2602 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
2607 if (Constraint.size() > 1) {
2608 const TargetRegisterClass *RC = nullptr;
2609 if (Constraint[1] == 'v') {
2610 RC = &AMDGPU::VGPR_32RegClass;
2611 } else if (Constraint[1] == 's') {
2612 RC = &AMDGPU::SGPR_32RegClass;
2617 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2618 if (!Failed && Idx < RC->getNumRegs())
2619 return std::make_pair(RC->getRegister(Idx), RC);
2622 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2625 SITargetLowering::ConstraintType
2626 SITargetLowering::getConstraintType(StringRef Constraint) const {
2627 if (Constraint.size() == 1) {
2628 switch (Constraint[0]) {
2632 return C_RegisterClass;
2635 return TargetLowering::getConstraintType(Constraint);