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);
214 setOperationAction(ISD::FDIV, MVT::f64, Custom);
216 setTargetDAGCombine(ISD::FADD);
217 setTargetDAGCombine(ISD::FSUB);
218 setTargetDAGCombine(ISD::FMINNUM);
219 setTargetDAGCombine(ISD::FMAXNUM);
220 setTargetDAGCombine(ISD::SELECT_CC);
221 setTargetDAGCombine(ISD::SETCC);
222 setTargetDAGCombine(ISD::AND);
223 setTargetDAGCombine(ISD::OR);
224 setTargetDAGCombine(ISD::UINT_TO_FP);
226 // All memory operations. Some folding on the pointer operand is done to help
227 // matching the constant offsets in the addressing modes.
228 setTargetDAGCombine(ISD::LOAD);
229 setTargetDAGCombine(ISD::STORE);
230 setTargetDAGCombine(ISD::ATOMIC_LOAD);
231 setTargetDAGCombine(ISD::ATOMIC_STORE);
232 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
233 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
234 setTargetDAGCombine(ISD::ATOMIC_SWAP);
235 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
243 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
246 setSchedulingPreference(Sched::RegPressure);
249 //===----------------------------------------------------------------------===//
250 // TargetLowering queries
251 //===----------------------------------------------------------------------===//
253 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
255 // SI has some legal vector types, but no legal vector operations. Say no
256 // shuffles are legal in order to prefer scalarizing some vector operations.
260 // FIXME: This really needs an address space argument. The immediate offset
261 // size is different for different sets of memory instruction sets.
263 // The single offset DS instructions have a 16-bit unsigned byte offset.
265 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
266 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
267 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
269 // SMRD instructions have an 8-bit, dword offset.
271 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
273 // No global is ever allowed as a base.
277 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
279 if (!isUInt<16>(AM.BaseOffs))
284 case 0: // "r+i" or just "i", depending on HasBaseReg.
287 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
289 // Otherwise we have r+r or r+i.
292 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
296 default: // Don't allow n * r
303 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
306 bool *IsFast) const {
310 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
311 // which isn't a simple VT.
312 if (!VT.isSimple() || VT == MVT::Other)
315 // TODO - CI+ supports unaligned memory accesses, but this requires driver
318 // XXX - The only mention I see of this in the ISA manual is for LDS direct
319 // reads the "byte address and must be dword aligned". Is it also true for the
320 // normal loads and stores?
321 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
322 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
323 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
324 // with adjacent offsets.
325 return Align % 4 == 0;
328 // Smaller than dword value must be aligned.
329 // FIXME: This should be allowed on CI+
330 if (VT.bitsLT(MVT::i32))
333 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
334 // byte-address are ignored, thus forcing Dword alignment.
335 // This applies to private, global, and constant memory.
339 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
342 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
343 unsigned SrcAlign, bool IsMemset,
346 MachineFunction &MF) const {
347 // FIXME: Should account for address space here.
349 // The default fallback uses the private pointer size as a guess for a type to
350 // use. Make sure we switch these to 64-bit accesses.
352 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
355 if (Size >= 8 && DstAlign >= 4)
362 TargetLoweringBase::LegalizeTypeAction
363 SITargetLowering::getPreferredVectorAction(EVT VT) const {
364 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
365 return TypeSplitVector;
367 return TargetLoweringBase::getPreferredVectorAction(VT);
370 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
372 const SIInstrInfo *TII =
373 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
374 return TII->isInlineConstant(Imm);
377 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
378 SDLoc SL, SDValue Chain,
379 unsigned Offset, bool Signed) const {
380 const DataLayout *DL = getDataLayout();
381 MachineFunction &MF = DAG.getMachineFunction();
382 const SIRegisterInfo *TRI =
383 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
384 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
386 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
388 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
389 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
390 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
391 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
392 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
393 DAG.getConstant(Offset, MVT::i64));
394 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
395 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
397 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
398 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
400 true, // isNonTemporal
402 DL->getABITypeAlignment(Ty)); // Alignment
405 SDValue SITargetLowering::LowerFormalArguments(
406 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
407 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
408 SmallVectorImpl<SDValue> &InVals) const {
409 const SIRegisterInfo *TRI =
410 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
412 MachineFunction &MF = DAG.getMachineFunction();
413 FunctionType *FType = MF.getFunction()->getFunctionType();
414 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
416 assert(CallConv == CallingConv::C);
418 SmallVector<ISD::InputArg, 16> Splits;
419 BitVector Skipped(Ins.size());
421 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
422 const ISD::InputArg &Arg = Ins[i];
424 // First check if it's a PS input addr
425 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
426 !Arg.Flags.isByVal()) {
428 assert((PSInputNum <= 15) && "Too many PS inputs!");
431 // We can savely skip PS inputs
437 Info->PSInputAddr |= 1 << PSInputNum++;
440 // Second split vertices into their elements
441 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
442 ISD::InputArg NewArg = Arg;
443 NewArg.Flags.setSplit();
444 NewArg.VT = Arg.VT.getVectorElementType();
446 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
447 // three or five element vertex only needs three or five registers,
448 // NOT four or eigth.
449 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
450 unsigned NumElements = ParamType->getVectorNumElements();
452 for (unsigned j = 0; j != NumElements; ++j) {
453 Splits.push_back(NewArg);
454 NewArg.PartOffset += NewArg.VT.getStoreSize();
457 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
458 Splits.push_back(Arg);
462 SmallVector<CCValAssign, 16> ArgLocs;
463 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
466 // At least one interpolation mode must be enabled or else the GPU will hang.
467 if (Info->getShaderType() == ShaderType::PIXEL &&
468 (Info->PSInputAddr & 0x7F) == 0) {
469 Info->PSInputAddr |= 1;
470 CCInfo.AllocateReg(AMDGPU::VGPR0);
471 CCInfo.AllocateReg(AMDGPU::VGPR1);
474 // The pointer to the list of arguments is stored in SGPR0, SGPR1
475 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
476 if (Info->getShaderType() == ShaderType::COMPUTE) {
477 if (Subtarget->isAmdHsaOS())
478 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
480 Info->NumUserSGPRs = 4;
482 unsigned InputPtrReg =
483 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
484 unsigned InputPtrRegLo =
485 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
486 unsigned InputPtrRegHi =
487 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
489 unsigned ScratchPtrReg =
490 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
491 unsigned ScratchPtrRegLo =
492 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
493 unsigned ScratchPtrRegHi =
494 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
496 CCInfo.AllocateReg(InputPtrRegLo);
497 CCInfo.AllocateReg(InputPtrRegHi);
498 CCInfo.AllocateReg(ScratchPtrRegLo);
499 CCInfo.AllocateReg(ScratchPtrRegHi);
500 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
501 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
504 if (Info->getShaderType() == ShaderType::COMPUTE) {
505 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
509 AnalyzeFormalArguments(CCInfo, Splits);
511 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
513 const ISD::InputArg &Arg = Ins[i];
515 InVals.push_back(DAG.getUNDEF(Arg.VT));
519 CCValAssign &VA = ArgLocs[ArgIdx++];
520 MVT VT = VA.getLocVT();
524 EVT MemVT = Splits[i].VT;
525 const unsigned Offset = 36 + VA.getLocMemOffset();
526 // The first 36 bytes of the input buffer contains information about
527 // thread group and global sizes.
528 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
529 Offset, Ins[i].Flags.isSExt());
531 const PointerType *ParamTy =
532 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
533 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
534 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
535 // On SI local pointers are just offsets into LDS, so they are always
536 // less than 16-bits. On CI and newer they could potentially be
537 // real pointers, so we can't guarantee their size.
538 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
539 DAG.getValueType(MVT::i16));
542 InVals.push_back(Arg);
543 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
546 assert(VA.isRegLoc() && "Parameter must be in a register!");
548 unsigned Reg = VA.getLocReg();
550 if (VT == MVT::i64) {
551 // For now assume it is a pointer
552 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
553 &AMDGPU::SReg_64RegClass);
554 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
555 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
559 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
561 Reg = MF.addLiveIn(Reg, RC);
562 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
564 if (Arg.VT.isVector()) {
566 // Build a vector from the registers
567 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
568 unsigned NumElements = ParamType->getVectorNumElements();
570 SmallVector<SDValue, 4> Regs;
572 for (unsigned j = 1; j != NumElements; ++j) {
573 Reg = ArgLocs[ArgIdx++].getLocReg();
574 Reg = MF.addLiveIn(Reg, RC);
575 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
578 // Fill up the missing vector elements
579 NumElements = Arg.VT.getVectorNumElements() - NumElements;
580 Regs.append(NumElements, 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. We can't use this if we want to support
684 // denormals, so only report this in these cases.
685 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
695 //===----------------------------------------------------------------------===//
696 // Custom DAG Lowering Operations
697 //===----------------------------------------------------------------------===//
699 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
700 switch (Op.getOpcode()) {
701 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
702 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
703 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
705 SDValue Result = LowerLOAD(Op, DAG);
706 assert((!Result.getNode() ||
707 Result.getNode()->getNumValues() == 2) &&
708 "Load should return a value and a chain");
714 return LowerTrig(Op, DAG);
715 case ISD::SELECT: return LowerSELECT(Op, DAG);
716 case ISD::FDIV: return LowerFDIV(Op, DAG);
717 case ISD::STORE: return LowerSTORE(Op, DAG);
718 case ISD::GlobalAddress: {
719 MachineFunction &MF = DAG.getMachineFunction();
720 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
721 return LowerGlobalAddress(MFI, Op, DAG);
723 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
724 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
729 /// \brief Helper function for LowerBRCOND
730 static SDNode *findUser(SDValue Value, unsigned Opcode) {
732 SDNode *Parent = Value.getNode();
733 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
736 if (I.getUse().get() != Value)
739 if (I->getOpcode() == Opcode)
745 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
747 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
748 unsigned FrameIndex = FINode->getIndex();
750 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
753 /// This transforms the control flow intrinsics to get the branch destination as
754 /// last parameter, also switches branch target with BR if the need arise
755 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
756 SelectionDAG &DAG) const {
760 SDNode *Intr = BRCOND.getOperand(1).getNode();
761 SDValue Target = BRCOND.getOperand(2);
762 SDNode *BR = nullptr;
764 if (Intr->getOpcode() == ISD::SETCC) {
765 // As long as we negate the condition everything is fine
766 SDNode *SetCC = Intr;
767 assert(SetCC->getConstantOperandVal(1) == 1);
768 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
770 Intr = SetCC->getOperand(0).getNode();
773 // Get the target from BR if we don't negate the condition
774 BR = findUser(BRCOND, ISD::BR);
775 Target = BR->getOperand(1);
778 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
780 // Build the result and
781 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
783 // operands of the new intrinsic call
784 SmallVector<SDValue, 4> Ops;
785 Ops.push_back(BRCOND.getOperand(0));
786 Ops.append(Intr->op_begin() + 1, Intr->op_end());
787 Ops.push_back(Target);
789 // build the new intrinsic call
790 SDNode *Result = DAG.getNode(
791 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
792 DAG.getVTList(Res), Ops).getNode();
795 // Give the branch instruction our target
800 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
801 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
802 BR = NewBR.getNode();
805 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
807 // Copy the intrinsic results to registers
808 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
809 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
813 Chain = DAG.getCopyToReg(
815 CopyToReg->getOperand(1),
816 SDValue(Result, i - 1),
819 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
822 // Remove the old intrinsic from the chain
823 DAG.ReplaceAllUsesOfValueWith(
824 SDValue(Intr, Intr->getNumValues() - 1),
825 Intr->getOperand(0));
830 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
832 SelectionDAG &DAG) const {
833 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
835 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
836 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
839 const GlobalValue *GV = GSD->getGlobal();
840 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
842 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
843 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
845 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
846 DAG.getConstant(0, MVT::i32));
847 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
848 DAG.getConstant(1, MVT::i32));
850 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
852 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
853 PtrHi, DAG.getConstant(0, MVT::i32),
854 SDValue(Lo.getNode(), 1));
855 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
858 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
859 SelectionDAG &DAG) const {
860 MachineFunction &MF = DAG.getMachineFunction();
861 const SIRegisterInfo *TRI =
862 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
864 EVT VT = Op.getValueType();
866 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
868 switch (IntrinsicID) {
869 case Intrinsic::r600_read_ngroups_x:
870 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
871 SI::KernelInputOffsets::NGROUPS_X, false);
872 case Intrinsic::r600_read_ngroups_y:
873 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
874 SI::KernelInputOffsets::NGROUPS_Y, false);
875 case Intrinsic::r600_read_ngroups_z:
876 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
877 SI::KernelInputOffsets::NGROUPS_Z, false);
878 case Intrinsic::r600_read_global_size_x:
879 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
880 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
881 case Intrinsic::r600_read_global_size_y:
882 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
883 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
884 case Intrinsic::r600_read_global_size_z:
885 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
886 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
887 case Intrinsic::r600_read_local_size_x:
888 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
889 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
890 case Intrinsic::r600_read_local_size_y:
891 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
892 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
893 case Intrinsic::r600_read_local_size_z:
894 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
895 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
897 case Intrinsic::AMDGPU_read_workdim:
898 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
899 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
902 case Intrinsic::r600_read_tgid_x:
903 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
904 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
905 case Intrinsic::r600_read_tgid_y:
906 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
907 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
908 case Intrinsic::r600_read_tgid_z:
909 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
910 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
911 case Intrinsic::r600_read_tidig_x:
912 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
913 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
914 case Intrinsic::r600_read_tidig_y:
915 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
916 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
917 case Intrinsic::r600_read_tidig_z:
918 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
919 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
920 case AMDGPUIntrinsic::SI_load_const: {
926 MachineMemOperand *MMO = MF.getMachineMemOperand(
927 MachinePointerInfo(),
928 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
929 VT.getStoreSize(), 4);
930 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
931 Op->getVTList(), Ops, VT, MMO);
933 case AMDGPUIntrinsic::SI_sample:
934 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
935 case AMDGPUIntrinsic::SI_sampleb:
936 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
937 case AMDGPUIntrinsic::SI_sampled:
938 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
939 case AMDGPUIntrinsic::SI_samplel:
940 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
941 case AMDGPUIntrinsic::SI_vs_load_input:
942 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
947 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
951 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
952 SelectionDAG &DAG) const {
953 MachineFunction &MF = DAG.getMachineFunction();
954 SDValue Chain = Op.getOperand(0);
955 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
957 switch (IntrinsicID) {
958 case AMDGPUIntrinsic::SI_tbuffer_store: {
977 EVT VT = Op.getOperand(3).getValueType();
979 MachineMemOperand *MMO = MF.getMachineMemOperand(
980 MachinePointerInfo(),
981 MachineMemOperand::MOStore,
982 VT.getStoreSize(), 4);
983 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
984 Op->getVTList(), Ops, VT, MMO);
991 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
993 LoadSDNode *Load = cast<LoadSDNode>(Op);
995 if (Op.getValueType().isVector()) {
996 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
997 "Custom lowering for non-i32 vectors hasn't been implemented.");
998 unsigned NumElements = Op.getValueType().getVectorNumElements();
999 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1000 switch (Load->getAddressSpace()) {
1002 case AMDGPUAS::GLOBAL_ADDRESS:
1003 case AMDGPUAS::PRIVATE_ADDRESS:
1004 // v4 loads are supported for private and global memory.
1005 if (NumElements <= 4)
1008 case AMDGPUAS::LOCAL_ADDRESS:
1009 return ScalarizeVectorLoad(Op, DAG);
1013 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1016 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1018 SelectionDAG &DAG) const {
1019 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1025 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1026 if (Op.getValueType() != MVT::i64)
1030 SDValue Cond = Op.getOperand(0);
1032 SDValue Zero = DAG.getConstant(0, MVT::i32);
1033 SDValue One = DAG.getConstant(1, MVT::i32);
1035 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1036 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1038 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1039 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1041 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1043 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1044 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1046 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1048 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1049 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1052 // Catch division cases where we can use shortcuts with rcp and rsq
1054 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1056 SDValue LHS = Op.getOperand(0);
1057 SDValue RHS = Op.getOperand(1);
1058 EVT VT = Op.getValueType();
1059 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1061 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1062 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1063 CLHS->isExactlyValue(1.0)) {
1064 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1065 // the CI documentation has a worst case error of 1 ulp.
1066 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1067 // use it as long as we aren't trying to use denormals.
1069 // 1.0 / sqrt(x) -> rsq(x)
1071 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1072 // error seems really high at 2^29 ULP.
1073 if (RHS.getOpcode() == ISD::FSQRT)
1074 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1076 // 1.0 / x -> rcp(x)
1077 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1082 // Turn into multiply by the reciprocal.
1083 // x / y -> x * (1.0 / y)
1084 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1085 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1091 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1092 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1093 if (FastLowered.getNode())
1096 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1097 // selection error for now rather than do something incorrect.
1098 if (Subtarget->hasFP32Denormals())
1102 SDValue LHS = Op.getOperand(0);
1103 SDValue RHS = Op.getOperand(1);
1105 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1107 const APFloat K0Val(BitsToFloat(0x6f800000));
1108 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1110 const APFloat K1Val(BitsToFloat(0x2f800000));
1111 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1113 const SDValue One = DAG.getConstantFP(1.0, MVT::f32);
1115 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1117 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1119 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1121 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1123 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1125 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1127 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1130 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1131 if (DAG.getTarget().Options.UnsafeFPMath)
1132 return LowerFastFDIV(Op, DAG);
1135 SDValue X = Op.getOperand(0);
1136 SDValue Y = Op.getOperand(1);
1138 const SDValue One = DAG.getConstantFP(1.0, MVT::f64);
1140 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1142 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1144 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1146 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1148 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1150 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1152 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1154 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1156 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1157 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1159 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1160 NegDivScale0, Mul, DivScale1);
1164 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1165 // Workaround a hardware bug on SI where the condition output from div_scale
1168 const SDValue Hi = DAG.getConstant(1, MVT::i32);
1170 // Figure out if the scale to use for div_fmas.
1171 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1172 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1173 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1174 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1176 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1177 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1180 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1182 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1184 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1185 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1186 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1188 Scale = DivScale1.getValue(1);
1191 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1192 Fma4, Fma3, Mul, Scale);
1194 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1197 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1198 EVT VT = Op.getValueType();
1201 return LowerFDIV32(Op, DAG);
1204 return LowerFDIV64(Op, DAG);
1206 llvm_unreachable("Unexpected type for fdiv");
1209 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1211 StoreSDNode *Store = cast<StoreSDNode>(Op);
1212 EVT VT = Store->getMemoryVT();
1214 // These stores are legal.
1215 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1216 if (VT.isVector() && VT.getVectorNumElements() > 4)
1217 return ScalarizeVectorStore(Op, DAG);
1221 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1225 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1226 return ScalarizeVectorStore(Op, DAG);
1229 return DAG.getTruncStore(Store->getChain(), DL,
1230 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1231 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1236 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1237 EVT VT = Op.getValueType();
1238 SDValue Arg = Op.getOperand(0);
1239 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1240 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1241 DAG.getConstantFP(0.5 / M_PI, VT)));
1243 switch (Op.getOpcode()) {
1245 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1247 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1249 llvm_unreachable("Wrong trig opcode");
1253 //===----------------------------------------------------------------------===//
1254 // Custom DAG optimizations
1255 //===----------------------------------------------------------------------===//
1257 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1258 DAGCombinerInfo &DCI) const {
1259 EVT VT = N->getValueType(0);
1260 EVT ScalarVT = VT.getScalarType();
1261 if (ScalarVT != MVT::f32)
1264 SelectionDAG &DAG = DCI.DAG;
1267 SDValue Src = N->getOperand(0);
1268 EVT SrcVT = Src.getValueType();
1270 // TODO: We could try to match extracting the higher bytes, which would be
1271 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1272 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1273 // about in practice.
1274 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1275 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1276 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1277 DCI.AddToWorklist(Cvt.getNode());
1282 // We are primarily trying to catch operations on illegal vector types
1283 // before they are expanded.
1284 // For scalars, we can use the more flexible method of checking masked bits
1285 // after legalization.
1286 if (!DCI.isBeforeLegalize() ||
1287 !SrcVT.isVector() ||
1288 SrcVT.getVectorElementType() != MVT::i8) {
1292 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1294 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1296 unsigned NElts = SrcVT.getVectorNumElements();
1297 if (!SrcVT.isSimple() && NElts != 3)
1300 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1301 // prevent a mess from expanding to v4i32 and repacking.
1302 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1303 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1304 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1305 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1306 LoadSDNode *Load = cast<LoadSDNode>(Src);
1308 unsigned AS = Load->getAddressSpace();
1309 unsigned Align = Load->getAlignment();
1310 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1311 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
1313 // Don't try to replace the load if we have to expand it due to alignment
1314 // problems. Otherwise we will end up scalarizing the load, and trying to
1315 // repack into the vector for no real reason.
1316 if (Align < ABIAlignment &&
1317 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1321 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1325 Load->getMemOperand());
1327 // Make sure successors of the original load stay after it by updating
1328 // them to use the new Chain.
1329 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1331 SmallVector<SDValue, 4> Elts;
1332 if (RegVT.isVector())
1333 DAG.ExtractVectorElements(NewLoad, Elts);
1335 Elts.push_back(NewLoad);
1337 SmallVector<SDValue, 4> Ops;
1339 unsigned EltIdx = 0;
1340 for (SDValue Elt : Elts) {
1341 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1342 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1343 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1344 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1345 DCI.AddToWorklist(Cvt.getNode());
1352 assert(Ops.size() == NElts);
1354 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1360 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1362 // This is a variant of
1363 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1365 // The normal DAG combiner will do this, but only if the add has one use since
1366 // that would increase the number of instructions.
1368 // This prevents us from seeing a constant offset that can be folded into a
1369 // memory instruction's addressing mode. If we know the resulting add offset of
1370 // a pointer can be folded into an addressing offset, we can replace the pointer
1371 // operand with the add of new constant offset. This eliminates one of the uses,
1372 // and may allow the remaining use to also be simplified.
1374 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1376 DAGCombinerInfo &DCI) const {
1377 SDValue N0 = N->getOperand(0);
1378 SDValue N1 = N->getOperand(1);
1380 if (N0.getOpcode() != ISD::ADD)
1383 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1387 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1391 const SIInstrInfo *TII =
1392 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1394 // If the resulting offset is too large, we can't fold it into the addressing
1396 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1397 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1400 SelectionDAG &DAG = DCI.DAG;
1402 EVT VT = N->getValueType(0);
1404 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1405 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1407 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1410 SDValue SITargetLowering::performAndCombine(SDNode *N,
1411 DAGCombinerInfo &DCI) const {
1412 if (DCI.isBeforeLegalize())
1415 SelectionDAG &DAG = DCI.DAG;
1417 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1418 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1419 SDValue LHS = N->getOperand(0);
1420 SDValue RHS = N->getOperand(1);
1422 if (LHS.getOpcode() == ISD::SETCC &&
1423 RHS.getOpcode() == ISD::SETCC) {
1424 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1425 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1427 SDValue X = LHS.getOperand(0);
1428 SDValue Y = RHS.getOperand(0);
1429 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1432 if (LCC == ISD::SETO) {
1433 if (X != LHS.getOperand(1))
1436 if (RCC == ISD::SETUNE) {
1437 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1438 if (!C1 || !C1->isInfinity() || C1->isNegative())
1441 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1442 SIInstrFlags::N_SUBNORMAL |
1443 SIInstrFlags::N_ZERO |
1444 SIInstrFlags::P_ZERO |
1445 SIInstrFlags::P_SUBNORMAL |
1446 SIInstrFlags::P_NORMAL;
1448 static_assert(((~(SIInstrFlags::S_NAN |
1449 SIInstrFlags::Q_NAN |
1450 SIInstrFlags::N_INFINITY |
1451 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1454 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1455 X, DAG.getConstant(Mask, MVT::i32));
1463 SDValue SITargetLowering::performOrCombine(SDNode *N,
1464 DAGCombinerInfo &DCI) const {
1465 SelectionDAG &DAG = DCI.DAG;
1466 SDValue LHS = N->getOperand(0);
1467 SDValue RHS = N->getOperand(1);
1469 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1470 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1471 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1472 SDValue Src = LHS.getOperand(0);
1473 if (Src != RHS.getOperand(0))
1476 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1477 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1481 // Only 10 bits are used.
1482 static const uint32_t MaxMask = 0x3ff;
1484 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1485 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1486 Src, DAG.getConstant(NewMask, MVT::i32));
1492 SDValue SITargetLowering::performClassCombine(SDNode *N,
1493 DAGCombinerInfo &DCI) const {
1494 SelectionDAG &DAG = DCI.DAG;
1495 SDValue Mask = N->getOperand(1);
1497 // fp_class x, 0 -> false
1498 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1499 if (CMask->isNullValue())
1500 return DAG.getConstant(0, MVT::i1);
1506 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1509 return AMDGPUISD::FMAX3;
1510 case AMDGPUISD::SMAX:
1511 return AMDGPUISD::SMAX3;
1512 case AMDGPUISD::UMAX:
1513 return AMDGPUISD::UMAX3;
1515 return AMDGPUISD::FMIN3;
1516 case AMDGPUISD::SMIN:
1517 return AMDGPUISD::SMIN3;
1518 case AMDGPUISD::UMIN:
1519 return AMDGPUISD::UMIN3;
1521 llvm_unreachable("Not a min/max opcode");
1525 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1526 DAGCombinerInfo &DCI) const {
1527 SelectionDAG &DAG = DCI.DAG;
1529 unsigned Opc = N->getOpcode();
1530 SDValue Op0 = N->getOperand(0);
1531 SDValue Op1 = N->getOperand(1);
1533 // Only do this if the inner op has one use since this will just increases
1534 // register pressure for no benefit.
1536 // max(max(a, b), c)
1537 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1539 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1547 // max(a, max(b, c))
1548 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1550 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1561 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1562 DAGCombinerInfo &DCI) const {
1563 SelectionDAG &DAG = DCI.DAG;
1566 SDValue LHS = N->getOperand(0);
1567 SDValue RHS = N->getOperand(1);
1568 EVT VT = LHS.getValueType();
1570 if (VT != MVT::f32 && VT != MVT::f64)
1573 // Match isinf pattern
1574 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1575 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1576 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1577 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1581 const APFloat &APF = CRHS->getValueAPF();
1582 if (APF.isInfinity() && !APF.isNegative()) {
1583 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1584 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1,
1585 LHS.getOperand(0), DAG.getConstant(Mask, MVT::i32));
1592 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1593 DAGCombinerInfo &DCI) const {
1594 SelectionDAG &DAG = DCI.DAG;
1597 switch (N->getOpcode()) {
1599 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1601 return performSetCCCombine(N, DCI);
1602 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1604 case AMDGPUISD::SMAX:
1605 case AMDGPUISD::SMIN:
1606 case AMDGPUISD::UMAX:
1607 case AMDGPUISD::UMIN: {
1608 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1609 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1610 return performMin3Max3Combine(N, DCI);
1614 case AMDGPUISD::CVT_F32_UBYTE0:
1615 case AMDGPUISD::CVT_F32_UBYTE1:
1616 case AMDGPUISD::CVT_F32_UBYTE2:
1617 case AMDGPUISD::CVT_F32_UBYTE3: {
1618 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1620 SDValue Src = N->getOperand(0);
1621 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1623 APInt KnownZero, KnownOne;
1624 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1625 !DCI.isBeforeLegalizeOps());
1626 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1627 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1628 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1629 DCI.CommitTargetLoweringOpt(TLO);
1635 case ISD::UINT_TO_FP: {
1636 return performUCharToFloatCombine(N, DCI);
1639 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1642 EVT VT = N->getValueType(0);
1646 // Only do this if we are not trying to support denormals. v_mad_f32 does
1647 // not support denormals ever.
1648 if (Subtarget->hasFP32Denormals())
1651 SDValue LHS = N->getOperand(0);
1652 SDValue RHS = N->getOperand(1);
1654 // These should really be instruction patterns, but writing patterns with
1655 // source modiifiers is a pain.
1657 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1658 if (LHS.getOpcode() == ISD::FADD) {
1659 SDValue A = LHS.getOperand(0);
1660 if (A == LHS.getOperand(1)) {
1661 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1662 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1666 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1667 if (RHS.getOpcode() == ISD::FADD) {
1668 SDValue A = RHS.getOperand(0);
1669 if (A == RHS.getOperand(1)) {
1670 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1671 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1678 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1681 EVT VT = N->getValueType(0);
1683 // Try to get the fneg to fold into the source modifier. This undoes generic
1684 // DAG combines and folds them into the mad.
1686 // Only do this if we are not trying to support denormals. v_mad_f32 does
1687 // not support denormals ever.
1688 if (VT == MVT::f32 &&
1689 !Subtarget->hasFP32Denormals()) {
1690 SDValue LHS = N->getOperand(0);
1691 SDValue RHS = N->getOperand(1);
1692 if (LHS.getOpcode() == ISD::FADD) {
1693 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1695 SDValue A = LHS.getOperand(0);
1696 if (A == LHS.getOperand(1)) {
1697 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1698 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1700 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1704 if (RHS.getOpcode() == ISD::FADD) {
1705 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1707 SDValue A = RHS.getOperand(0);
1708 if (A == RHS.getOperand(1)) {
1709 const SDValue NegTwo = DAG.getConstantFP(-2.0, MVT::f32);
1710 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1722 case ISD::ATOMIC_LOAD:
1723 case ISD::ATOMIC_STORE:
1724 case ISD::ATOMIC_CMP_SWAP:
1725 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1726 case ISD::ATOMIC_SWAP:
1727 case ISD::ATOMIC_LOAD_ADD:
1728 case ISD::ATOMIC_LOAD_SUB:
1729 case ISD::ATOMIC_LOAD_AND:
1730 case ISD::ATOMIC_LOAD_OR:
1731 case ISD::ATOMIC_LOAD_XOR:
1732 case ISD::ATOMIC_LOAD_NAND:
1733 case ISD::ATOMIC_LOAD_MIN:
1734 case ISD::ATOMIC_LOAD_MAX:
1735 case ISD::ATOMIC_LOAD_UMIN:
1736 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1737 if (DCI.isBeforeLegalize())
1740 MemSDNode *MemNode = cast<MemSDNode>(N);
1741 SDValue Ptr = MemNode->getBasePtr();
1743 // TODO: We could also do this for multiplies.
1744 unsigned AS = MemNode->getAddressSpace();
1745 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1746 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1748 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
1750 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1751 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1757 return performAndCombine(N, DCI);
1759 return performOrCombine(N, DCI);
1760 case AMDGPUISD::FP_CLASS:
1761 return performClassCombine(N, DCI);
1763 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1766 /// \brief Test if RegClass is one of the VSrc classes
1767 static bool isVSrc(unsigned RegClass) {
1769 default: return false;
1770 case AMDGPU::VS_32RegClassID:
1771 case AMDGPU::VS_64RegClassID:
1776 /// \brief Analyze the possible immediate value Op
1778 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1779 /// and the immediate value if it's a literal immediate
1780 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1782 const SIInstrInfo *TII =
1783 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1785 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1786 if (TII->isInlineConstant(Node->getAPIntValue()))
1789 uint64_t Val = Node->getZExtValue();
1790 return isUInt<32>(Val) ? Val : -1;
1793 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1794 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1797 if (Node->getValueType(0) == MVT::f32)
1798 return FloatToBits(Node->getValueAPF().convertToFloat());
1806 const TargetRegisterClass *
1807 SITargetLowering::getRegClassForNode(SelectionDAG &DAG,
1808 const SDValue &Op) const {
1809 const SIInstrInfo *TII =
1810 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1811 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1813 if (!Op->isMachineOpcode()) {
1814 switch(Op->getOpcode()) {
1815 case ISD::CopyFromReg: {
1816 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1817 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1818 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1819 return MRI.getRegClass(Reg);
1821 return TRI.getPhysRegClass(Reg);
1823 default: return nullptr;
1826 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1827 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1828 if (OpClassID != -1) {
1829 return TRI.getRegClass(OpClassID);
1831 switch(Op.getMachineOpcode()) {
1832 case AMDGPU::COPY_TO_REGCLASS:
1833 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1834 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1836 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1837 // class, then the register class for the value could be either a
1838 // VReg or and SReg. In order to get a more accurate
1839 if (isVSrc(OpClassID))
1840 return getRegClassForNode(DAG, Op.getOperand(0));
1842 return TRI.getRegClass(OpClassID);
1843 case AMDGPU::EXTRACT_SUBREG: {
1844 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1845 const TargetRegisterClass *SuperClass =
1846 getRegClassForNode(DAG, Op.getOperand(0));
1847 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1849 case AMDGPU::REG_SEQUENCE:
1850 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1851 return TRI.getRegClass(
1852 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1854 return getRegClassFor(Op.getSimpleValueType());
1858 /// \brief Does "Op" fit into register class "RegClass" ?
1859 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1860 unsigned RegClass) const {
1861 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
1862 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1866 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1869 /// \brief Helper function for adjustWritemask
1870 static unsigned SubIdx2Lane(unsigned Idx) {
1873 case AMDGPU::sub0: return 0;
1874 case AMDGPU::sub1: return 1;
1875 case AMDGPU::sub2: return 2;
1876 case AMDGPU::sub3: return 3;
1880 /// \brief Adjust the writemask of MIMG instructions
1881 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1882 SelectionDAG &DAG) const {
1883 SDNode *Users[4] = { };
1885 unsigned OldDmask = Node->getConstantOperandVal(0);
1886 unsigned NewDmask = 0;
1888 // Try to figure out the used register components
1889 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1892 // Abort if we can't understand the usage
1893 if (!I->isMachineOpcode() ||
1894 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1897 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1898 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1899 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1901 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1903 // Set which texture component corresponds to the lane.
1905 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1907 Comp = countTrailingZeros(Dmask);
1908 Dmask &= ~(1 << Comp);
1911 // Abort if we have more than one user per component
1916 NewDmask |= 1 << Comp;
1919 // Abort if there's no change
1920 if (NewDmask == OldDmask)
1923 // Adjust the writemask in the node
1924 std::vector<SDValue> Ops;
1925 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1926 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
1927 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1929 // If we only got one lane, replace it with a copy
1930 // (if NewDmask has only one bit set...)
1931 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1932 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, MVT::i32);
1933 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1934 SDLoc(), Users[Lane]->getValueType(0),
1935 SDValue(Node, 0), RC);
1936 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1940 // Update the users of the node with the new indices
1941 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1943 SDNode *User = Users[i];
1947 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1948 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1952 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1953 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1954 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1959 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1960 /// with frame index operands.
1961 /// LLVM assumes that inputs are to these instructions are registers.
1962 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1963 SelectionDAG &DAG) const {
1965 SmallVector<SDValue, 8> Ops;
1966 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1967 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1968 Ops.push_back(Node->getOperand(i));
1973 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1974 Node->getOperand(i).getValueType(),
1975 Node->getOperand(i)), 0));
1978 DAG.UpdateNodeOperands(Node, Ops);
1981 /// \brief Fold the instructions after selecting them.
1982 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1983 SelectionDAG &DAG) const {
1984 const SIInstrInfo *TII =
1985 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1986 Node = AdjustRegClass(Node, DAG);
1988 if (TII->isMIMG(Node->getMachineOpcode()))
1989 adjustWritemask(Node, DAG);
1991 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1992 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1993 legalizeTargetIndependentNode(Node, DAG);
1999 /// \brief Assign the register class depending on the number of
2000 /// bits set in the writemask
2001 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2002 SDNode *Node) const {
2003 const SIInstrInfo *TII =
2004 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2006 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2007 TII->legalizeOperands(MI);
2009 if (TII->isMIMG(MI->getOpcode())) {
2010 unsigned VReg = MI->getOperand(0).getReg();
2011 unsigned Writemask = MI->getOperand(1).getImm();
2012 unsigned BitsSet = 0;
2013 for (unsigned i = 0; i < 4; ++i)
2014 BitsSet += Writemask & (1 << i) ? 1 : 0;
2016 const TargetRegisterClass *RC;
2019 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
2020 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2021 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2024 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2025 MI->setDesc(TII->get(NewOpcode));
2026 MRI.setRegClass(VReg, RC);
2030 // Replace unused atomics with the no return version.
2031 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2032 if (NoRetAtomicOp != -1) {
2033 if (!Node->hasAnyUseOfValue(0)) {
2034 MI->setDesc(TII->get(NoRetAtomicOp));
2035 MI->RemoveOperand(0);
2042 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2043 SDValue K = DAG.getTargetConstant(Val, MVT::i32);
2044 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2047 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2049 SDValue Ptr) const {
2050 const SIInstrInfo *TII =
2051 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2053 // XXX - Workaround for moveToVALU not handling different register class
2054 // inserts for REG_SEQUENCE.
2056 // Build the half of the subregister with the constants.
2057 const SDValue Ops0[] = {
2058 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
2059 buildSMovImm32(DAG, DL, 0),
2060 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2061 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2062 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
2065 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2066 MVT::v2i32, Ops0), 0);
2068 // Combine the constants and the pointer.
2069 const SDValue Ops1[] = {
2070 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2072 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2074 DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
2077 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2079 const SDValue Ops[] = {
2080 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2082 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2083 buildSMovImm32(DAG, DL, 0),
2084 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2085 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2086 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2089 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2094 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2095 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2096 /// of the resource descriptor) to create an offset, which is added to the
2097 /// resource ponter.
2098 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2101 uint32_t RsrcDword1,
2102 uint64_t RsrcDword2And3) const {
2103 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2104 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2106 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2107 DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2110 SDValue DataLo = buildSMovImm32(DAG, DL,
2111 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2112 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2114 const SDValue Ops[] = {
2115 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2117 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2119 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2121 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2123 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2126 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2129 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2131 SDValue Ptr) const {
2132 const SIInstrInfo *TII =
2133 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2134 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2137 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2140 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2141 SelectionDAG &DAG) const {
2144 unsigned NewOpcode = N->getMachineOpcode();
2146 switch (N->getMachineOpcode()) {
2148 case AMDGPU::S_LOAD_DWORD_IMM:
2149 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2151 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2152 if (NewOpcode == N->getMachineOpcode()) {
2153 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2156 case AMDGPU::S_LOAD_DWORDX4_IMM:
2157 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2158 if (NewOpcode == N->getMachineOpcode()) {
2159 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2161 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2164 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2166 const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2167 SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2168 MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2170 SmallVector<SDValue, 8> Ops;
2171 Ops.push_back(SDValue(RSrc, 0));
2172 Ops.push_back(N->getOperand(0));
2173 Ops.push_back(DAG.getTargetConstant(0, MVT::i32)); // soffset
2175 // The immediate offset is in dwords on SI and in bytes on VI.
2176 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
2177 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue(), MVT::i32));
2179 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue() << 2, MVT::i32));
2181 // Copy remaining operands so we keep any chain and glue nodes that follow
2182 // the normal operands.
2183 Ops.append(N->op_begin() + 2, N->op_end());
2185 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2190 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2191 const TargetRegisterClass *RC,
2192 unsigned Reg, EVT VT) const {
2193 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2195 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2196 cast<RegisterSDNode>(VReg)->getReg(), VT);