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::VReg_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::VReg_256RegClass);
57 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
59 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
60 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
62 computeRegisterProperties();
65 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
66 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
67 setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
68 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
69 setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
70 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
72 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
73 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
74 setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
75 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
76 setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
77 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
79 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
80 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
81 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
82 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
84 setOperationAction(ISD::ADD, MVT::i32, Legal);
85 setOperationAction(ISD::ADDC, MVT::i32, Legal);
86 setOperationAction(ISD::ADDE, MVT::i32, Legal);
87 setOperationAction(ISD::SUBC, MVT::i32, Legal);
88 setOperationAction(ISD::SUBE, MVT::i32, Legal);
90 setOperationAction(ISD::FSIN, MVT::f32, Custom);
91 setOperationAction(ISD::FCOS, MVT::f32, Custom);
93 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
94 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
95 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
96 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
98 // We need to custom lower vector stores from local memory
99 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
100 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
101 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
103 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
104 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
106 setOperationAction(ISD::STORE, MVT::i1, Custom);
107 setOperationAction(ISD::STORE, MVT::i32, Custom);
108 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
109 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
111 setOperationAction(ISD::SELECT, MVT::f32, Promote);
112 AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
113 setOperationAction(ISD::SELECT, MVT::i64, Custom);
114 setOperationAction(ISD::SELECT, MVT::f64, Promote);
115 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
117 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
118 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
119 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
120 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
122 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
123 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
125 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
131 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
132 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
133 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
135 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
136 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
137 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
139 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
140 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
142 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
143 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
144 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
145 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
147 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
148 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
150 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
151 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
152 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
153 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
154 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
155 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
157 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
158 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
159 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
160 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
162 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
163 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
164 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
165 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
166 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
168 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
169 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
170 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
171 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
172 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
173 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
175 setOperationAction(ISD::LOAD, MVT::i1, Custom);
177 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
178 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
179 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
181 // These should use UDIVREM, so set them to expand
182 setOperationAction(ISD::UDIV, MVT::i64, Expand);
183 setOperationAction(ISD::UREM, MVT::i64, Expand);
185 // We only support LOAD/STORE and vector manipulation ops for vectors
186 // with > 4 elements.
188 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
191 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
192 setOperationAction(ISD::SELECT, MVT::i1, Promote);
194 for (MVT VT : VecTypes) {
195 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
199 case ISD::BUILD_VECTOR:
201 case ISD::EXTRACT_VECTOR_ELT:
202 case ISD::INSERT_VECTOR_ELT:
203 case ISD::INSERT_SUBVECTOR:
204 case ISD::EXTRACT_SUBVECTOR:
206 case ISD::CONCAT_VECTORS:
207 setOperationAction(Op, VT, Custom);
210 setOperationAction(Op, VT, Expand);
216 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
217 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
218 setOperationAction(ISD::FTRUNC, VT, Expand);
219 setOperationAction(ISD::FCEIL, VT, Expand);
220 setOperationAction(ISD::FFLOOR, VT, Expand);
223 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
224 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
225 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
226 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
227 setOperationAction(ISD::FRINT, MVT::f64, Legal);
230 setOperationAction(ISD::FDIV, MVT::f32, Custom);
232 setTargetDAGCombine(ISD::FADD);
233 setTargetDAGCombine(ISD::FSUB);
234 setTargetDAGCombine(ISD::FMINNUM);
235 setTargetDAGCombine(ISD::FMAXNUM);
236 setTargetDAGCombine(ISD::SELECT_CC);
237 setTargetDAGCombine(ISD::SETCC);
239 setTargetDAGCombine(ISD::UINT_TO_FP);
241 // All memory operations. Some folding on the pointer operand is done to help
242 // matching the constant offsets in the addressing modes.
243 setTargetDAGCombine(ISD::LOAD);
244 setTargetDAGCombine(ISD::STORE);
245 setTargetDAGCombine(ISD::ATOMIC_LOAD);
246 setTargetDAGCombine(ISD::ATOMIC_STORE);
247 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
248 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
249 setTargetDAGCombine(ISD::ATOMIC_SWAP);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
252 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
253 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
254 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
255 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
256 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
257 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
258 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
259 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
261 setSchedulingPreference(Sched::RegPressure);
264 //===----------------------------------------------------------------------===//
265 // TargetLowering queries
266 //===----------------------------------------------------------------------===//
268 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
270 // SI has some legal vector types, but no legal vector operations. Say no
271 // shuffles are legal in order to prefer scalarizing some vector operations.
275 // FIXME: This really needs an address space argument. The immediate offset
276 // size is different for different sets of memory instruction sets.
278 // The single offset DS instructions have a 16-bit unsigned byte offset.
280 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
281 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
282 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
284 // SMRD instructions have an 8-bit, dword offset.
286 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
288 // No global is ever allowed as a base.
292 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
294 if (!isUInt<16>(AM.BaseOffs))
299 case 0: // "r+i" or just "i", depending on HasBaseReg.
302 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
304 // Otherwise we have r+r or r+i.
307 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
311 default: // Don't allow n * r
318 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
321 bool *IsFast) const {
325 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
326 // which isn't a simple VT.
327 if (!VT.isSimple() || VT == MVT::Other)
330 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
331 // see what for specifically. The wording everywhere else seems to be the
334 // XXX - The only mention I see of this in the ISA manual is for LDS direct
335 // reads the "byte address and must be dword aligned". Is it also true for the
336 // normal loads and stores?
337 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
338 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
339 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
340 // with adjacent offsets.
341 return Align % 4 == 0;
344 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
345 // byte-address are ignored, thus forcing Dword alignment.
346 // This applies to private, global, and constant memory.
349 return VT.bitsGT(MVT::i32);
352 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
353 unsigned SrcAlign, bool IsMemset,
356 MachineFunction &MF) const {
357 // FIXME: Should account for address space here.
359 // The default fallback uses the private pointer size as a guess for a type to
360 // use. Make sure we switch these to 64-bit accesses.
362 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
365 if (Size >= 8 && DstAlign >= 4)
372 TargetLoweringBase::LegalizeTypeAction
373 SITargetLowering::getPreferredVectorAction(EVT VT) const {
374 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
375 return TypeSplitVector;
377 return TargetLoweringBase::getPreferredVectorAction(VT);
380 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
382 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
383 getTargetMachine().getSubtargetImpl()->getInstrInfo());
384 return TII->isInlineConstant(Imm);
387 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
388 SDLoc SL, SDValue Chain,
389 unsigned Offset, bool Signed) const {
390 const DataLayout *DL = getDataLayout();
391 MachineFunction &MF = DAG.getMachineFunction();
392 const SIRegisterInfo *TRI =
393 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
394 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
396 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
398 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
399 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
400 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
401 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
402 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
403 DAG.getConstant(Offset, MVT::i64));
404 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
405 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
407 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
408 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
410 true, // isNonTemporal
412 DL->getABITypeAlignment(Ty)); // Alignment
415 SDValue SITargetLowering::LowerFormalArguments(
417 CallingConv::ID CallConv,
419 const SmallVectorImpl<ISD::InputArg> &Ins,
420 SDLoc DL, SelectionDAG &DAG,
421 SmallVectorImpl<SDValue> &InVals) const {
423 const TargetMachine &TM = getTargetMachine();
424 const SIRegisterInfo *TRI =
425 static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
427 MachineFunction &MF = DAG.getMachineFunction();
428 FunctionType *FType = MF.getFunction()->getFunctionType();
429 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
431 assert(CallConv == CallingConv::C);
433 SmallVector<ISD::InputArg, 16> Splits;
434 BitVector Skipped(Ins.size());
436 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
437 const ISD::InputArg &Arg = Ins[i];
439 // First check if it's a PS input addr
440 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
441 !Arg.Flags.isByVal()) {
443 assert((PSInputNum <= 15) && "Too many PS inputs!");
446 // We can savely skip PS inputs
452 Info->PSInputAddr |= 1 << PSInputNum++;
455 // Second split vertices into their elements
456 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
457 ISD::InputArg NewArg = Arg;
458 NewArg.Flags.setSplit();
459 NewArg.VT = Arg.VT.getVectorElementType();
461 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
462 // three or five element vertex only needs three or five registers,
463 // NOT four or eigth.
464 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
465 unsigned NumElements = ParamType->getVectorNumElements();
467 for (unsigned j = 0; j != NumElements; ++j) {
468 Splits.push_back(NewArg);
469 NewArg.PartOffset += NewArg.VT.getStoreSize();
472 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
473 Splits.push_back(Arg);
477 SmallVector<CCValAssign, 16> ArgLocs;
478 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
481 // At least one interpolation mode must be enabled or else the GPU will hang.
482 if (Info->getShaderType() == ShaderType::PIXEL &&
483 (Info->PSInputAddr & 0x7F) == 0) {
484 Info->PSInputAddr |= 1;
485 CCInfo.AllocateReg(AMDGPU::VGPR0);
486 CCInfo.AllocateReg(AMDGPU::VGPR1);
489 // The pointer to the list of arguments is stored in SGPR0, SGPR1
490 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
491 if (Info->getShaderType() == ShaderType::COMPUTE) {
492 Info->NumUserSGPRs = 4;
494 unsigned InputPtrReg =
495 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
496 unsigned InputPtrRegLo =
497 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
498 unsigned InputPtrRegHi =
499 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
501 unsigned ScratchPtrReg =
502 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
503 unsigned ScratchPtrRegLo =
504 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
505 unsigned ScratchPtrRegHi =
506 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
508 CCInfo.AllocateReg(InputPtrRegLo);
509 CCInfo.AllocateReg(InputPtrRegHi);
510 CCInfo.AllocateReg(ScratchPtrRegLo);
511 CCInfo.AllocateReg(ScratchPtrRegHi);
512 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
513 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
516 if (Info->getShaderType() == ShaderType::COMPUTE) {
517 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
521 AnalyzeFormalArguments(CCInfo, Splits);
523 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
525 const ISD::InputArg &Arg = Ins[i];
527 InVals.push_back(DAG.getUNDEF(Arg.VT));
531 CCValAssign &VA = ArgLocs[ArgIdx++];
532 MVT VT = VA.getLocVT();
536 EVT MemVT = Splits[i].VT;
537 const unsigned Offset = 36 + VA.getLocMemOffset();
538 // The first 36 bytes of the input buffer contains information about
539 // thread group and global sizes.
540 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
541 Offset, Ins[i].Flags.isSExt());
543 const PointerType *ParamTy =
544 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
545 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
546 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
547 // On SI local pointers are just offsets into LDS, so they are always
548 // less than 16-bits. On CI and newer they could potentially be
549 // real pointers, so we can't guarantee their size.
550 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
551 DAG.getValueType(MVT::i16));
554 InVals.push_back(Arg);
555 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
558 assert(VA.isRegLoc() && "Parameter must be in a register!");
560 unsigned Reg = VA.getLocReg();
562 if (VT == MVT::i64) {
563 // For now assume it is a pointer
564 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
565 &AMDGPU::SReg_64RegClass);
566 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
567 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
571 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
573 Reg = MF.addLiveIn(Reg, RC);
574 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
576 if (Arg.VT.isVector()) {
578 // Build a vector from the registers
579 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
580 unsigned NumElements = ParamType->getVectorNumElements();
582 SmallVector<SDValue, 4> Regs;
584 for (unsigned j = 1; j != NumElements; ++j) {
585 Reg = ArgLocs[ArgIdx++].getLocReg();
586 Reg = MF.addLiveIn(Reg, RC);
587 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
590 // Fill up the missing vector elements
591 NumElements = Arg.VT.getVectorNumElements() - NumElements;
592 for (unsigned j = 0; j != NumElements; ++j)
593 Regs.push_back(DAG.getUNDEF(VT));
595 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
599 InVals.push_back(Val);
604 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
605 MachineInstr * MI, MachineBasicBlock * BB) const {
607 MachineBasicBlock::iterator I = *MI;
608 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
609 getTargetMachine().getSubtargetImpl()->getInstrInfo());
611 switch (MI->getOpcode()) {
613 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
614 case AMDGPU::BRANCH: return BB;
615 case AMDGPU::V_SUB_F64: {
616 unsigned DestReg = MI->getOperand(0).getReg();
617 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
618 .addImm(0) // SRC0 modifiers
619 .addReg(MI->getOperand(1).getReg())
620 .addImm(1) // SRC1 modifiers
621 .addReg(MI->getOperand(2).getReg())
624 MI->eraseFromParent();
627 case AMDGPU::SI_RegisterStorePseudo: {
628 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
629 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
630 MachineInstrBuilder MIB =
631 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
633 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
634 MIB.addOperand(MI->getOperand(i));
636 MI->eraseFromParent();
643 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
644 if (!VT.isVector()) {
647 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
650 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
654 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
655 VT = VT.getScalarType();
660 switch (VT.getSimpleVT().SimpleTy) {
662 return false; /* There is V_MAD_F32 for f32 */
672 //===----------------------------------------------------------------------===//
673 // Custom DAG Lowering Operations
674 //===----------------------------------------------------------------------===//
676 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
677 switch (Op.getOpcode()) {
678 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
679 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
680 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
682 SDValue Result = LowerLOAD(Op, DAG);
683 assert((!Result.getNode() ||
684 Result.getNode()->getNumValues() == 2) &&
685 "Load should return a value and a chain");
691 return LowerTrig(Op, DAG);
692 case ISD::SELECT: return LowerSELECT(Op, DAG);
693 case ISD::FDIV: return LowerFDIV(Op, DAG);
694 case ISD::STORE: return LowerSTORE(Op, DAG);
695 case ISD::GlobalAddress: {
696 MachineFunction &MF = DAG.getMachineFunction();
697 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
698 return LowerGlobalAddress(MFI, Op, DAG);
700 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
701 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
706 /// \brief Helper function for LowerBRCOND
707 static SDNode *findUser(SDValue Value, unsigned Opcode) {
709 SDNode *Parent = Value.getNode();
710 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
713 if (I.getUse().get() != Value)
716 if (I->getOpcode() == Opcode)
722 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
724 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
725 unsigned FrameIndex = FINode->getIndex();
727 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
730 /// This transforms the control flow intrinsics to get the branch destination as
731 /// last parameter, also switches branch target with BR if the need arise
732 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
733 SelectionDAG &DAG) const {
737 SDNode *Intr = BRCOND.getOperand(1).getNode();
738 SDValue Target = BRCOND.getOperand(2);
739 SDNode *BR = nullptr;
741 if (Intr->getOpcode() == ISD::SETCC) {
742 // As long as we negate the condition everything is fine
743 SDNode *SetCC = Intr;
744 assert(SetCC->getConstantOperandVal(1) == 1);
745 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
747 Intr = SetCC->getOperand(0).getNode();
750 // Get the target from BR if we don't negate the condition
751 BR = findUser(BRCOND, ISD::BR);
752 Target = BR->getOperand(1);
755 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
757 // Build the result and
758 SmallVector<EVT, 4> Res;
759 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
760 Res.push_back(Intr->getValueType(i));
762 // operands of the new intrinsic call
763 SmallVector<SDValue, 4> Ops;
764 Ops.push_back(BRCOND.getOperand(0));
765 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
766 Ops.push_back(Intr->getOperand(i));
767 Ops.push_back(Target);
769 // build the new intrinsic call
770 SDNode *Result = DAG.getNode(
771 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
772 DAG.getVTList(Res), Ops).getNode();
775 // Give the branch instruction our target
780 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
781 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
782 BR = NewBR.getNode();
785 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
787 // Copy the intrinsic results to registers
788 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
789 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
793 Chain = DAG.getCopyToReg(
795 CopyToReg->getOperand(1),
796 SDValue(Result, i - 1),
799 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
802 // Remove the old intrinsic from the chain
803 DAG.ReplaceAllUsesOfValueWith(
804 SDValue(Intr, Intr->getNumValues() - 1),
805 Intr->getOperand(0));
810 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
812 SelectionDAG &DAG) const {
813 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
815 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
816 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
819 const GlobalValue *GV = GSD->getGlobal();
820 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
822 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
823 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
825 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
826 DAG.getConstant(0, MVT::i32));
827 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
828 DAG.getConstant(1, MVT::i32));
830 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
832 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
833 PtrHi, DAG.getConstant(0, MVT::i32),
834 SDValue(Lo.getNode(), 1));
835 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
838 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
839 SelectionDAG &DAG) const {
840 MachineFunction &MF = DAG.getMachineFunction();
841 const SIRegisterInfo *TRI =
842 static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
844 EVT VT = Op.getValueType();
846 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
848 switch (IntrinsicID) {
849 case Intrinsic::r600_read_ngroups_x:
850 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
851 SI::KernelInputOffsets::NGROUPS_X, false);
852 case Intrinsic::r600_read_ngroups_y:
853 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
854 SI::KernelInputOffsets::NGROUPS_Y, false);
855 case Intrinsic::r600_read_ngroups_z:
856 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
857 SI::KernelInputOffsets::NGROUPS_Z, false);
858 case Intrinsic::r600_read_global_size_x:
859 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
860 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
861 case Intrinsic::r600_read_global_size_y:
862 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
863 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
864 case Intrinsic::r600_read_global_size_z:
865 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
866 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
867 case Intrinsic::r600_read_local_size_x:
868 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
869 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
870 case Intrinsic::r600_read_local_size_y:
871 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
872 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
873 case Intrinsic::r600_read_local_size_z:
874 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
875 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
877 case Intrinsic::AMDGPU_read_workdim:
878 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
879 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
882 case Intrinsic::r600_read_tgid_x:
883 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
884 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
885 case Intrinsic::r600_read_tgid_y:
886 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
887 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
888 case Intrinsic::r600_read_tgid_z:
889 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
890 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
891 case Intrinsic::r600_read_tidig_x:
892 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
893 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
894 case Intrinsic::r600_read_tidig_y:
895 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
896 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
897 case Intrinsic::r600_read_tidig_z:
898 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
899 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
900 case AMDGPUIntrinsic::SI_load_const: {
906 MachineMemOperand *MMO = MF.getMachineMemOperand(
907 MachinePointerInfo(),
908 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
909 VT.getStoreSize(), 4);
910 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
911 Op->getVTList(), Ops, VT, MMO);
913 case AMDGPUIntrinsic::SI_sample:
914 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
915 case AMDGPUIntrinsic::SI_sampleb:
916 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
917 case AMDGPUIntrinsic::SI_sampled:
918 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
919 case AMDGPUIntrinsic::SI_samplel:
920 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
921 case AMDGPUIntrinsic::SI_vs_load_input:
922 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
927 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
931 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
932 SelectionDAG &DAG) const {
933 MachineFunction &MF = DAG.getMachineFunction();
934 SDValue Chain = Op.getOperand(0);
935 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
937 switch (IntrinsicID) {
938 case AMDGPUIntrinsic::SI_tbuffer_store: {
957 EVT VT = Op.getOperand(3).getValueType();
959 MachineMemOperand *MMO = MF.getMachineMemOperand(
960 MachinePointerInfo(),
961 MachineMemOperand::MOStore,
962 VT.getStoreSize(), 4);
963 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
964 Op->getVTList(), Ops, VT, MMO);
971 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
973 LoadSDNode *Load = cast<LoadSDNode>(Op);
975 if (Op.getValueType().isVector()) {
976 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
977 "Custom lowering for non-i32 vectors hasn't been implemented.");
978 unsigned NumElements = Op.getValueType().getVectorNumElements();
979 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
980 switch (Load->getAddressSpace()) {
982 case AMDGPUAS::GLOBAL_ADDRESS:
983 case AMDGPUAS::PRIVATE_ADDRESS:
984 // v4 loads are supported for private and global memory.
985 if (NumElements <= 4)
988 case AMDGPUAS::LOCAL_ADDRESS:
989 return ScalarizeVectorLoad(Op, DAG);
993 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
996 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
998 SelectionDAG &DAG) const {
999 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1005 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1006 if (Op.getValueType() != MVT::i64)
1010 SDValue Cond = Op.getOperand(0);
1012 SDValue Zero = DAG.getConstant(0, MVT::i32);
1013 SDValue One = DAG.getConstant(1, MVT::i32);
1015 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1016 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1018 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1019 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1021 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1023 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1024 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1026 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1028 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1029 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1032 // Catch division cases where we can use shortcuts with rcp and rsq
1034 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1036 SDValue LHS = Op.getOperand(0);
1037 SDValue RHS = Op.getOperand(1);
1038 EVT VT = Op.getValueType();
1039 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1041 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1042 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1043 CLHS->isExactlyValue(1.0)) {
1044 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1045 // the CI documentation has a worst case error of 1 ulp.
1046 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1047 // use it as long as we aren't trying to use denormals.
1049 // 1.0 / sqrt(x) -> rsq(x)
1051 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1052 // error seems really high at 2^29 ULP.
1053 if (RHS.getOpcode() == ISD::FSQRT)
1054 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1056 // 1.0 / x -> rcp(x)
1057 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1062 // Turn into multiply by the reciprocal.
1063 // x / y -> x * (1.0 / y)
1064 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1065 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1071 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1072 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1073 if (FastLowered.getNode())
1076 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1077 // selection error for now rather than do something incorrect.
1078 if (Subtarget->hasFP32Denormals())
1082 SDValue LHS = Op.getOperand(0);
1083 SDValue RHS = Op.getOperand(1);
1085 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1087 const APFloat K0Val(BitsToFloat(0x6f800000));
1088 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1090 const APFloat K1Val(BitsToFloat(0x2f800000));
1091 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1093 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1095 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1097 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1099 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1101 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1103 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1105 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1107 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1110 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1114 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1115 EVT VT = Op.getValueType();
1118 return LowerFDIV32(Op, DAG);
1121 return LowerFDIV64(Op, DAG);
1123 llvm_unreachable("Unexpected type for fdiv");
1126 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1128 StoreSDNode *Store = cast<StoreSDNode>(Op);
1129 EVT VT = Store->getMemoryVT();
1131 // These stores are legal.
1132 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1133 VT.isVector() && VT.getVectorNumElements() == 2 &&
1134 VT.getVectorElementType() == MVT::i32)
1137 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1138 if (VT.isVector() && VT.getVectorNumElements() > 4)
1139 return ScalarizeVectorStore(Op, DAG);
1143 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1147 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1148 return ScalarizeVectorStore(Op, DAG);
1151 return DAG.getTruncStore(Store->getChain(), DL,
1152 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1153 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1158 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1159 EVT VT = Op.getValueType();
1160 SDValue Arg = Op.getOperand(0);
1161 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1162 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1163 DAG.getConstantFP(0.5 / M_PI, VT)));
1165 switch (Op.getOpcode()) {
1167 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1169 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1171 llvm_unreachable("Wrong trig opcode");
1175 //===----------------------------------------------------------------------===//
1176 // Custom DAG optimizations
1177 //===----------------------------------------------------------------------===//
1179 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1180 DAGCombinerInfo &DCI) {
1181 EVT VT = N->getValueType(0);
1182 EVT ScalarVT = VT.getScalarType();
1183 if (ScalarVT != MVT::f32)
1186 SelectionDAG &DAG = DCI.DAG;
1189 SDValue Src = N->getOperand(0);
1190 EVT SrcVT = Src.getValueType();
1192 // TODO: We could try to match extracting the higher bytes, which would be
1193 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1194 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1195 // about in practice.
1196 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1197 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1198 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1199 DCI.AddToWorklist(Cvt.getNode());
1204 // We are primarily trying to catch operations on illegal vector types
1205 // before they are expanded.
1206 // For scalars, we can use the more flexible method of checking masked bits
1207 // after legalization.
1208 if (!DCI.isBeforeLegalize() ||
1209 !SrcVT.isVector() ||
1210 SrcVT.getVectorElementType() != MVT::i8) {
1214 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1216 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1218 unsigned NElts = SrcVT.getVectorNumElements();
1219 if (!SrcVT.isSimple() && NElts != 3)
1222 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1223 // prevent a mess from expanding to v4i32 and repacking.
1224 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1225 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1226 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1227 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1229 LoadSDNode *Load = cast<LoadSDNode>(Src);
1230 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1234 Load->getMemOperand());
1236 // Make sure successors of the original load stay after it by updating
1237 // them to use the new Chain.
1238 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1240 SmallVector<SDValue, 4> Elts;
1241 if (RegVT.isVector())
1242 DAG.ExtractVectorElements(NewLoad, Elts);
1244 Elts.push_back(NewLoad);
1246 SmallVector<SDValue, 4> Ops;
1248 unsigned EltIdx = 0;
1249 for (SDValue Elt : Elts) {
1250 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1251 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1252 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1253 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1254 DCI.AddToWorklist(Cvt.getNode());
1261 assert(Ops.size() == NElts);
1263 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1269 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1271 // This is a variant of
1272 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1274 // The normal DAG combiner will do this, but only if the add has one use since
1275 // that would increase the number of instructions.
1277 // This prevents us from seeing a constant offset that can be folded into a
1278 // memory instruction's addressing mode. If we know the resulting add offset of
1279 // a pointer can be folded into an addressing offset, we can replace the pointer
1280 // operand with the add of new constant offset. This eliminates one of the uses,
1281 // and may allow the remaining use to also be simplified.
1283 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1285 DAGCombinerInfo &DCI) const {
1286 SDValue N0 = N->getOperand(0);
1287 SDValue N1 = N->getOperand(1);
1289 if (N0.getOpcode() != ISD::ADD)
1292 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1296 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1300 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1301 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1303 // If the resulting offset is too large, we can't fold it into the addressing
1305 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1306 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1309 SelectionDAG &DAG = DCI.DAG;
1311 EVT VT = N->getValueType(0);
1313 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1314 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1316 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1319 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1322 return AMDGPUISD::FMAX3;
1323 case AMDGPUISD::SMAX:
1324 return AMDGPUISD::SMAX3;
1325 case AMDGPUISD::UMAX:
1326 return AMDGPUISD::UMAX3;
1328 return AMDGPUISD::FMIN3;
1329 case AMDGPUISD::SMIN:
1330 return AMDGPUISD::SMIN3;
1331 case AMDGPUISD::UMIN:
1332 return AMDGPUISD::UMIN3;
1334 llvm_unreachable("Not a min/max opcode");
1338 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1339 DAGCombinerInfo &DCI) const {
1340 SelectionDAG &DAG = DCI.DAG;
1342 unsigned Opc = N->getOpcode();
1343 SDValue Op0 = N->getOperand(0);
1344 SDValue Op1 = N->getOperand(1);
1346 // Only do this if the inner op has one use since this will just increases
1347 // register pressure for no benefit.
1349 // max(max(a, b), c)
1350 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1352 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1360 // max(a, max(b, c))
1361 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1363 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1374 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1375 DAGCombinerInfo &DCI) const {
1376 SelectionDAG &DAG = DCI.DAG;
1378 EVT VT = N->getValueType(0);
1380 switch (N->getOpcode()) {
1381 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1383 SDValue Arg0 = N->getOperand(0);
1384 SDValue Arg1 = N->getOperand(1);
1385 SDValue CC = N->getOperand(2);
1386 ConstantSDNode * C = nullptr;
1387 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1389 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1391 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1392 && Arg0.getOperand(0).getValueType() == MVT::i1
1393 && (C = dyn_cast<ConstantSDNode>(Arg1))
1395 && CCOp == ISD::SETNE) {
1396 return SimplifySetCC(VT, Arg0.getOperand(0),
1397 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1401 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1403 case AMDGPUISD::SMAX:
1404 case AMDGPUISD::SMIN:
1405 case AMDGPUISD::UMAX:
1406 case AMDGPUISD::UMIN: {
1407 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1408 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1409 return performMin3Max3Combine(N, DCI);
1413 case AMDGPUISD::CVT_F32_UBYTE0:
1414 case AMDGPUISD::CVT_F32_UBYTE1:
1415 case AMDGPUISD::CVT_F32_UBYTE2:
1416 case AMDGPUISD::CVT_F32_UBYTE3: {
1417 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1419 SDValue Src = N->getOperand(0);
1420 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1422 APInt KnownZero, KnownOne;
1423 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1424 !DCI.isBeforeLegalizeOps());
1425 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1426 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1427 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1428 DCI.CommitTargetLoweringOpt(TLO);
1434 case ISD::UINT_TO_FP: {
1435 return performUCharToFloatCombine(N, DCI);
1438 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1441 EVT VT = N->getValueType(0);
1445 SDValue LHS = N->getOperand(0);
1446 SDValue RHS = N->getOperand(1);
1448 // These should really be instruction patterns, but writing patterns with
1449 // source modiifiers is a pain.
1451 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1452 if (LHS.getOpcode() == ISD::FADD) {
1453 SDValue A = LHS.getOperand(0);
1454 if (A == LHS.getOperand(1)) {
1455 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1456 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1460 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1461 if (RHS.getOpcode() == ISD::FADD) {
1462 SDValue A = RHS.getOperand(0);
1463 if (A == RHS.getOperand(1)) {
1464 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1465 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1472 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1475 EVT VT = N->getValueType(0);
1477 // Try to get the fneg to fold into the source modifier. This undoes generic
1478 // DAG combines and folds them into the mad.
1479 if (VT == MVT::f32) {
1480 SDValue LHS = N->getOperand(0);
1481 SDValue RHS = N->getOperand(1);
1483 if (LHS.getOpcode() == ISD::FMUL) {
1484 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1486 SDValue A = LHS.getOperand(0);
1487 SDValue B = LHS.getOperand(1);
1488 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1490 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1493 if (RHS.getOpcode() == ISD::FMUL) {
1494 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1496 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1497 SDValue B = RHS.getOperand(1);
1500 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1503 if (LHS.getOpcode() == ISD::FADD) {
1504 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1506 SDValue A = LHS.getOperand(0);
1507 if (A == LHS.getOperand(1)) {
1508 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1509 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1511 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1515 if (RHS.getOpcode() == ISD::FADD) {
1516 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1518 SDValue A = RHS.getOperand(0);
1519 if (A == RHS.getOperand(1)) {
1520 const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
1521 return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1531 case ISD::ATOMIC_LOAD:
1532 case ISD::ATOMIC_STORE:
1533 case ISD::ATOMIC_CMP_SWAP:
1534 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1535 case ISD::ATOMIC_SWAP:
1536 case ISD::ATOMIC_LOAD_ADD:
1537 case ISD::ATOMIC_LOAD_SUB:
1538 case ISD::ATOMIC_LOAD_AND:
1539 case ISD::ATOMIC_LOAD_OR:
1540 case ISD::ATOMIC_LOAD_XOR:
1541 case ISD::ATOMIC_LOAD_NAND:
1542 case ISD::ATOMIC_LOAD_MIN:
1543 case ISD::ATOMIC_LOAD_MAX:
1544 case ISD::ATOMIC_LOAD_UMIN:
1545 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1546 if (DCI.isBeforeLegalize())
1549 MemSDNode *MemNode = cast<MemSDNode>(N);
1550 SDValue Ptr = MemNode->getBasePtr();
1552 // TODO: We could also do this for multiplies.
1553 unsigned AS = MemNode->getAddressSpace();
1554 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1555 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1557 SmallVector<SDValue, 8> NewOps;
1558 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1559 NewOps.push_back(MemNode->getOperand(I));
1561 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1562 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1568 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1571 /// \brief Test if RegClass is one of the VSrc classes
1572 static bool isVSrc(unsigned RegClass) {
1574 default: return false;
1575 case AMDGPU::VSrc_32RegClassID:
1576 case AMDGPU::VCSrc_32RegClassID:
1577 case AMDGPU::VSrc_64RegClassID:
1578 case AMDGPU::VCSrc_64RegClassID:
1583 /// \brief Test if RegClass is one of the SSrc classes
1584 static bool isSSrc(unsigned RegClass) {
1585 return AMDGPU::SSrc_32RegClassID == RegClass ||
1586 AMDGPU::SSrc_64RegClassID == RegClass;
1589 /// \brief Analyze the possible immediate value Op
1591 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1592 /// and the immediate value if it's a literal immediate
1593 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1600 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1601 if (Node->getZExtValue() >> 32) {
1604 Imm.I = Node->getSExtValue();
1605 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1606 if (N->getValueType(0) != MVT::f32)
1608 Imm.F = Node->getValueAPF().convertToFloat();
1610 return -1; // It isn't an immediate
1612 if ((Imm.I >= -16 && Imm.I <= 64) ||
1613 Imm.F == 0.5f || Imm.F == -0.5f ||
1614 Imm.F == 1.0f || Imm.F == -1.0f ||
1615 Imm.F == 2.0f || Imm.F == -2.0f ||
1616 Imm.F == 4.0f || Imm.F == -4.0f)
1617 return 0; // It's an inline immediate
1619 return Imm.I; // It's a literal immediate
1622 /// \brief Try to fold an immediate directly into an instruction
1623 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1624 bool &ScalarSlotUsed) const {
1626 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1627 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1628 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1629 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1632 const SDValue &Op = Mov->getOperand(0);
1633 int32_t Value = analyzeImmediate(Op.getNode());
1635 // Not an immediate at all
1638 } else if (Value == 0) {
1639 // Inline immediates can always be fold
1643 } else if (Value == Immediate) {
1644 // Already fold literal immediate
1648 } else if (!ScalarSlotUsed && !Immediate) {
1649 // Fold this literal immediate
1650 ScalarSlotUsed = true;
1660 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1661 SelectionDAG &DAG, const SDValue &Op) const {
1662 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1663 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1664 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1666 if (!Op->isMachineOpcode()) {
1667 switch(Op->getOpcode()) {
1668 case ISD::CopyFromReg: {
1669 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1670 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1671 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1672 return MRI.getRegClass(Reg);
1674 return TRI.getPhysRegClass(Reg);
1676 default: return nullptr;
1679 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1680 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1681 if (OpClassID != -1) {
1682 return TRI.getRegClass(OpClassID);
1684 switch(Op.getMachineOpcode()) {
1685 case AMDGPU::COPY_TO_REGCLASS:
1686 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1687 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1689 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1690 // class, then the register class for the value could be either a
1691 // VReg or and SReg. In order to get a more accurate
1692 if (isVSrc(OpClassID))
1693 return getRegClassForNode(DAG, Op.getOperand(0));
1695 return TRI.getRegClass(OpClassID);
1696 case AMDGPU::EXTRACT_SUBREG: {
1697 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1698 const TargetRegisterClass *SuperClass =
1699 getRegClassForNode(DAG, Op.getOperand(0));
1700 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1702 case AMDGPU::REG_SEQUENCE:
1703 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1704 return TRI.getRegClass(
1705 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1707 return getRegClassFor(Op.getSimpleValueType());
1711 /// \brief Does "Op" fit into register class "RegClass" ?
1712 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1713 unsigned RegClass) const {
1714 const TargetRegisterInfo *TRI =
1715 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1716 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1720 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1723 /// \returns true if \p Node's operands are different from the SDValue list
1725 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1726 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1727 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1734 /// TODO: This needs to be removed. It's current primary purpose is to fold
1735 /// immediates into operands when legal. The legalization parts are redundant
1736 /// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
1737 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1738 SelectionDAG &DAG) const {
1739 // Original encoding (either e32 or e64)
1740 int Opcode = Node->getMachineOpcode();
1741 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1742 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1743 const MCInstrDesc *Desc = &TII->get(Opcode);
1745 unsigned NumDefs = Desc->getNumDefs();
1746 unsigned NumOps = Desc->getNumOperands();
1748 // Commuted opcode if available
1749 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1750 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1752 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1753 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1755 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1756 bool HaveVSrc = false, HaveSSrc = false;
1758 // First figure out what we already have in this instruction.
1759 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1760 i != e && Op < NumOps; ++i, ++Op) {
1762 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1763 if (isVSrc(RegClass))
1765 else if (isSSrc(RegClass))
1770 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1771 if (Imm != -1 && Imm != 0) {
1772 // Literal immediate
1777 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1778 if (!HaveVSrc && !HaveSSrc)
1781 // No scalar allowed when we have both VSrc and SSrc
1782 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1784 // If this instruction has an implicit use of VCC, then it can't use the
1786 for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1787 if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1788 ScalarSlotUsed = true;
1793 // Second go over the operands and try to fold them
1794 std::vector<SDValue> Ops;
1795 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1796 i != e && Op < NumOps; ++i, ++Op) {
1798 const SDValue &Operand = Node->getOperand(i);
1799 Ops.push_back(Operand);
1801 // Already folded immediate?
1802 if (isa<ConstantSDNode>(Operand.getNode()) ||
1803 isa<ConstantFPSDNode>(Operand.getNode()))
1806 // Is this a VSrc or SSrc operand?
1807 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1808 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1809 // Try to fold the immediates. If this ends up with multiple constant bus
1810 // uses, it will be legalized later.
1811 foldImm(Ops[i], Immediate, ScalarSlotUsed);
1815 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1817 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1818 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1820 // Test if it makes sense to swap operands
1821 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1822 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1823 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1825 // Swap commutable operands
1826 std::swap(Ops[0], Ops[1]);
1835 // Add optional chain and glue
1836 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1837 Ops.push_back(Node->getOperand(i));
1839 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1840 // this case a brand new node is always be created, even if the operands
1841 // are the same as before. So, manually check if anything has been changed.
1842 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1846 // Create a complete new instruction
1847 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1850 /// \brief Helper function for adjustWritemask
1851 static unsigned SubIdx2Lane(unsigned Idx) {
1854 case AMDGPU::sub0: return 0;
1855 case AMDGPU::sub1: return 1;
1856 case AMDGPU::sub2: return 2;
1857 case AMDGPU::sub3: return 3;
1861 /// \brief Adjust the writemask of MIMG instructions
1862 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1863 SelectionDAG &DAG) const {
1864 SDNode *Users[4] = { };
1866 unsigned OldDmask = Node->getConstantOperandVal(0);
1867 unsigned NewDmask = 0;
1869 // Try to figure out the used register components
1870 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1873 // Abort if we can't understand the usage
1874 if (!I->isMachineOpcode() ||
1875 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1878 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1879 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1880 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1882 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1884 // Set which texture component corresponds to the lane.
1886 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1888 Comp = countTrailingZeros(Dmask);
1889 Dmask &= ~(1 << Comp);
1892 // Abort if we have more than one user per component
1897 NewDmask |= 1 << Comp;
1900 // Abort if there's no change
1901 if (NewDmask == OldDmask)
1904 // Adjust the writemask in the node
1905 std::vector<SDValue> Ops;
1906 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1907 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1908 Ops.push_back(Node->getOperand(i));
1909 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1911 // If we only got one lane, replace it with a copy
1912 // (if NewDmask has only one bit set...)
1913 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1914 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1915 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1916 SDLoc(), Users[Lane]->getValueType(0),
1917 SDValue(Node, 0), RC);
1918 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1922 // Update the users of the node with the new indices
1923 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1925 SDNode *User = Users[i];
1929 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1930 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1934 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1935 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1936 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1941 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1942 /// with frame index operands.
1943 /// LLVM assumes that inputs are to these instructions are registers.
1944 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1945 SelectionDAG &DAG) const {
1947 SmallVector<SDValue, 8> Ops;
1948 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1949 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1950 Ops.push_back(Node->getOperand(i));
1955 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1956 Node->getOperand(i).getValueType(),
1957 Node->getOperand(i)), 0));
1960 DAG.UpdateNodeOperands(Node, Ops);
1963 /// \brief Fold the instructions after selecting them.
1964 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1965 SelectionDAG &DAG) const {
1966 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1967 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1968 Node = AdjustRegClass(Node, DAG);
1970 if (TII->isMIMG(Node->getMachineOpcode()))
1971 adjustWritemask(Node, DAG);
1973 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1974 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1975 legalizeTargetIndependentNode(Node, DAG);
1979 return legalizeOperands(Node, DAG);
1982 /// \brief Assign the register class depending on the number of
1983 /// bits set in the writemask
1984 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1985 SDNode *Node) const {
1986 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1987 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1989 TII->legalizeOperands(MI);
1991 if (TII->isMIMG(MI->getOpcode())) {
1992 unsigned VReg = MI->getOperand(0).getReg();
1993 unsigned Writemask = MI->getOperand(1).getImm();
1994 unsigned BitsSet = 0;
1995 for (unsigned i = 0; i < 4; ++i)
1996 BitsSet += Writemask & (1 << i) ? 1 : 0;
1998 const TargetRegisterClass *RC;
2001 case 1: RC = &AMDGPU::VReg_32RegClass; break;
2002 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2003 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2006 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2007 MI->setDesc(TII->get(NewOpcode));
2008 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2009 MRI.setRegClass(VReg, RC);
2013 // Replace unused atomics with the no return version.
2014 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2015 if (NoRetAtomicOp != -1) {
2016 if (!Node->hasAnyUseOfValue(0)) {
2017 MI->setDesc(TII->get(NoRetAtomicOp));
2018 MI->RemoveOperand(0);
2025 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2026 SDValue K = DAG.getTargetConstant(Val, MVT::i32);
2027 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2030 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2032 SDValue Ptr) const {
2034 // XXX - Workaround for moveToVALU not handling different register class
2035 // inserts for REG_SEQUENCE.
2037 // Build the half of the subregister with the constants.
2038 const SDValue Ops0[] = {
2039 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
2040 buildSMovImm32(DAG, DL, 0),
2041 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2042 buildSMovImm32(DAG, DL, AMDGPU::RSRC_DATA_FORMAT >> 32),
2043 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
2046 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2047 MVT::v2i32, Ops0), 0);
2049 // Combine the constants and the pointer.
2050 const SDValue Ops1[] = {
2051 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2053 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2055 DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
2058 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2060 const SDValue Ops[] = {
2061 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2063 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2064 buildSMovImm32(DAG, DL, 0),
2065 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2066 buildSMovImm32(DAG, DL, AMDGPU::RSRC_DATA_FORMAT >> 32),
2067 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2070 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2075 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2076 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2077 /// of the resource descriptor) to create an offset, which is added to the
2078 /// resource ponter.
2079 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2082 uint32_t RsrcDword1,
2083 uint64_t RsrcDword2And3) const {
2084 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2085 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2087 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2088 DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2091 SDValue DataLo = buildSMovImm32(DAG, DL,
2092 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2093 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2095 const SDValue Ops[] = {
2096 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2098 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2100 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2102 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2104 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2107 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2110 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2112 SDValue Ptr) const {
2113 uint64_t Rsrc = AMDGPU::RSRC_DATA_FORMAT | AMDGPU::RSRC_TID_ENABLE |
2116 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2119 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2120 SelectionDAG &DAG) const {
2123 unsigned NewOpcode = N->getMachineOpcode();
2125 switch (N->getMachineOpcode()) {
2127 case AMDGPU::S_LOAD_DWORD_IMM:
2128 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2130 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2131 if (NewOpcode == N->getMachineOpcode()) {
2132 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2135 case AMDGPU::S_LOAD_DWORDX4_IMM:
2136 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2137 if (NewOpcode == N->getMachineOpcode()) {
2138 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2140 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2143 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2145 const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2146 SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2147 MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2149 SmallVector<SDValue, 8> Ops;
2150 Ops.push_back(SDValue(RSrc, 0));
2151 Ops.push_back(N->getOperand(0));
2152 Ops.push_back(DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32));
2154 // Copy remaining operands so we keep any chain and glue nodes that follow
2155 // the normal operands.
2156 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2157 Ops.push_back(N->getOperand(I));
2159 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2164 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2165 const TargetRegisterClass *RC,
2166 unsigned Reg, EVT VT) const {
2167 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2169 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2170 cast<RegisterSDNode>(VReg)->getReg(), VT);