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 "AMDGPUIntrinsicInfo.h"
24 #include "AMDGPUSubtarget.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/ADT/SmallString.h"
38 SITargetLowering::SITargetLowering(TargetMachine &TM,
39 const AMDGPUSubtarget &STI)
40 : AMDGPUTargetLowering(TM, STI) {
41 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
42 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
44 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
45 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
47 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
48 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
50 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
51 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
52 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
54 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
55 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
57 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
58 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
60 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
61 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
63 computeRegisterProperties();
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
68 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
70 setOperationAction(ISD::ADD, MVT::i32, Legal);
71 setOperationAction(ISD::ADDC, MVT::i32, Legal);
72 setOperationAction(ISD::ADDE, MVT::i32, Legal);
73 setOperationAction(ISD::SUBC, MVT::i32, Legal);
74 setOperationAction(ISD::SUBE, MVT::i32, Legal);
76 setOperationAction(ISD::FSIN, MVT::f32, Custom);
77 setOperationAction(ISD::FCOS, MVT::f32, Custom);
79 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
80 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
81 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
82 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
84 // We need to custom lower vector stores from local memory
85 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
86 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
87 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
89 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
90 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
92 setOperationAction(ISD::STORE, MVT::i1, Custom);
93 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
95 setOperationAction(ISD::SELECT, MVT::i64, Custom);
96 setOperationAction(ISD::SELECT, MVT::f64, Promote);
97 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
99 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
100 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
101 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
102 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
104 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
105 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
107 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
109 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
110 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
111 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
114 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
115 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
124 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
125 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
129 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
130 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
132 for (MVT VT : MVT::integer_valuetypes()) {
136 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
137 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
138 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
139 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
141 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
142 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
143 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
144 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
146 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
147 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
148 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
149 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
152 for (MVT VT : MVT::integer_vector_valuetypes()) {
153 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
154 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
157 for (MVT VT : MVT::fp_valuetypes())
158 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
160 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
161 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
162 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
163 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
165 setOperationAction(ISD::LOAD, MVT::i1, Custom);
167 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
168 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
169 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
171 // These should use UDIVREM, so set them to expand
172 setOperationAction(ISD::UDIV, MVT::i64, Expand);
173 setOperationAction(ISD::UREM, MVT::i64, Expand);
175 // We only support LOAD/STORE and vector manipulation ops for vectors
176 // with > 4 elements.
178 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
181 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
182 setOperationAction(ISD::SELECT, MVT::i1, Promote);
184 for (MVT VT : VecTypes) {
185 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
189 case ISD::BUILD_VECTOR:
191 case ISD::EXTRACT_VECTOR_ELT:
192 case ISD::INSERT_VECTOR_ELT:
193 case ISD::INSERT_SUBVECTOR:
194 case ISD::EXTRACT_SUBVECTOR:
196 case ISD::CONCAT_VECTORS:
197 setOperationAction(Op, VT, Custom);
200 setOperationAction(Op, VT, Expand);
206 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
207 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
208 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
209 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
210 setOperationAction(ISD::FRINT, MVT::f64, Legal);
213 setOperationAction(ISD::FDIV, MVT::f32, Custom);
215 setTargetDAGCombine(ISD::FADD);
216 setTargetDAGCombine(ISD::FSUB);
217 setTargetDAGCombine(ISD::FMINNUM);
218 setTargetDAGCombine(ISD::FMAXNUM);
219 setTargetDAGCombine(ISD::SELECT_CC);
220 setTargetDAGCombine(ISD::SETCC);
221 setTargetDAGCombine(ISD::AND);
222 setTargetDAGCombine(ISD::OR);
223 setTargetDAGCombine(ISD::UINT_TO_FP);
225 // All memory operations. Some folding on the pointer operand is done to help
226 // matching the constant offsets in the addressing modes.
227 setTargetDAGCombine(ISD::LOAD);
228 setTargetDAGCombine(ISD::STORE);
229 setTargetDAGCombine(ISD::ATOMIC_LOAD);
230 setTargetDAGCombine(ISD::ATOMIC_STORE);
231 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
232 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
233 setTargetDAGCombine(ISD::ATOMIC_SWAP);
234 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
235 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
243 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
245 setSchedulingPreference(Sched::RegPressure);
248 //===----------------------------------------------------------------------===//
249 // TargetLowering queries
250 //===----------------------------------------------------------------------===//
252 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
254 // SI has some legal vector types, but no legal vector operations. Say no
255 // shuffles are legal in order to prefer scalarizing some vector operations.
259 // FIXME: This really needs an address space argument. The immediate offset
260 // size is different for different sets of memory instruction sets.
262 // The single offset DS instructions have a 16-bit unsigned byte offset.
264 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
265 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
266 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
268 // SMRD instructions have an 8-bit, dword offset.
270 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
272 // No global is ever allowed as a base.
276 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
278 if (!isUInt<16>(AM.BaseOffs))
283 case 0: // "r+i" or just "i", depending on HasBaseReg.
286 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
288 // Otherwise we have r+r or r+i.
291 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
295 default: // Don't allow n * r
302 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
305 bool *IsFast) const {
309 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
310 // which isn't a simple VT.
311 if (!VT.isSimple() || VT == MVT::Other)
314 // TODO - CI+ supports unaligned memory accesses, but this requires driver
317 // XXX - The only mention I see of this in the ISA manual is for LDS direct
318 // reads the "byte address and must be dword aligned". Is it also true for the
319 // normal loads and stores?
320 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
321 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
322 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
323 // with adjacent offsets.
324 return Align % 4 == 0;
327 // Smaller than dword value must be aligned.
328 // FIXME: This should be allowed on CI+
329 if (VT.bitsLT(MVT::i32))
332 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
333 // byte-address are ignored, thus forcing Dword alignment.
334 // This applies to private, global, and constant memory.
338 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
341 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
342 unsigned SrcAlign, bool IsMemset,
345 MachineFunction &MF) const {
346 // FIXME: Should account for address space here.
348 // The default fallback uses the private pointer size as a guess for a type to
349 // use. Make sure we switch these to 64-bit accesses.
351 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
354 if (Size >= 8 && DstAlign >= 4)
361 TargetLoweringBase::LegalizeTypeAction
362 SITargetLowering::getPreferredVectorAction(EVT VT) const {
363 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
364 return TypeSplitVector;
366 return TargetLoweringBase::getPreferredVectorAction(VT);
369 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
371 const SIInstrInfo *TII =
372 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
373 return TII->isInlineConstant(Imm);
376 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
377 SDLoc SL, SDValue Chain,
378 unsigned Offset, bool Signed) const {
379 const DataLayout *DL = getDataLayout();
380 MachineFunction &MF = DAG.getMachineFunction();
381 const SIRegisterInfo *TRI =
382 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
383 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
385 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
387 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
388 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
389 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
390 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
391 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
392 DAG.getConstant(Offset, MVT::i64));
393 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
394 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
396 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
397 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
399 true, // isNonTemporal
401 DL->getABITypeAlignment(Ty)); // Alignment
404 SDValue SITargetLowering::LowerFormalArguments(
405 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
406 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
407 SmallVectorImpl<SDValue> &InVals) const {
408 const SIRegisterInfo *TRI =
409 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
411 MachineFunction &MF = DAG.getMachineFunction();
412 FunctionType *FType = MF.getFunction()->getFunctionType();
413 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
415 assert(CallConv == CallingConv::C);
417 SmallVector<ISD::InputArg, 16> Splits;
418 BitVector Skipped(Ins.size());
420 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
421 const ISD::InputArg &Arg = Ins[i];
423 // First check if it's a PS input addr
424 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
425 !Arg.Flags.isByVal()) {
427 assert((PSInputNum <= 15) && "Too many PS inputs!");
430 // We can savely skip PS inputs
436 Info->PSInputAddr |= 1 << PSInputNum++;
439 // Second split vertices into their elements
440 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
441 ISD::InputArg NewArg = Arg;
442 NewArg.Flags.setSplit();
443 NewArg.VT = Arg.VT.getVectorElementType();
445 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
446 // three or five element vertex only needs three or five registers,
447 // NOT four or eigth.
448 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
449 unsigned NumElements = ParamType->getVectorNumElements();
451 for (unsigned j = 0; j != NumElements; ++j) {
452 Splits.push_back(NewArg);
453 NewArg.PartOffset += NewArg.VT.getStoreSize();
456 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
457 Splits.push_back(Arg);
461 SmallVector<CCValAssign, 16> ArgLocs;
462 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
465 // At least one interpolation mode must be enabled or else the GPU will hang.
466 if (Info->getShaderType() == ShaderType::PIXEL &&
467 (Info->PSInputAddr & 0x7F) == 0) {
468 Info->PSInputAddr |= 1;
469 CCInfo.AllocateReg(AMDGPU::VGPR0);
470 CCInfo.AllocateReg(AMDGPU::VGPR1);
473 // The pointer to the list of arguments is stored in SGPR0, SGPR1
474 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
475 if (Info->getShaderType() == ShaderType::COMPUTE) {
476 if (Subtarget->isAmdHsaOS())
477 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
479 Info->NumUserSGPRs = 4;
481 unsigned InputPtrReg =
482 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
483 unsigned InputPtrRegLo =
484 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
485 unsigned InputPtrRegHi =
486 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
488 unsigned ScratchPtrReg =
489 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
490 unsigned ScratchPtrRegLo =
491 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
492 unsigned ScratchPtrRegHi =
493 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
495 CCInfo.AllocateReg(InputPtrRegLo);
496 CCInfo.AllocateReg(InputPtrRegHi);
497 CCInfo.AllocateReg(ScratchPtrRegLo);
498 CCInfo.AllocateReg(ScratchPtrRegHi);
499 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
500 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
503 if (Info->getShaderType() == ShaderType::COMPUTE) {
504 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
508 AnalyzeFormalArguments(CCInfo, Splits);
510 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
512 const ISD::InputArg &Arg = Ins[i];
514 InVals.push_back(DAG.getUNDEF(Arg.VT));
518 CCValAssign &VA = ArgLocs[ArgIdx++];
519 MVT VT = VA.getLocVT();
523 EVT MemVT = Splits[i].VT;
524 const unsigned Offset = 36 + VA.getLocMemOffset();
525 // The first 36 bytes of the input buffer contains information about
526 // thread group and global sizes.
527 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
528 Offset, Ins[i].Flags.isSExt());
530 const PointerType *ParamTy =
531 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
532 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
533 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
534 // On SI local pointers are just offsets into LDS, so they are always
535 // less than 16-bits. On CI and newer they could potentially be
536 // real pointers, so we can't guarantee their size.
537 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
538 DAG.getValueType(MVT::i16));
541 InVals.push_back(Arg);
542 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
545 assert(VA.isRegLoc() && "Parameter must be in a register!");
547 unsigned Reg = VA.getLocReg();
549 if (VT == MVT::i64) {
550 // For now assume it is a pointer
551 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
552 &AMDGPU::SReg_64RegClass);
553 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
554 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
558 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
560 Reg = MF.addLiveIn(Reg, RC);
561 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
563 if (Arg.VT.isVector()) {
565 // Build a vector from the registers
566 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
567 unsigned NumElements = ParamType->getVectorNumElements();
569 SmallVector<SDValue, 4> Regs;
571 for (unsigned j = 1; j != NumElements; ++j) {
572 Reg = ArgLocs[ArgIdx++].getLocReg();
573 Reg = MF.addLiveIn(Reg, RC);
574 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
577 // Fill up the missing vector elements
578 NumElements = Arg.VT.getVectorNumElements() - NumElements;
579 for (unsigned j = 0; j != NumElements; ++j)
580 Regs.push_back(DAG.getUNDEF(VT));
582 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
586 InVals.push_back(Val);
589 if (Info->getShaderType() != ShaderType::COMPUTE) {
590 unsigned ScratchIdx = CCInfo.getFirstUnallocated(
591 AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs());
592 Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
597 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
598 MachineInstr * MI, MachineBasicBlock * BB) const {
600 MachineBasicBlock::iterator I = *MI;
601 const SIInstrInfo *TII =
602 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
604 switch (MI->getOpcode()) {
606 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
607 case AMDGPU::BRANCH: return BB;
608 case AMDGPU::V_SUB_F64: {
609 unsigned DestReg = MI->getOperand(0).getReg();
610 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
611 .addImm(0) // SRC0 modifiers
612 .addReg(MI->getOperand(1).getReg())
613 .addImm(1) // SRC1 modifiers
614 .addReg(MI->getOperand(2).getReg())
617 MI->eraseFromParent();
620 case AMDGPU::SI_RegisterStorePseudo: {
621 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
622 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
623 MachineInstrBuilder MIB =
624 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
626 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
627 MIB.addOperand(MI->getOperand(i));
629 MI->eraseFromParent();
636 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
637 // This currently forces unfolding various combinations of fsub into fma with
638 // free fneg'd operands. As long as we have fast FMA (controlled by
639 // isFMAFasterThanFMulAndFAdd), we should perform these.
641 // When fma is quarter rate, for f64 where add / sub are at best half rate,
642 // most of these combines appear to be cycle neutral but save on instruction
643 // count / code size.
647 EVT SITargetLowering::getSetCCResultType(LLVMContext &Ctx, EVT VT) const {
648 if (!VT.isVector()) {
651 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
654 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
658 // Answering this is somewhat tricky and depends on the specific device which
659 // have different rates for fma or all f64 operations.
661 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
662 // regardless of which device (although the number of cycles differs between
663 // devices), so it is always profitable for f64.
665 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
666 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
667 // which we can always do even without fused FP ops since it returns the same
668 // result as the separate operations and since it is always full
669 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
670 // however does not support denormals, so we do report fma as faster if we have
671 // a fast fma device and require denormals.
673 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
674 VT = VT.getScalarType();
679 switch (VT.getSimpleVT().SimpleTy) {
681 // This is as fast on some subtargets. However, we always have full rate f32
682 // mad available which returns the same result as the separate operations
683 // which we should prefer over fma.
694 //===----------------------------------------------------------------------===//
695 // Custom DAG Lowering Operations
696 //===----------------------------------------------------------------------===//
698 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
699 switch (Op.getOpcode()) {
700 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
701 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
702 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
704 SDValue Result = LowerLOAD(Op, DAG);
705 assert((!Result.getNode() ||
706 Result.getNode()->getNumValues() == 2) &&
707 "Load should return a value and a chain");
713 return LowerTrig(Op, DAG);
714 case ISD::SELECT: return LowerSELECT(Op, DAG);
715 case ISD::FDIV: return LowerFDIV(Op, DAG);
716 case ISD::STORE: return LowerSTORE(Op, DAG);
717 case ISD::GlobalAddress: {
718 MachineFunction &MF = DAG.getMachineFunction();
719 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
720 return LowerGlobalAddress(MFI, Op, DAG);
722 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
723 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
728 /// \brief Helper function for LowerBRCOND
729 static SDNode *findUser(SDValue Value, unsigned Opcode) {
731 SDNode *Parent = Value.getNode();
732 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
735 if (I.getUse().get() != Value)
738 if (I->getOpcode() == Opcode)
744 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
746 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
747 unsigned FrameIndex = FINode->getIndex();
749 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
752 /// This transforms the control flow intrinsics to get the branch destination as
753 /// last parameter, also switches branch target with BR if the need arise
754 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
755 SelectionDAG &DAG) const {
759 SDNode *Intr = BRCOND.getOperand(1).getNode();
760 SDValue Target = BRCOND.getOperand(2);
761 SDNode *BR = nullptr;
763 if (Intr->getOpcode() == ISD::SETCC) {
764 // As long as we negate the condition everything is fine
765 SDNode *SetCC = Intr;
766 assert(SetCC->getConstantOperandVal(1) == 1);
767 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
769 Intr = SetCC->getOperand(0).getNode();
772 // Get the target from BR if we don't negate the condition
773 BR = findUser(BRCOND, ISD::BR);
774 Target = BR->getOperand(1);
777 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
779 // Build the result and
780 SmallVector<EVT, 4> Res;
781 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
782 Res.push_back(Intr->getValueType(i));
784 // operands of the new intrinsic call
785 SmallVector<SDValue, 4> Ops;
786 Ops.push_back(BRCOND.getOperand(0));
787 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
788 Ops.push_back(Intr->getOperand(i));
789 Ops.push_back(Target);
791 // build the new intrinsic call
792 SDNode *Result = DAG.getNode(
793 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
794 DAG.getVTList(Res), Ops).getNode();
797 // Give the branch instruction our target
802 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
803 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
804 BR = NewBR.getNode();
807 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
809 // Copy the intrinsic results to registers
810 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
811 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
815 Chain = DAG.getCopyToReg(
817 CopyToReg->getOperand(1),
818 SDValue(Result, i - 1),
821 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
824 // Remove the old intrinsic from the chain
825 DAG.ReplaceAllUsesOfValueWith(
826 SDValue(Intr, Intr->getNumValues() - 1),
827 Intr->getOperand(0));
832 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
834 SelectionDAG &DAG) const {
835 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
837 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
838 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
841 const GlobalValue *GV = GSD->getGlobal();
842 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
844 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
845 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
847 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
848 DAG.getConstant(0, MVT::i32));
849 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
850 DAG.getConstant(1, MVT::i32));
852 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
854 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
855 PtrHi, DAG.getConstant(0, MVT::i32),
856 SDValue(Lo.getNode(), 1));
857 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
860 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
861 SelectionDAG &DAG) const {
862 MachineFunction &MF = DAG.getMachineFunction();
863 const SIRegisterInfo *TRI =
864 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
866 EVT VT = Op.getValueType();
868 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
870 switch (IntrinsicID) {
871 case Intrinsic::r600_read_ngroups_x:
872 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
873 SI::KernelInputOffsets::NGROUPS_X, false);
874 case Intrinsic::r600_read_ngroups_y:
875 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
876 SI::KernelInputOffsets::NGROUPS_Y, false);
877 case Intrinsic::r600_read_ngroups_z:
878 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
879 SI::KernelInputOffsets::NGROUPS_Z, false);
880 case Intrinsic::r600_read_global_size_x:
881 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
882 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
883 case Intrinsic::r600_read_global_size_y:
884 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
885 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
886 case Intrinsic::r600_read_global_size_z:
887 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
888 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
889 case Intrinsic::r600_read_local_size_x:
890 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
891 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
892 case Intrinsic::r600_read_local_size_y:
893 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
894 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
895 case Intrinsic::r600_read_local_size_z:
896 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
897 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
899 case Intrinsic::AMDGPU_read_workdim:
900 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
901 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
904 case Intrinsic::r600_read_tgid_x:
905 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
906 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
907 case Intrinsic::r600_read_tgid_y:
908 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
909 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
910 case Intrinsic::r600_read_tgid_z:
911 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
912 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
913 case Intrinsic::r600_read_tidig_x:
914 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
915 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
916 case Intrinsic::r600_read_tidig_y:
917 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
918 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
919 case Intrinsic::r600_read_tidig_z:
920 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
921 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
922 case AMDGPUIntrinsic::SI_load_const: {
928 MachineMemOperand *MMO = MF.getMachineMemOperand(
929 MachinePointerInfo(),
930 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
931 VT.getStoreSize(), 4);
932 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
933 Op->getVTList(), Ops, VT, MMO);
935 case AMDGPUIntrinsic::SI_sample:
936 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
937 case AMDGPUIntrinsic::SI_sampleb:
938 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
939 case AMDGPUIntrinsic::SI_sampled:
940 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
941 case AMDGPUIntrinsic::SI_samplel:
942 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
943 case AMDGPUIntrinsic::SI_vs_load_input:
944 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
949 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
953 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
954 SelectionDAG &DAG) const {
955 MachineFunction &MF = DAG.getMachineFunction();
956 SDValue Chain = Op.getOperand(0);
957 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
959 switch (IntrinsicID) {
960 case AMDGPUIntrinsic::SI_tbuffer_store: {
979 EVT VT = Op.getOperand(3).getValueType();
981 MachineMemOperand *MMO = MF.getMachineMemOperand(
982 MachinePointerInfo(),
983 MachineMemOperand::MOStore,
984 VT.getStoreSize(), 4);
985 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
986 Op->getVTList(), Ops, VT, MMO);
993 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
995 LoadSDNode *Load = cast<LoadSDNode>(Op);
997 if (Op.getValueType().isVector()) {
998 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
999 "Custom lowering for non-i32 vectors hasn't been implemented.");
1000 unsigned NumElements = Op.getValueType().getVectorNumElements();
1001 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1002 switch (Load->getAddressSpace()) {
1004 case AMDGPUAS::GLOBAL_ADDRESS:
1005 case AMDGPUAS::PRIVATE_ADDRESS:
1006 // v4 loads are supported for private and global memory.
1007 if (NumElements <= 4)
1010 case AMDGPUAS::LOCAL_ADDRESS:
1011 return ScalarizeVectorLoad(Op, DAG);
1015 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1018 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1020 SelectionDAG &DAG) const {
1021 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1027 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1028 if (Op.getValueType() != MVT::i64)
1032 SDValue Cond = Op.getOperand(0);
1034 SDValue Zero = DAG.getConstant(0, MVT::i32);
1035 SDValue One = DAG.getConstant(1, MVT::i32);
1037 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1038 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1040 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1041 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1043 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1045 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1046 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1048 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1050 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1051 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1054 // Catch division cases where we can use shortcuts with rcp and rsq
1056 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1058 SDValue LHS = Op.getOperand(0);
1059 SDValue RHS = Op.getOperand(1);
1060 EVT VT = Op.getValueType();
1061 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1063 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1064 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1065 CLHS->isExactlyValue(1.0)) {
1066 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1067 // the CI documentation has a worst case error of 1 ulp.
1068 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1069 // use it as long as we aren't trying to use denormals.
1071 // 1.0 / sqrt(x) -> rsq(x)
1073 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1074 // error seems really high at 2^29 ULP.
1075 if (RHS.getOpcode() == ISD::FSQRT)
1076 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1078 // 1.0 / x -> rcp(x)
1079 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1084 // Turn into multiply by the reciprocal.
1085 // x / y -> x * (1.0 / y)
1086 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1087 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1093 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1094 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1095 if (FastLowered.getNode())
1098 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1099 // selection error for now rather than do something incorrect.
1100 if (Subtarget->hasFP32Denormals())
1104 SDValue LHS = Op.getOperand(0);
1105 SDValue RHS = Op.getOperand(1);
1107 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1109 const APFloat K0Val(BitsToFloat(0x6f800000));
1110 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1112 const APFloat K1Val(BitsToFloat(0x2f800000));
1113 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1115 const SDValue One = DAG.getConstantFP(1.0, MVT::f32);
1117 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1119 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1121 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1123 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1125 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1127 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1129 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1132 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1136 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1137 EVT VT = Op.getValueType();
1140 return LowerFDIV32(Op, DAG);
1143 return LowerFDIV64(Op, DAG);
1145 llvm_unreachable("Unexpected type for fdiv");
1148 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1150 StoreSDNode *Store = cast<StoreSDNode>(Op);
1151 EVT VT = Store->getMemoryVT();
1153 // These stores are legal.
1154 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1155 if (VT.isVector() && VT.getVectorNumElements() > 4)
1156 return ScalarizeVectorStore(Op, DAG);
1160 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1164 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1165 return ScalarizeVectorStore(Op, DAG);
1168 return DAG.getTruncStore(Store->getChain(), DL,
1169 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1170 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1175 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1176 EVT VT = Op.getValueType();
1177 SDValue Arg = Op.getOperand(0);
1178 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1179 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1180 DAG.getConstantFP(0.5 / M_PI, VT)));
1182 switch (Op.getOpcode()) {
1184 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1186 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1188 llvm_unreachable("Wrong trig opcode");
1192 //===----------------------------------------------------------------------===//
1193 // Custom DAG optimizations
1194 //===----------------------------------------------------------------------===//
1196 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1197 DAGCombinerInfo &DCI) const {
1198 EVT VT = N->getValueType(0);
1199 EVT ScalarVT = VT.getScalarType();
1200 if (ScalarVT != MVT::f32)
1203 SelectionDAG &DAG = DCI.DAG;
1206 SDValue Src = N->getOperand(0);
1207 EVT SrcVT = Src.getValueType();
1209 // TODO: We could try to match extracting the higher bytes, which would be
1210 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1211 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1212 // about in practice.
1213 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1214 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1215 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1216 DCI.AddToWorklist(Cvt.getNode());
1221 // We are primarily trying to catch operations on illegal vector types
1222 // before they are expanded.
1223 // For scalars, we can use the more flexible method of checking masked bits
1224 // after legalization.
1225 if (!DCI.isBeforeLegalize() ||
1226 !SrcVT.isVector() ||
1227 SrcVT.getVectorElementType() != MVT::i8) {
1231 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1233 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1235 unsigned NElts = SrcVT.getVectorNumElements();
1236 if (!SrcVT.isSimple() && NElts != 3)
1239 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1240 // prevent a mess from expanding to v4i32 and repacking.
1241 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1242 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1243 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1244 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1245 LoadSDNode *Load = cast<LoadSDNode>(Src);
1247 unsigned AS = Load->getAddressSpace();
1248 unsigned Align = Load->getAlignment();
1249 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1250 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
1252 // Don't try to replace the load if we have to expand it due to alignment
1253 // problems. Otherwise we will end up scalarizing the load, and trying to
1254 // repack into the vector for no real reason.
1255 if (Align < ABIAlignment &&
1256 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1260 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1264 Load->getMemOperand());
1266 // Make sure successors of the original load stay after it by updating
1267 // them to use the new Chain.
1268 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1270 SmallVector<SDValue, 4> Elts;
1271 if (RegVT.isVector())
1272 DAG.ExtractVectorElements(NewLoad, Elts);
1274 Elts.push_back(NewLoad);
1276 SmallVector<SDValue, 4> Ops;
1278 unsigned EltIdx = 0;
1279 for (SDValue Elt : Elts) {
1280 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1281 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1282 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1283 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1284 DCI.AddToWorklist(Cvt.getNode());
1291 assert(Ops.size() == NElts);
1293 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1299 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1301 // This is a variant of
1302 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1304 // The normal DAG combiner will do this, but only if the add has one use since
1305 // that would increase the number of instructions.
1307 // This prevents us from seeing a constant offset that can be folded into a
1308 // memory instruction's addressing mode. If we know the resulting add offset of
1309 // a pointer can be folded into an addressing offset, we can replace the pointer
1310 // operand with the add of new constant offset. This eliminates one of the uses,
1311 // and may allow the remaining use to also be simplified.
1313 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1315 DAGCombinerInfo &DCI) const {
1316 SDValue N0 = N->getOperand(0);
1317 SDValue N1 = N->getOperand(1);
1319 if (N0.getOpcode() != ISD::ADD)
1322 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1326 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1330 const SIInstrInfo *TII =
1331 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1333 // If the resulting offset is too large, we can't fold it into the addressing
1335 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1336 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1339 SelectionDAG &DAG = DCI.DAG;
1341 EVT VT = N->getValueType(0);
1343 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1344 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1346 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1349 SDValue SITargetLowering::performAndCombine(SDNode *N,
1350 DAGCombinerInfo &DCI) const {
1351 if (DCI.isBeforeLegalize())
1354 SelectionDAG &DAG = DCI.DAG;
1356 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1357 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1358 SDValue LHS = N->getOperand(0);
1359 SDValue RHS = N->getOperand(1);
1361 if (LHS.getOpcode() == ISD::SETCC &&
1362 RHS.getOpcode() == ISD::SETCC) {
1363 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1364 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1366 SDValue X = LHS.getOperand(0);
1367 SDValue Y = RHS.getOperand(0);
1368 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1371 if (LCC == ISD::SETO) {
1372 if (X != LHS.getOperand(1))
1375 if (RCC == ISD::SETUNE) {
1376 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1377 if (!C1 || !C1->isInfinity() || C1->isNegative())
1380 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1381 SIInstrFlags::N_SUBNORMAL |
1382 SIInstrFlags::N_ZERO |
1383 SIInstrFlags::P_ZERO |
1384 SIInstrFlags::P_SUBNORMAL |
1385 SIInstrFlags::P_NORMAL;
1387 static_assert(((~(SIInstrFlags::S_NAN |
1388 SIInstrFlags::Q_NAN |
1389 SIInstrFlags::N_INFINITY |
1390 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1393 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1394 X, DAG.getConstant(Mask, MVT::i32));
1402 SDValue SITargetLowering::performOrCombine(SDNode *N,
1403 DAGCombinerInfo &DCI) const {
1404 SelectionDAG &DAG = DCI.DAG;
1405 SDValue LHS = N->getOperand(0);
1406 SDValue RHS = N->getOperand(1);
1408 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1409 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1410 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1411 SDValue Src = LHS.getOperand(0);
1412 if (Src != RHS.getOperand(0))
1415 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1416 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1420 // Only 10 bits are used.
1421 static const uint32_t MaxMask = 0x3ff;
1423 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1424 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1425 Src, DAG.getConstant(NewMask, MVT::i32));
1431 SDValue SITargetLowering::performClassCombine(SDNode *N,
1432 DAGCombinerInfo &DCI) const {
1433 SelectionDAG &DAG = DCI.DAG;
1434 SDValue Mask = N->getOperand(1);
1436 // fp_class x, 0 -> false
1437 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1438 if (CMask->isNullValue())
1439 return DAG.getConstant(0, MVT::i1);
1445 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1448 return AMDGPUISD::FMAX3;
1449 case AMDGPUISD::SMAX:
1450 return AMDGPUISD::SMAX3;
1451 case AMDGPUISD::UMAX:
1452 return AMDGPUISD::UMAX3;
1454 return AMDGPUISD::FMIN3;
1455 case AMDGPUISD::SMIN:
1456 return AMDGPUISD::SMIN3;
1457 case AMDGPUISD::UMIN:
1458 return AMDGPUISD::UMIN3;
1460 llvm_unreachable("Not a min/max opcode");
1464 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1465 DAGCombinerInfo &DCI) const {
1466 SelectionDAG &DAG = DCI.DAG;
1468 unsigned Opc = N->getOpcode();
1469 SDValue Op0 = N->getOperand(0);
1470 SDValue Op1 = N->getOperand(1);
1472 // Only do this if the inner op has one use since this will just increases
1473 // register pressure for no benefit.
1475 // max(max(a, b), c)
1476 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1478 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1486 // max(a, max(b, c))
1487 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1489 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1500 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1501 DAGCombinerInfo &DCI) const {
1502 SelectionDAG &DAG = DCI.DAG;
1505 SDValue LHS = N->getOperand(0);
1506 SDValue RHS = N->getOperand(1);
1507 EVT VT = LHS.getValueType();
1509 if (VT != MVT::f32 && VT != MVT::f64)
1512 // Match isinf pattern
1513 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1514 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1515 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1516 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1520 const APFloat &APF = CRHS->getValueAPF();
1521 if (APF.isInfinity() && !APF.isNegative()) {
1522 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1523 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1,
1524 LHS.getOperand(0), DAG.getConstant(Mask, MVT::i32));
1531 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1532 DAGCombinerInfo &DCI) const {
1533 SelectionDAG &DAG = DCI.DAG;
1536 switch (N->getOpcode()) {
1538 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1540 return performSetCCCombine(N, DCI);
1541 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1543 case AMDGPUISD::SMAX:
1544 case AMDGPUISD::SMIN:
1545 case AMDGPUISD::UMAX:
1546 case AMDGPUISD::UMIN: {
1547 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1548 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1549 return performMin3Max3Combine(N, DCI);
1553 case AMDGPUISD::CVT_F32_UBYTE0:
1554 case AMDGPUISD::CVT_F32_UBYTE1:
1555 case AMDGPUISD::CVT_F32_UBYTE2:
1556 case AMDGPUISD::CVT_F32_UBYTE3: {
1557 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1559 SDValue Src = N->getOperand(0);
1560 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1562 APInt KnownZero, KnownOne;
1563 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1564 !DCI.isBeforeLegalizeOps());
1565 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1566 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1567 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1568 DCI.CommitTargetLoweringOpt(TLO);
1574 case ISD::UINT_TO_FP: {
1575 return performUCharToFloatCombine(N, DCI);
1578 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1581 EVT VT = N->getValueType(0);
1585 SDValue LHS = N->getOperand(0);
1586 SDValue RHS = N->getOperand(1);
1588 // These should really be instruction patterns, but writing patterns with
1589 // source modiifiers is a pain.
1591 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1592 if (LHS.getOpcode() == ISD::FADD) {
1593 SDValue A = LHS.getOperand(0);
1594 if (A == LHS.getOperand(1)) {
1595 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1596 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1600 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1601 if (RHS.getOpcode() == ISD::FADD) {
1602 SDValue A = RHS.getOperand(0);
1603 if (A == RHS.getOperand(1)) {
1604 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1605 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1612 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1615 EVT VT = N->getValueType(0);
1617 // Try to get the fneg to fold into the source modifier. This undoes generic
1618 // DAG combines and folds them into the mad.
1619 if (VT == MVT::f32) {
1620 SDValue LHS = N->getOperand(0);
1621 SDValue RHS = N->getOperand(1);
1623 if (LHS.getOpcode() == ISD::FMUL) {
1624 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1626 SDValue A = LHS.getOperand(0);
1627 SDValue B = LHS.getOperand(1);
1628 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1630 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1633 if (RHS.getOpcode() == ISD::FMUL) {
1634 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1636 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1637 SDValue B = RHS.getOperand(1);
1640 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1643 if (LHS.getOpcode() == ISD::FADD) {
1644 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1646 SDValue A = LHS.getOperand(0);
1647 if (A == LHS.getOperand(1)) {
1648 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1649 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1651 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1655 if (RHS.getOpcode() == ISD::FADD) {
1656 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1658 SDValue A = RHS.getOperand(0);
1659 if (A == RHS.getOperand(1)) {
1660 const SDValue NegTwo = DAG.getConstantFP(-2.0, MVT::f32);
1661 return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1671 case ISD::ATOMIC_LOAD:
1672 case ISD::ATOMIC_STORE:
1673 case ISD::ATOMIC_CMP_SWAP:
1674 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1675 case ISD::ATOMIC_SWAP:
1676 case ISD::ATOMIC_LOAD_ADD:
1677 case ISD::ATOMIC_LOAD_SUB:
1678 case ISD::ATOMIC_LOAD_AND:
1679 case ISD::ATOMIC_LOAD_OR:
1680 case ISD::ATOMIC_LOAD_XOR:
1681 case ISD::ATOMIC_LOAD_NAND:
1682 case ISD::ATOMIC_LOAD_MIN:
1683 case ISD::ATOMIC_LOAD_MAX:
1684 case ISD::ATOMIC_LOAD_UMIN:
1685 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1686 if (DCI.isBeforeLegalize())
1689 MemSDNode *MemNode = cast<MemSDNode>(N);
1690 SDValue Ptr = MemNode->getBasePtr();
1692 // TODO: We could also do this for multiplies.
1693 unsigned AS = MemNode->getAddressSpace();
1694 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1695 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1697 SmallVector<SDValue, 8> NewOps;
1698 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1699 NewOps.push_back(MemNode->getOperand(I));
1701 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1702 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1708 return performAndCombine(N, DCI);
1710 return performOrCombine(N, DCI);
1711 case AMDGPUISD::FP_CLASS:
1712 return performClassCombine(N, DCI);
1714 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1717 /// \brief Test if RegClass is one of the VSrc classes
1718 static bool isVSrc(unsigned RegClass) {
1720 default: return false;
1721 case AMDGPU::VS_32RegClassID:
1722 case AMDGPU::VS_64RegClassID:
1727 /// \brief Analyze the possible immediate value Op
1729 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1730 /// and the immediate value if it's a literal immediate
1731 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1733 const SIInstrInfo *TII =
1734 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1736 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1737 if (TII->isInlineConstant(Node->getAPIntValue()))
1740 uint64_t Val = Node->getZExtValue();
1741 return isUInt<32>(Val) ? Val : -1;
1744 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1745 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1748 if (Node->getValueType(0) == MVT::f32)
1749 return FloatToBits(Node->getValueAPF().convertToFloat());
1757 const TargetRegisterClass *
1758 SITargetLowering::getRegClassForNode(SelectionDAG &DAG,
1759 const SDValue &Op) const {
1760 const SIInstrInfo *TII =
1761 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1762 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1764 if (!Op->isMachineOpcode()) {
1765 switch(Op->getOpcode()) {
1766 case ISD::CopyFromReg: {
1767 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1768 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1769 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1770 return MRI.getRegClass(Reg);
1772 return TRI.getPhysRegClass(Reg);
1774 default: return nullptr;
1777 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1778 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1779 if (OpClassID != -1) {
1780 return TRI.getRegClass(OpClassID);
1782 switch(Op.getMachineOpcode()) {
1783 case AMDGPU::COPY_TO_REGCLASS:
1784 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1785 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1787 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1788 // class, then the register class for the value could be either a
1789 // VReg or and SReg. In order to get a more accurate
1790 if (isVSrc(OpClassID))
1791 return getRegClassForNode(DAG, Op.getOperand(0));
1793 return TRI.getRegClass(OpClassID);
1794 case AMDGPU::EXTRACT_SUBREG: {
1795 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1796 const TargetRegisterClass *SuperClass =
1797 getRegClassForNode(DAG, Op.getOperand(0));
1798 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1800 case AMDGPU::REG_SEQUENCE:
1801 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1802 return TRI.getRegClass(
1803 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1805 return getRegClassFor(Op.getSimpleValueType());
1809 /// \brief Does "Op" fit into register class "RegClass" ?
1810 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1811 unsigned RegClass) const {
1812 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
1813 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1817 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1820 /// \brief Helper function for adjustWritemask
1821 static unsigned SubIdx2Lane(unsigned Idx) {
1824 case AMDGPU::sub0: return 0;
1825 case AMDGPU::sub1: return 1;
1826 case AMDGPU::sub2: return 2;
1827 case AMDGPU::sub3: return 3;
1831 /// \brief Adjust the writemask of MIMG instructions
1832 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1833 SelectionDAG &DAG) const {
1834 SDNode *Users[4] = { };
1836 unsigned OldDmask = Node->getConstantOperandVal(0);
1837 unsigned NewDmask = 0;
1839 // Try to figure out the used register components
1840 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1843 // Abort if we can't understand the usage
1844 if (!I->isMachineOpcode() ||
1845 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1848 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1849 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1850 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1852 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1854 // Set which texture component corresponds to the lane.
1856 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1858 Comp = countTrailingZeros(Dmask);
1859 Dmask &= ~(1 << Comp);
1862 // Abort if we have more than one user per component
1867 NewDmask |= 1 << Comp;
1870 // Abort if there's no change
1871 if (NewDmask == OldDmask)
1874 // Adjust the writemask in the node
1875 std::vector<SDValue> Ops;
1876 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1877 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1878 Ops.push_back(Node->getOperand(i));
1879 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1881 // If we only got one lane, replace it with a copy
1882 // (if NewDmask has only one bit set...)
1883 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1884 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, MVT::i32);
1885 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1886 SDLoc(), Users[Lane]->getValueType(0),
1887 SDValue(Node, 0), RC);
1888 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1892 // Update the users of the node with the new indices
1893 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1895 SDNode *User = Users[i];
1899 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1900 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1904 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1905 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1906 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1911 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1912 /// with frame index operands.
1913 /// LLVM assumes that inputs are to these instructions are registers.
1914 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1915 SelectionDAG &DAG) const {
1917 SmallVector<SDValue, 8> Ops;
1918 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1919 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1920 Ops.push_back(Node->getOperand(i));
1925 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1926 Node->getOperand(i).getValueType(),
1927 Node->getOperand(i)), 0));
1930 DAG.UpdateNodeOperands(Node, Ops);
1933 /// \brief Fold the instructions after selecting them.
1934 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1935 SelectionDAG &DAG) const {
1936 const SIInstrInfo *TII =
1937 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1938 Node = AdjustRegClass(Node, DAG);
1940 if (TII->isMIMG(Node->getMachineOpcode()))
1941 adjustWritemask(Node, DAG);
1943 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1944 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1945 legalizeTargetIndependentNode(Node, DAG);
1951 /// \brief Assign the register class depending on the number of
1952 /// bits set in the writemask
1953 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1954 SDNode *Node) const {
1955 const SIInstrInfo *TII =
1956 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1958 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1959 TII->legalizeOperands(MI);
1961 if (TII->isMIMG(MI->getOpcode())) {
1962 unsigned VReg = MI->getOperand(0).getReg();
1963 unsigned Writemask = MI->getOperand(1).getImm();
1964 unsigned BitsSet = 0;
1965 for (unsigned i = 0; i < 4; ++i)
1966 BitsSet += Writemask & (1 << i) ? 1 : 0;
1968 const TargetRegisterClass *RC;
1971 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
1972 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1973 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1976 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1977 MI->setDesc(TII->get(NewOpcode));
1978 MRI.setRegClass(VReg, RC);
1982 // Replace unused atomics with the no return version.
1983 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1984 if (NoRetAtomicOp != -1) {
1985 if (!Node->hasAnyUseOfValue(0)) {
1986 MI->setDesc(TII->get(NoRetAtomicOp));
1987 MI->RemoveOperand(0);
1994 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
1995 SDValue K = DAG.getTargetConstant(Val, MVT::i32);
1996 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
1999 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2001 SDValue Ptr) const {
2002 const SIInstrInfo *TII =
2003 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2005 // XXX - Workaround for moveToVALU not handling different register class
2006 // inserts for REG_SEQUENCE.
2008 // Build the half of the subregister with the constants.
2009 const SDValue Ops0[] = {
2010 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
2011 buildSMovImm32(DAG, DL, 0),
2012 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2013 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2014 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
2017 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2018 MVT::v2i32, Ops0), 0);
2020 // Combine the constants and the pointer.
2021 const SDValue Ops1[] = {
2022 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2024 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2026 DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
2029 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2031 const SDValue Ops[] = {
2032 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2034 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2035 buildSMovImm32(DAG, DL, 0),
2036 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2037 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2038 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2041 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2046 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2047 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2048 /// of the resource descriptor) to create an offset, which is added to the
2049 /// resource ponter.
2050 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2053 uint32_t RsrcDword1,
2054 uint64_t RsrcDword2And3) const {
2055 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2056 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2058 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2059 DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2062 SDValue DataLo = buildSMovImm32(DAG, DL,
2063 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2064 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2066 const SDValue Ops[] = {
2067 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2069 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2071 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2073 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2075 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2078 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2081 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2083 SDValue Ptr) const {
2084 const SIInstrInfo *TII =
2085 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2086 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2089 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2092 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2093 SelectionDAG &DAG) const {
2096 unsigned NewOpcode = N->getMachineOpcode();
2098 switch (N->getMachineOpcode()) {
2100 case AMDGPU::S_LOAD_DWORD_IMM:
2101 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2103 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2104 if (NewOpcode == N->getMachineOpcode()) {
2105 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2108 case AMDGPU::S_LOAD_DWORDX4_IMM:
2109 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2110 if (NewOpcode == N->getMachineOpcode()) {
2111 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2113 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2116 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2118 const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2119 SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2120 MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2122 SmallVector<SDValue, 8> Ops;
2123 Ops.push_back(SDValue(RSrc, 0));
2124 Ops.push_back(N->getOperand(0));
2125 Ops.push_back(DAG.getTargetConstant(0, MVT::i32)); // soffset
2127 // The immediate offset is in dwords on SI and in bytes on VI.
2128 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
2129 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue(), MVT::i32));
2131 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue() << 2, MVT::i32));
2133 // Copy remaining operands so we keep any chain and glue nodes that follow
2134 // the normal operands.
2135 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2136 Ops.push_back(N->getOperand(I));
2138 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2143 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2144 const TargetRegisterClass *RC,
2145 unsigned Reg, EVT VT) const {
2146 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2148 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2149 cast<RegisterSDNode>(VReg)->getReg(), VT);