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 AMDGPUTargetLowering(TM) {
40 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
41 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
43 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
44 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
46 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
47 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
49 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
50 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
51 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
53 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
54 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
56 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
57 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
59 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
60 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
62 computeRegisterProperties();
64 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
69 setOperationAction(ISD::ADD, MVT::i32, Legal);
70 setOperationAction(ISD::ADDC, MVT::i32, Legal);
71 setOperationAction(ISD::ADDE, MVT::i32, Legal);
72 setOperationAction(ISD::SUBC, MVT::i32, Legal);
73 setOperationAction(ISD::SUBE, MVT::i32, Legal);
75 setOperationAction(ISD::FSIN, MVT::f32, Custom);
76 setOperationAction(ISD::FCOS, MVT::f32, Custom);
78 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
79 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
80 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
81 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
83 // We need to custom lower vector stores from local memory
84 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
85 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
86 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
88 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
89 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
91 setOperationAction(ISD::STORE, MVT::i1, Custom);
92 setOperationAction(ISD::STORE, MVT::i32, Custom);
93 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
94 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
96 setOperationAction(ISD::SELECT, MVT::i64, Custom);
97 setOperationAction(ISD::SELECT, MVT::f64, Promote);
98 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
100 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
101 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
102 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
103 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
105 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
106 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
108 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
110 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
111 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
114 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
115 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
125 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
128 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
130 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
131 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
133 for (MVT VT : MVT::integer_valuetypes()) {
134 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
135 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Custom);
136 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Custom);
137 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
139 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
140 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Custom);
141 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Custom);
142 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
144 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
145 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Custom);
146 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Custom);
147 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
150 for (MVT VT : MVT::integer_vector_valuetypes()) {
151 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
152 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
155 for (MVT VT : MVT::fp_valuetypes())
156 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
158 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
159 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
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 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
207 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
208 setOperationAction(ISD::FTRUNC, VT, Expand);
209 setOperationAction(ISD::FCEIL, VT, Expand);
210 setOperationAction(ISD::FFLOOR, VT, Expand);
213 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
214 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
215 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
216 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
217 setOperationAction(ISD::FRINT, MVT::f64, Legal);
220 setOperationAction(ISD::FDIV, MVT::f32, Custom);
222 setTargetDAGCombine(ISD::FADD);
223 setTargetDAGCombine(ISD::FSUB);
224 setTargetDAGCombine(ISD::FMINNUM);
225 setTargetDAGCombine(ISD::FMAXNUM);
226 setTargetDAGCombine(ISD::SELECT_CC);
227 setTargetDAGCombine(ISD::SETCC);
228 setTargetDAGCombine(ISD::AND);
229 setTargetDAGCombine(ISD::OR);
230 setTargetDAGCombine(ISD::UINT_TO_FP);
232 // All memory operations. Some folding on the pointer operand is done to help
233 // matching the constant offsets in the addressing modes.
234 setTargetDAGCombine(ISD::LOAD);
235 setTargetDAGCombine(ISD::STORE);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD);
237 setTargetDAGCombine(ISD::ATOMIC_STORE);
238 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
239 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
240 setTargetDAGCombine(ISD::ATOMIC_SWAP);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
243 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
245 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
246 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
247 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
248 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
252 setSchedulingPreference(Sched::RegPressure);
255 //===----------------------------------------------------------------------===//
256 // TargetLowering queries
257 //===----------------------------------------------------------------------===//
259 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
261 // SI has some legal vector types, but no legal vector operations. Say no
262 // shuffles are legal in order to prefer scalarizing some vector operations.
266 // FIXME: This really needs an address space argument. The immediate offset
267 // size is different for different sets of memory instruction sets.
269 // The single offset DS instructions have a 16-bit unsigned byte offset.
271 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
272 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
273 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
275 // SMRD instructions have an 8-bit, dword offset.
277 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
279 // No global is ever allowed as a base.
283 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
285 if (!isUInt<16>(AM.BaseOffs))
290 case 0: // "r+i" or just "i", depending on HasBaseReg.
293 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
295 // Otherwise we have r+r or r+i.
298 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
302 default: // Don't allow n * r
309 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
312 bool *IsFast) const {
316 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
317 // which isn't a simple VT.
318 if (!VT.isSimple() || VT == MVT::Other)
321 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
322 // see what for specifically. The wording everywhere else seems to be the
325 // XXX - The only mention I see of this in the ISA manual is for LDS direct
326 // reads the "byte address and must be dword aligned". Is it also true for the
327 // normal loads and stores?
328 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
329 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
330 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
331 // with adjacent offsets.
332 return Align % 4 == 0;
335 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
336 // byte-address are ignored, thus forcing Dword alignment.
337 // This applies to private, global, and constant memory.
340 return VT.bitsGT(MVT::i32);
343 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
344 unsigned SrcAlign, bool IsMemset,
347 MachineFunction &MF) const {
348 // FIXME: Should account for address space here.
350 // The default fallback uses the private pointer size as a guess for a type to
351 // use. Make sure we switch these to 64-bit accesses.
353 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
356 if (Size >= 8 && DstAlign >= 4)
363 TargetLoweringBase::LegalizeTypeAction
364 SITargetLowering::getPreferredVectorAction(EVT VT) const {
365 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
366 return TypeSplitVector;
368 return TargetLoweringBase::getPreferredVectorAction(VT);
371 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
373 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
374 getTargetMachine().getSubtargetImpl()->getInstrInfo());
375 return TII->isInlineConstant(Imm);
378 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
379 SDLoc SL, SDValue Chain,
380 unsigned Offset, bool Signed) const {
381 const DataLayout *DL = getDataLayout();
382 MachineFunction &MF = DAG.getMachineFunction();
383 const SIRegisterInfo *TRI =
384 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
385 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
387 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
389 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
390 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
391 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
392 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
393 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
394 DAG.getConstant(Offset, MVT::i64));
395 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
396 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
398 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
399 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
401 true, // isNonTemporal
403 DL->getABITypeAlignment(Ty)); // Alignment
406 SDValue SITargetLowering::LowerFormalArguments(
408 CallingConv::ID CallConv,
410 const SmallVectorImpl<ISD::InputArg> &Ins,
411 SDLoc DL, SelectionDAG &DAG,
412 SmallVectorImpl<SDValue> &InVals) const {
414 const TargetMachine &TM = getTargetMachine();
415 const SIRegisterInfo *TRI =
416 static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
418 MachineFunction &MF = DAG.getMachineFunction();
419 FunctionType *FType = MF.getFunction()->getFunctionType();
420 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
422 assert(CallConv == CallingConv::C);
424 SmallVector<ISD::InputArg, 16> Splits;
425 BitVector Skipped(Ins.size());
427 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
428 const ISD::InputArg &Arg = Ins[i];
430 // First check if it's a PS input addr
431 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
432 !Arg.Flags.isByVal()) {
434 assert((PSInputNum <= 15) && "Too many PS inputs!");
437 // We can savely skip PS inputs
443 Info->PSInputAddr |= 1 << PSInputNum++;
446 // Second split vertices into their elements
447 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
448 ISD::InputArg NewArg = Arg;
449 NewArg.Flags.setSplit();
450 NewArg.VT = Arg.VT.getVectorElementType();
452 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
453 // three or five element vertex only needs three or five registers,
454 // NOT four or eigth.
455 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
456 unsigned NumElements = ParamType->getVectorNumElements();
458 for (unsigned j = 0; j != NumElements; ++j) {
459 Splits.push_back(NewArg);
460 NewArg.PartOffset += NewArg.VT.getStoreSize();
463 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
464 Splits.push_back(Arg);
468 SmallVector<CCValAssign, 16> ArgLocs;
469 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
472 // At least one interpolation mode must be enabled or else the GPU will hang.
473 if (Info->getShaderType() == ShaderType::PIXEL &&
474 (Info->PSInputAddr & 0x7F) == 0) {
475 Info->PSInputAddr |= 1;
476 CCInfo.AllocateReg(AMDGPU::VGPR0);
477 CCInfo.AllocateReg(AMDGPU::VGPR1);
480 // The pointer to the list of arguments is stored in SGPR0, SGPR1
481 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
482 if (Info->getShaderType() == ShaderType::COMPUTE) {
483 if (Subtarget->isAmdHsaOS())
484 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
486 Info->NumUserSGPRs = 4;
488 unsigned InputPtrReg =
489 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
490 unsigned InputPtrRegLo =
491 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
492 unsigned InputPtrRegHi =
493 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
495 unsigned ScratchPtrReg =
496 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
497 unsigned ScratchPtrRegLo =
498 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
499 unsigned ScratchPtrRegHi =
500 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
502 CCInfo.AllocateReg(InputPtrRegLo);
503 CCInfo.AllocateReg(InputPtrRegHi);
504 CCInfo.AllocateReg(ScratchPtrRegLo);
505 CCInfo.AllocateReg(ScratchPtrRegHi);
506 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
507 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
510 if (Info->getShaderType() == ShaderType::COMPUTE) {
511 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
515 AnalyzeFormalArguments(CCInfo, Splits);
517 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
519 const ISD::InputArg &Arg = Ins[i];
521 InVals.push_back(DAG.getUNDEF(Arg.VT));
525 CCValAssign &VA = ArgLocs[ArgIdx++];
526 MVT VT = VA.getLocVT();
530 EVT MemVT = Splits[i].VT;
531 const unsigned Offset = 36 + VA.getLocMemOffset();
532 // The first 36 bytes of the input buffer contains information about
533 // thread group and global sizes.
534 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
535 Offset, Ins[i].Flags.isSExt());
537 const PointerType *ParamTy =
538 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
539 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
540 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
541 // On SI local pointers are just offsets into LDS, so they are always
542 // less than 16-bits. On CI and newer they could potentially be
543 // real pointers, so we can't guarantee their size.
544 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
545 DAG.getValueType(MVT::i16));
548 InVals.push_back(Arg);
549 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
552 assert(VA.isRegLoc() && "Parameter must be in a register!");
554 unsigned Reg = VA.getLocReg();
556 if (VT == MVT::i64) {
557 // For now assume it is a pointer
558 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
559 &AMDGPU::SReg_64RegClass);
560 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
561 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
565 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
567 Reg = MF.addLiveIn(Reg, RC);
568 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
570 if (Arg.VT.isVector()) {
572 // Build a vector from the registers
573 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
574 unsigned NumElements = ParamType->getVectorNumElements();
576 SmallVector<SDValue, 4> Regs;
578 for (unsigned j = 1; j != NumElements; ++j) {
579 Reg = ArgLocs[ArgIdx++].getLocReg();
580 Reg = MF.addLiveIn(Reg, RC);
581 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
584 // Fill up the missing vector elements
585 NumElements = Arg.VT.getVectorNumElements() - NumElements;
586 for (unsigned j = 0; j != NumElements; ++j)
587 Regs.push_back(DAG.getUNDEF(VT));
589 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
593 InVals.push_back(Val);
598 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
599 MachineInstr * MI, MachineBasicBlock * BB) const {
601 MachineBasicBlock::iterator I = *MI;
602 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
603 getTargetMachine().getSubtargetImpl()->getInstrInfo());
605 switch (MI->getOpcode()) {
607 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
608 case AMDGPU::BRANCH: return BB;
609 case AMDGPU::V_SUB_F64: {
610 unsigned DestReg = MI->getOperand(0).getReg();
611 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
612 .addImm(0) // SRC0 modifiers
613 .addReg(MI->getOperand(1).getReg())
614 .addImm(1) // SRC1 modifiers
615 .addReg(MI->getOperand(2).getReg())
618 MI->eraseFromParent();
621 case AMDGPU::SI_RegisterStorePseudo: {
622 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
623 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
624 MachineInstrBuilder MIB =
625 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
627 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
628 MIB.addOperand(MI->getOperand(i));
630 MI->eraseFromParent();
637 EVT SITargetLowering::getSetCCResultType(LLVMContext &Ctx, EVT VT) const {
638 if (!VT.isVector()) {
641 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
644 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
648 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
649 VT = VT.getScalarType();
654 switch (VT.getSimpleVT().SimpleTy) {
656 return false; /* There is V_MAD_F32 for f32 */
666 //===----------------------------------------------------------------------===//
667 // Custom DAG Lowering Operations
668 //===----------------------------------------------------------------------===//
670 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
671 switch (Op.getOpcode()) {
672 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
673 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
674 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
676 SDValue Result = LowerLOAD(Op, DAG);
677 assert((!Result.getNode() ||
678 Result.getNode()->getNumValues() == 2) &&
679 "Load should return a value and a chain");
685 return LowerTrig(Op, DAG);
686 case ISD::SELECT: return LowerSELECT(Op, DAG);
687 case ISD::FDIV: return LowerFDIV(Op, DAG);
688 case ISD::STORE: return LowerSTORE(Op, DAG);
689 case ISD::GlobalAddress: {
690 MachineFunction &MF = DAG.getMachineFunction();
691 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
692 return LowerGlobalAddress(MFI, Op, DAG);
694 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
695 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
700 /// \brief Helper function for LowerBRCOND
701 static SDNode *findUser(SDValue Value, unsigned Opcode) {
703 SDNode *Parent = Value.getNode();
704 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
707 if (I.getUse().get() != Value)
710 if (I->getOpcode() == Opcode)
716 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
718 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
719 unsigned FrameIndex = FINode->getIndex();
721 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
724 /// This transforms the control flow intrinsics to get the branch destination as
725 /// last parameter, also switches branch target with BR if the need arise
726 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
727 SelectionDAG &DAG) const {
731 SDNode *Intr = BRCOND.getOperand(1).getNode();
732 SDValue Target = BRCOND.getOperand(2);
733 SDNode *BR = nullptr;
735 if (Intr->getOpcode() == ISD::SETCC) {
736 // As long as we negate the condition everything is fine
737 SDNode *SetCC = Intr;
738 assert(SetCC->getConstantOperandVal(1) == 1);
739 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
741 Intr = SetCC->getOperand(0).getNode();
744 // Get the target from BR if we don't negate the condition
745 BR = findUser(BRCOND, ISD::BR);
746 Target = BR->getOperand(1);
749 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
751 // Build the result and
752 SmallVector<EVT, 4> Res;
753 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
754 Res.push_back(Intr->getValueType(i));
756 // operands of the new intrinsic call
757 SmallVector<SDValue, 4> Ops;
758 Ops.push_back(BRCOND.getOperand(0));
759 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
760 Ops.push_back(Intr->getOperand(i));
761 Ops.push_back(Target);
763 // build the new intrinsic call
764 SDNode *Result = DAG.getNode(
765 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
766 DAG.getVTList(Res), Ops).getNode();
769 // Give the branch instruction our target
774 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
775 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
776 BR = NewBR.getNode();
779 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
781 // Copy the intrinsic results to registers
782 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
783 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
787 Chain = DAG.getCopyToReg(
789 CopyToReg->getOperand(1),
790 SDValue(Result, i - 1),
793 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
796 // Remove the old intrinsic from the chain
797 DAG.ReplaceAllUsesOfValueWith(
798 SDValue(Intr, Intr->getNumValues() - 1),
799 Intr->getOperand(0));
804 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
806 SelectionDAG &DAG) const {
807 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
809 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
810 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
813 const GlobalValue *GV = GSD->getGlobal();
814 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
816 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
817 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
819 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
820 DAG.getConstant(0, MVT::i32));
821 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
822 DAG.getConstant(1, MVT::i32));
824 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
826 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
827 PtrHi, DAG.getConstant(0, MVT::i32),
828 SDValue(Lo.getNode(), 1));
829 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
832 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
833 SelectionDAG &DAG) const {
834 MachineFunction &MF = DAG.getMachineFunction();
835 const SIRegisterInfo *TRI =
836 static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
838 EVT VT = Op.getValueType();
840 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
842 switch (IntrinsicID) {
843 case Intrinsic::r600_read_ngroups_x:
844 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
845 SI::KernelInputOffsets::NGROUPS_X, false);
846 case Intrinsic::r600_read_ngroups_y:
847 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
848 SI::KernelInputOffsets::NGROUPS_Y, false);
849 case Intrinsic::r600_read_ngroups_z:
850 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
851 SI::KernelInputOffsets::NGROUPS_Z, false);
852 case Intrinsic::r600_read_global_size_x:
853 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
854 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
855 case Intrinsic::r600_read_global_size_y:
856 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
857 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
858 case Intrinsic::r600_read_global_size_z:
859 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
860 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
861 case Intrinsic::r600_read_local_size_x:
862 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
863 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
864 case Intrinsic::r600_read_local_size_y:
865 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
866 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
867 case Intrinsic::r600_read_local_size_z:
868 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
869 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
871 case Intrinsic::AMDGPU_read_workdim:
872 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
873 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
876 case Intrinsic::r600_read_tgid_x:
877 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
878 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
879 case Intrinsic::r600_read_tgid_y:
880 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
881 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
882 case Intrinsic::r600_read_tgid_z:
883 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
884 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
885 case Intrinsic::r600_read_tidig_x:
886 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
887 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
888 case Intrinsic::r600_read_tidig_y:
889 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
890 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
891 case Intrinsic::r600_read_tidig_z:
892 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
893 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
894 case AMDGPUIntrinsic::SI_load_const: {
900 MachineMemOperand *MMO = MF.getMachineMemOperand(
901 MachinePointerInfo(),
902 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
903 VT.getStoreSize(), 4);
904 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
905 Op->getVTList(), Ops, VT, MMO);
907 case AMDGPUIntrinsic::SI_sample:
908 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
909 case AMDGPUIntrinsic::SI_sampleb:
910 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
911 case AMDGPUIntrinsic::SI_sampled:
912 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
913 case AMDGPUIntrinsic::SI_samplel:
914 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
915 case AMDGPUIntrinsic::SI_vs_load_input:
916 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
921 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
925 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
926 SelectionDAG &DAG) const {
927 MachineFunction &MF = DAG.getMachineFunction();
928 SDValue Chain = Op.getOperand(0);
929 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
931 switch (IntrinsicID) {
932 case AMDGPUIntrinsic::SI_tbuffer_store: {
951 EVT VT = Op.getOperand(3).getValueType();
953 MachineMemOperand *MMO = MF.getMachineMemOperand(
954 MachinePointerInfo(),
955 MachineMemOperand::MOStore,
956 VT.getStoreSize(), 4);
957 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
958 Op->getVTList(), Ops, VT, MMO);
965 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
967 LoadSDNode *Load = cast<LoadSDNode>(Op);
969 if (Op.getValueType().isVector()) {
970 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
971 "Custom lowering for non-i32 vectors hasn't been implemented.");
972 unsigned NumElements = Op.getValueType().getVectorNumElements();
973 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
974 switch (Load->getAddressSpace()) {
976 case AMDGPUAS::GLOBAL_ADDRESS:
977 case AMDGPUAS::PRIVATE_ADDRESS:
978 // v4 loads are supported for private and global memory.
979 if (NumElements <= 4)
982 case AMDGPUAS::LOCAL_ADDRESS:
983 return ScalarizeVectorLoad(Op, DAG);
987 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
990 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
992 SelectionDAG &DAG) const {
993 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
999 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1000 if (Op.getValueType() != MVT::i64)
1004 SDValue Cond = Op.getOperand(0);
1006 SDValue Zero = DAG.getConstant(0, MVT::i32);
1007 SDValue One = DAG.getConstant(1, MVT::i32);
1009 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1010 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1012 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1013 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1015 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1017 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1018 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1020 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1022 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1023 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1026 // Catch division cases where we can use shortcuts with rcp and rsq
1028 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1030 SDValue LHS = Op.getOperand(0);
1031 SDValue RHS = Op.getOperand(1);
1032 EVT VT = Op.getValueType();
1033 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1035 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1036 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1037 CLHS->isExactlyValue(1.0)) {
1038 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1039 // the CI documentation has a worst case error of 1 ulp.
1040 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1041 // use it as long as we aren't trying to use denormals.
1043 // 1.0 / sqrt(x) -> rsq(x)
1045 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1046 // error seems really high at 2^29 ULP.
1047 if (RHS.getOpcode() == ISD::FSQRT)
1048 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1050 // 1.0 / x -> rcp(x)
1051 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1056 // Turn into multiply by the reciprocal.
1057 // x / y -> x * (1.0 / y)
1058 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1059 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1065 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1066 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1067 if (FastLowered.getNode())
1070 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1071 // selection error for now rather than do something incorrect.
1072 if (Subtarget->hasFP32Denormals())
1076 SDValue LHS = Op.getOperand(0);
1077 SDValue RHS = Op.getOperand(1);
1079 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1081 const APFloat K0Val(BitsToFloat(0x6f800000));
1082 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1084 const APFloat K1Val(BitsToFloat(0x2f800000));
1085 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1087 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1089 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1091 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1093 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1095 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1097 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1099 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1101 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1104 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1108 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1109 EVT VT = Op.getValueType();
1112 return LowerFDIV32(Op, DAG);
1115 return LowerFDIV64(Op, DAG);
1117 llvm_unreachable("Unexpected type for fdiv");
1120 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1122 StoreSDNode *Store = cast<StoreSDNode>(Op);
1123 EVT VT = Store->getMemoryVT();
1125 // These stores are legal.
1126 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1127 VT.isVector() && VT.getVectorNumElements() == 2 &&
1128 VT.getVectorElementType() == MVT::i32)
1131 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1132 if (VT.isVector() && VT.getVectorNumElements() > 4)
1133 return ScalarizeVectorStore(Op, DAG);
1137 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1141 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1142 return ScalarizeVectorStore(Op, DAG);
1145 return DAG.getTruncStore(Store->getChain(), DL,
1146 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1147 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1152 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1153 EVT VT = Op.getValueType();
1154 SDValue Arg = Op.getOperand(0);
1155 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1156 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1157 DAG.getConstantFP(0.5 / M_PI, VT)));
1159 switch (Op.getOpcode()) {
1161 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1163 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1165 llvm_unreachable("Wrong trig opcode");
1169 //===----------------------------------------------------------------------===//
1170 // Custom DAG optimizations
1171 //===----------------------------------------------------------------------===//
1173 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1174 DAGCombinerInfo &DCI) {
1175 EVT VT = N->getValueType(0);
1176 EVT ScalarVT = VT.getScalarType();
1177 if (ScalarVT != MVT::f32)
1180 SelectionDAG &DAG = DCI.DAG;
1183 SDValue Src = N->getOperand(0);
1184 EVT SrcVT = Src.getValueType();
1186 // TODO: We could try to match extracting the higher bytes, which would be
1187 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1188 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1189 // about in practice.
1190 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1191 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1192 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1193 DCI.AddToWorklist(Cvt.getNode());
1198 // We are primarily trying to catch operations on illegal vector types
1199 // before they are expanded.
1200 // For scalars, we can use the more flexible method of checking masked bits
1201 // after legalization.
1202 if (!DCI.isBeforeLegalize() ||
1203 !SrcVT.isVector() ||
1204 SrcVT.getVectorElementType() != MVT::i8) {
1208 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1210 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1212 unsigned NElts = SrcVT.getVectorNumElements();
1213 if (!SrcVT.isSimple() && NElts != 3)
1216 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1217 // prevent a mess from expanding to v4i32 and repacking.
1218 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1219 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1220 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1221 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1223 LoadSDNode *Load = cast<LoadSDNode>(Src);
1224 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1228 Load->getMemOperand());
1230 // Make sure successors of the original load stay after it by updating
1231 // them to use the new Chain.
1232 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1234 SmallVector<SDValue, 4> Elts;
1235 if (RegVT.isVector())
1236 DAG.ExtractVectorElements(NewLoad, Elts);
1238 Elts.push_back(NewLoad);
1240 SmallVector<SDValue, 4> Ops;
1242 unsigned EltIdx = 0;
1243 for (SDValue Elt : Elts) {
1244 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1245 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1246 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1247 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1248 DCI.AddToWorklist(Cvt.getNode());
1255 assert(Ops.size() == NElts);
1257 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1263 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1265 // This is a variant of
1266 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1268 // The normal DAG combiner will do this, but only if the add has one use since
1269 // that would increase the number of instructions.
1271 // This prevents us from seeing a constant offset that can be folded into a
1272 // memory instruction's addressing mode. If we know the resulting add offset of
1273 // a pointer can be folded into an addressing offset, we can replace the pointer
1274 // operand with the add of new constant offset. This eliminates one of the uses,
1275 // and may allow the remaining use to also be simplified.
1277 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1279 DAGCombinerInfo &DCI) const {
1280 SDValue N0 = N->getOperand(0);
1281 SDValue N1 = N->getOperand(1);
1283 if (N0.getOpcode() != ISD::ADD)
1286 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1290 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1294 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1295 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1297 // If the resulting offset is too large, we can't fold it into the addressing
1299 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1300 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1303 SelectionDAG &DAG = DCI.DAG;
1305 EVT VT = N->getValueType(0);
1307 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1308 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1310 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1313 SDValue SITargetLowering::performAndCombine(SDNode *N,
1314 DAGCombinerInfo &DCI) const {
1315 if (DCI.isBeforeLegalize())
1318 SelectionDAG &DAG = DCI.DAG;
1320 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1321 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1322 SDValue LHS = N->getOperand(0);
1323 SDValue RHS = N->getOperand(1);
1325 if (LHS.getOpcode() == ISD::SETCC &&
1326 RHS.getOpcode() == ISD::SETCC) {
1327 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1328 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1330 SDValue X = LHS.getOperand(0);
1331 SDValue Y = RHS.getOperand(0);
1332 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1335 if (LCC == ISD::SETO) {
1336 if (X != LHS.getOperand(1))
1339 if (RCC == ISD::SETUNE) {
1340 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1341 if (!C1 || !C1->isInfinity() || C1->isNegative())
1344 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1345 SIInstrFlags::N_SUBNORMAL |
1346 SIInstrFlags::N_ZERO |
1347 SIInstrFlags::P_ZERO |
1348 SIInstrFlags::P_SUBNORMAL |
1349 SIInstrFlags::P_NORMAL;
1351 static_assert(((~(SIInstrFlags::S_NAN |
1352 SIInstrFlags::Q_NAN |
1353 SIInstrFlags::N_INFINITY |
1354 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1357 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1358 X, DAG.getConstant(Mask, MVT::i32));
1366 SDValue SITargetLowering::performOrCombine(SDNode *N,
1367 DAGCombinerInfo &DCI) const {
1368 SelectionDAG &DAG = DCI.DAG;
1369 SDValue LHS = N->getOperand(0);
1370 SDValue RHS = N->getOperand(1);
1372 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1373 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1374 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1375 SDValue Src = LHS.getOperand(0);
1376 if (Src != RHS.getOperand(0))
1379 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1380 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1384 // Only 10 bits are used.
1385 static const uint32_t MaxMask = 0x3ff;
1387 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1388 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1389 Src, DAG.getConstant(NewMask, MVT::i32));
1395 SDValue SITargetLowering::performClassCombine(SDNode *N,
1396 DAGCombinerInfo &DCI) const {
1397 SelectionDAG &DAG = DCI.DAG;
1398 SDValue Mask = N->getOperand(1);
1400 // fp_class x, 0 -> false
1401 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1402 if (CMask->isNullValue())
1403 return DAG.getConstant(0, MVT::i1);
1409 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1412 return AMDGPUISD::FMAX3;
1413 case AMDGPUISD::SMAX:
1414 return AMDGPUISD::SMAX3;
1415 case AMDGPUISD::UMAX:
1416 return AMDGPUISD::UMAX3;
1418 return AMDGPUISD::FMIN3;
1419 case AMDGPUISD::SMIN:
1420 return AMDGPUISD::SMIN3;
1421 case AMDGPUISD::UMIN:
1422 return AMDGPUISD::UMIN3;
1424 llvm_unreachable("Not a min/max opcode");
1428 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1429 DAGCombinerInfo &DCI) const {
1430 SelectionDAG &DAG = DCI.DAG;
1432 unsigned Opc = N->getOpcode();
1433 SDValue Op0 = N->getOperand(0);
1434 SDValue Op1 = N->getOperand(1);
1436 // Only do this if the inner op has one use since this will just increases
1437 // register pressure for no benefit.
1439 // max(max(a, b), c)
1440 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1442 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1450 // max(a, max(b, c))
1451 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1453 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1464 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1465 DAGCombinerInfo &DCI) const {
1466 SelectionDAG &DAG = DCI.DAG;
1469 SDValue LHS = N->getOperand(0);
1470 SDValue RHS = N->getOperand(1);
1471 EVT VT = LHS.getValueType();
1473 if (VT != MVT::f32 && VT != MVT::f64)
1476 // Match isinf pattern
1477 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1478 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1479 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1480 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1484 const APFloat &APF = CRHS->getValueAPF();
1485 if (APF.isInfinity() && !APF.isNegative()) {
1486 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1487 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1,
1488 LHS.getOperand(0), DAG.getConstant(Mask, MVT::i32));
1495 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1496 DAGCombinerInfo &DCI) const {
1497 SelectionDAG &DAG = DCI.DAG;
1500 switch (N->getOpcode()) {
1502 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1504 return performSetCCCombine(N, DCI);
1505 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1507 case AMDGPUISD::SMAX:
1508 case AMDGPUISD::SMIN:
1509 case AMDGPUISD::UMAX:
1510 case AMDGPUISD::UMIN: {
1511 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1512 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1513 return performMin3Max3Combine(N, DCI);
1517 case AMDGPUISD::CVT_F32_UBYTE0:
1518 case AMDGPUISD::CVT_F32_UBYTE1:
1519 case AMDGPUISD::CVT_F32_UBYTE2:
1520 case AMDGPUISD::CVT_F32_UBYTE3: {
1521 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1523 SDValue Src = N->getOperand(0);
1524 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1526 APInt KnownZero, KnownOne;
1527 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1528 !DCI.isBeforeLegalizeOps());
1529 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1530 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1531 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1532 DCI.CommitTargetLoweringOpt(TLO);
1538 case ISD::UINT_TO_FP: {
1539 return performUCharToFloatCombine(N, DCI);
1542 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1545 EVT VT = N->getValueType(0);
1549 SDValue LHS = N->getOperand(0);
1550 SDValue RHS = N->getOperand(1);
1552 // These should really be instruction patterns, but writing patterns with
1553 // source modiifiers is a pain.
1555 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1556 if (LHS.getOpcode() == ISD::FADD) {
1557 SDValue A = LHS.getOperand(0);
1558 if (A == LHS.getOperand(1)) {
1559 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1560 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1564 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1565 if (RHS.getOpcode() == ISD::FADD) {
1566 SDValue A = RHS.getOperand(0);
1567 if (A == RHS.getOperand(1)) {
1568 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1569 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1576 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1579 EVT VT = N->getValueType(0);
1581 // Try to get the fneg to fold into the source modifier. This undoes generic
1582 // DAG combines and folds them into the mad.
1583 if (VT == MVT::f32) {
1584 SDValue LHS = N->getOperand(0);
1585 SDValue RHS = N->getOperand(1);
1587 if (LHS.getOpcode() == ISD::FMUL) {
1588 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1590 SDValue A = LHS.getOperand(0);
1591 SDValue B = LHS.getOperand(1);
1592 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1594 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1597 if (RHS.getOpcode() == ISD::FMUL) {
1598 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1600 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1601 SDValue B = RHS.getOperand(1);
1604 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1607 if (LHS.getOpcode() == ISD::FADD) {
1608 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1610 SDValue A = LHS.getOperand(0);
1611 if (A == LHS.getOperand(1)) {
1612 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1613 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1615 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1619 if (RHS.getOpcode() == ISD::FADD) {
1620 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1622 SDValue A = RHS.getOperand(0);
1623 if (A == RHS.getOperand(1)) {
1624 const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
1625 return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1635 case ISD::ATOMIC_LOAD:
1636 case ISD::ATOMIC_STORE:
1637 case ISD::ATOMIC_CMP_SWAP:
1638 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1639 case ISD::ATOMIC_SWAP:
1640 case ISD::ATOMIC_LOAD_ADD:
1641 case ISD::ATOMIC_LOAD_SUB:
1642 case ISD::ATOMIC_LOAD_AND:
1643 case ISD::ATOMIC_LOAD_OR:
1644 case ISD::ATOMIC_LOAD_XOR:
1645 case ISD::ATOMIC_LOAD_NAND:
1646 case ISD::ATOMIC_LOAD_MIN:
1647 case ISD::ATOMIC_LOAD_MAX:
1648 case ISD::ATOMIC_LOAD_UMIN:
1649 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1650 if (DCI.isBeforeLegalize())
1653 MemSDNode *MemNode = cast<MemSDNode>(N);
1654 SDValue Ptr = MemNode->getBasePtr();
1656 // TODO: We could also do this for multiplies.
1657 unsigned AS = MemNode->getAddressSpace();
1658 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1659 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1661 SmallVector<SDValue, 8> NewOps;
1662 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1663 NewOps.push_back(MemNode->getOperand(I));
1665 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1666 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1672 return performAndCombine(N, DCI);
1674 return performOrCombine(N, DCI);
1675 case AMDGPUISD::FP_CLASS:
1676 return performClassCombine(N, DCI);
1678 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1681 /// \brief Test if RegClass is one of the VSrc classes
1682 static bool isVSrc(unsigned RegClass) {
1684 default: return false;
1685 case AMDGPU::VSrc_32RegClassID:
1686 case AMDGPU::VCSrc_32RegClassID:
1687 case AMDGPU::VSrc_64RegClassID:
1688 case AMDGPU::VCSrc_64RegClassID:
1693 /// \brief Analyze the possible immediate value Op
1695 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1696 /// and the immediate value if it's a literal immediate
1697 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1699 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1700 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1702 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1703 if (Node->getZExtValue() >> 32)
1706 if (TII->isInlineConstant(Node->getAPIntValue()))
1709 return Node->getZExtValue();
1712 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1713 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1716 if (Node->getValueType(0) == MVT::f32)
1717 return FloatToBits(Node->getValueAPF().convertToFloat());
1725 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1726 SelectionDAG &DAG, const SDValue &Op) const {
1727 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1728 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1729 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1731 if (!Op->isMachineOpcode()) {
1732 switch(Op->getOpcode()) {
1733 case ISD::CopyFromReg: {
1734 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1735 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1736 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1737 return MRI.getRegClass(Reg);
1739 return TRI.getPhysRegClass(Reg);
1741 default: return nullptr;
1744 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1745 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1746 if (OpClassID != -1) {
1747 return TRI.getRegClass(OpClassID);
1749 switch(Op.getMachineOpcode()) {
1750 case AMDGPU::COPY_TO_REGCLASS:
1751 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1752 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1754 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1755 // class, then the register class for the value could be either a
1756 // VReg or and SReg. In order to get a more accurate
1757 if (isVSrc(OpClassID))
1758 return getRegClassForNode(DAG, Op.getOperand(0));
1760 return TRI.getRegClass(OpClassID);
1761 case AMDGPU::EXTRACT_SUBREG: {
1762 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1763 const TargetRegisterClass *SuperClass =
1764 getRegClassForNode(DAG, Op.getOperand(0));
1765 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1767 case AMDGPU::REG_SEQUENCE:
1768 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1769 return TRI.getRegClass(
1770 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1772 return getRegClassFor(Op.getSimpleValueType());
1776 /// \brief Does "Op" fit into register class "RegClass" ?
1777 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1778 unsigned RegClass) const {
1779 const TargetRegisterInfo *TRI =
1780 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1781 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1785 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1788 /// \brief Helper function for adjustWritemask
1789 static unsigned SubIdx2Lane(unsigned Idx) {
1792 case AMDGPU::sub0: return 0;
1793 case AMDGPU::sub1: return 1;
1794 case AMDGPU::sub2: return 2;
1795 case AMDGPU::sub3: return 3;
1799 /// \brief Adjust the writemask of MIMG instructions
1800 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1801 SelectionDAG &DAG) const {
1802 SDNode *Users[4] = { };
1804 unsigned OldDmask = Node->getConstantOperandVal(0);
1805 unsigned NewDmask = 0;
1807 // Try to figure out the used register components
1808 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1811 // Abort if we can't understand the usage
1812 if (!I->isMachineOpcode() ||
1813 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1816 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1817 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1818 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1820 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1822 // Set which texture component corresponds to the lane.
1824 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1826 Comp = countTrailingZeros(Dmask);
1827 Dmask &= ~(1 << Comp);
1830 // Abort if we have more than one user per component
1835 NewDmask |= 1 << Comp;
1838 // Abort if there's no change
1839 if (NewDmask == OldDmask)
1842 // Adjust the writemask in the node
1843 std::vector<SDValue> Ops;
1844 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1845 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1846 Ops.push_back(Node->getOperand(i));
1847 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1849 // If we only got one lane, replace it with a copy
1850 // (if NewDmask has only one bit set...)
1851 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1852 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, MVT::i32);
1853 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1854 SDLoc(), Users[Lane]->getValueType(0),
1855 SDValue(Node, 0), RC);
1856 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1860 // Update the users of the node with the new indices
1861 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1863 SDNode *User = Users[i];
1867 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1868 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1872 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1873 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1874 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1879 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1880 /// with frame index operands.
1881 /// LLVM assumes that inputs are to these instructions are registers.
1882 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1883 SelectionDAG &DAG) const {
1885 SmallVector<SDValue, 8> Ops;
1886 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1887 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1888 Ops.push_back(Node->getOperand(i));
1893 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1894 Node->getOperand(i).getValueType(),
1895 Node->getOperand(i)), 0));
1898 DAG.UpdateNodeOperands(Node, Ops);
1901 /// \brief Fold the instructions after selecting them.
1902 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1903 SelectionDAG &DAG) const {
1904 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1905 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1906 Node = AdjustRegClass(Node, DAG);
1908 if (TII->isMIMG(Node->getMachineOpcode()))
1909 adjustWritemask(Node, DAG);
1911 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1912 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1913 legalizeTargetIndependentNode(Node, DAG);
1919 /// \brief Assign the register class depending on the number of
1920 /// bits set in the writemask
1921 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1922 SDNode *Node) const {
1923 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1924 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1926 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1927 TII->legalizeOperands(MI);
1929 if (TII->isMIMG(MI->getOpcode())) {
1930 unsigned VReg = MI->getOperand(0).getReg();
1931 unsigned Writemask = MI->getOperand(1).getImm();
1932 unsigned BitsSet = 0;
1933 for (unsigned i = 0; i < 4; ++i)
1934 BitsSet += Writemask & (1 << i) ? 1 : 0;
1936 const TargetRegisterClass *RC;
1939 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
1940 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1941 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1944 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1945 MI->setDesc(TII->get(NewOpcode));
1946 MRI.setRegClass(VReg, RC);
1950 // Replace unused atomics with the no return version.
1951 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1952 if (NoRetAtomicOp != -1) {
1953 if (!Node->hasAnyUseOfValue(0)) {
1954 MI->setDesc(TII->get(NoRetAtomicOp));
1955 MI->RemoveOperand(0);
1962 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
1963 SDValue K = DAG.getTargetConstant(Val, MVT::i32);
1964 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
1967 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
1969 SDValue Ptr) const {
1970 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1971 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1973 // XXX - Workaround for moveToVALU not handling different register class
1974 // inserts for REG_SEQUENCE.
1976 // Build the half of the subregister with the constants.
1977 const SDValue Ops0[] = {
1978 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
1979 buildSMovImm32(DAG, DL, 0),
1980 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
1981 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
1982 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
1985 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1986 MVT::v2i32, Ops0), 0);
1988 // Combine the constants and the pointer.
1989 const SDValue Ops1[] = {
1990 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
1992 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
1994 DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
1997 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
1999 const SDValue Ops[] = {
2000 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2002 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2003 buildSMovImm32(DAG, DL, 0),
2004 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2005 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2006 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2009 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2014 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2015 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2016 /// of the resource descriptor) to create an offset, which is added to the
2017 /// resource ponter.
2018 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2021 uint32_t RsrcDword1,
2022 uint64_t RsrcDword2And3) const {
2023 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2024 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2026 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2027 DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2030 SDValue DataLo = buildSMovImm32(DAG, DL,
2031 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2032 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2034 const SDValue Ops[] = {
2035 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2037 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2039 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2041 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2043 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2046 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2049 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2051 SDValue Ptr) const {
2052 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
2053 getTargetMachine().getSubtargetImpl()->getInstrInfo());
2054 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2057 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2060 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2061 SelectionDAG &DAG) const {
2064 unsigned NewOpcode = N->getMachineOpcode();
2066 switch (N->getMachineOpcode()) {
2068 case AMDGPU::S_LOAD_DWORD_IMM:
2069 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2071 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2072 if (NewOpcode == N->getMachineOpcode()) {
2073 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2076 case AMDGPU::S_LOAD_DWORDX4_IMM:
2077 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2078 if (NewOpcode == N->getMachineOpcode()) {
2079 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2081 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2084 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2086 const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2087 SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2088 MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2090 SmallVector<SDValue, 8> Ops;
2091 Ops.push_back(SDValue(RSrc, 0));
2092 Ops.push_back(N->getOperand(0));
2094 // The immediate offset is in dwords on SI and in bytes on VI.
2095 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
2096 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue(), MVT::i32));
2098 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue() << 2, MVT::i32));
2100 // Copy remaining operands so we keep any chain and glue nodes that follow
2101 // the normal operands.
2102 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2103 Ops.push_back(N->getOperand(I));
2105 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2110 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2111 const TargetRegisterClass *RC,
2112 unsigned Reg, EVT VT) const {
2113 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2115 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2116 cast<RegisterSDNode>(VReg)->getReg(), VT);