1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Custom DAG lowering for SI
13 //===----------------------------------------------------------------------===//
17 #define _USE_MATH_DEFINES
21 #include "SIISelLowering.h"
23 #include "AMDGPUIntrinsicInfo.h"
24 #include "AMDGPUSubtarget.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/ADT/SmallString.h"
38 SITargetLowering::SITargetLowering(TargetMachine &TM,
39 const AMDGPUSubtarget &STI)
40 : AMDGPUTargetLowering(TM, STI) {
41 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
42 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
44 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
45 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
47 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
48 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
50 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
51 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
52 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
54 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
55 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
57 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
58 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
60 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
61 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
63 computeRegisterProperties(STI.getRegisterInfo());
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
68 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
70 setOperationAction(ISD::ADD, MVT::i32, Legal);
71 setOperationAction(ISD::ADDC, MVT::i32, Legal);
72 setOperationAction(ISD::ADDE, MVT::i32, Legal);
73 setOperationAction(ISD::SUBC, MVT::i32, Legal);
74 setOperationAction(ISD::SUBE, MVT::i32, Legal);
76 setOperationAction(ISD::FSIN, MVT::f32, Custom);
77 setOperationAction(ISD::FCOS, MVT::f32, Custom);
79 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
80 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
82 // We need to custom lower vector stores from local memory
83 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
84 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
85 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
87 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
88 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
90 setOperationAction(ISD::STORE, MVT::i1, Custom);
91 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
93 setOperationAction(ISD::SELECT, MVT::i64, Custom);
94 setOperationAction(ISD::SELECT, MVT::f64, Promote);
95 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
97 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
98 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
99 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
100 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
102 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
103 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
105 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
107 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
108 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
109 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
111 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
115 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
122 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
123 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
124 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
125 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
127 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
128 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
130 for (MVT VT : MVT::integer_valuetypes()) {
134 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
135 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
136 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
137 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
139 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
140 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
141 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
142 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
144 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
145 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
146 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
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::f64, MVT::f32, Expand);
159 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
160 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
161 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
163 setOperationAction(ISD::LOAD, MVT::i1, Custom);
165 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
166 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
167 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
169 // These should use UDIVREM, so set them to expand
170 setOperationAction(ISD::UDIV, MVT::i64, Expand);
171 setOperationAction(ISD::UREM, MVT::i64, Expand);
173 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
174 setOperationAction(ISD::SELECT, MVT::i1, Promote);
176 // We only support LOAD/STORE and vector manipulation ops for vectors
177 // with > 4 elements.
178 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32}) {
179 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
183 case ISD::BUILD_VECTOR:
185 case ISD::EXTRACT_VECTOR_ELT:
186 case ISD::INSERT_VECTOR_ELT:
187 case ISD::INSERT_SUBVECTOR:
188 case ISD::EXTRACT_SUBVECTOR:
190 case ISD::CONCAT_VECTORS:
191 setOperationAction(Op, VT, Custom);
194 setOperationAction(Op, VT, Expand);
200 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
201 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
202 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
203 setOperationAction(ISD::FRINT, MVT::f64, Legal);
206 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
207 setOperationAction(ISD::FDIV, MVT::f32, Custom);
208 setOperationAction(ISD::FDIV, MVT::f64, Custom);
210 setTargetDAGCombine(ISD::FADD);
211 setTargetDAGCombine(ISD::FSUB);
212 setTargetDAGCombine(ISD::FMINNUM);
213 setTargetDAGCombine(ISD::FMAXNUM);
214 setTargetDAGCombine(ISD::SELECT_CC);
215 setTargetDAGCombine(ISD::SETCC);
216 setTargetDAGCombine(ISD::AND);
217 setTargetDAGCombine(ISD::OR);
218 setTargetDAGCombine(ISD::UINT_TO_FP);
220 // All memory operations. Some folding on the pointer operand is done to help
221 // matching the constant offsets in the addressing modes.
222 setTargetDAGCombine(ISD::LOAD);
223 setTargetDAGCombine(ISD::STORE);
224 setTargetDAGCombine(ISD::ATOMIC_LOAD);
225 setTargetDAGCombine(ISD::ATOMIC_STORE);
226 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
227 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
228 setTargetDAGCombine(ISD::ATOMIC_SWAP);
229 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
230 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
231 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
232 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
233 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
234 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
235 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
240 setSchedulingPreference(Sched::RegPressure);
243 //===----------------------------------------------------------------------===//
244 // TargetLowering queries
245 //===----------------------------------------------------------------------===//
247 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
249 // SI has some legal vector types, but no legal vector operations. Say no
250 // shuffles are legal in order to prefer scalarizing some vector operations.
254 // FIXME: This really needs an address space argument. The immediate offset
255 // size is different for different sets of memory instruction sets.
257 // The single offset DS instructions have a 16-bit unsigned byte offset.
259 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
260 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
261 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
263 // SMRD instructions have an 8-bit, dword offset.
265 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
266 Type *Ty, unsigned AS) const {
267 // No global is ever allowed as a base.
271 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
273 if (!isUInt<16>(AM.BaseOffs))
278 case 0: // "r+i" or just "i", depending on HasBaseReg.
281 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
283 // Otherwise we have r+r or r+i.
286 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
290 default: // Don't allow n * r
297 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
300 bool *IsFast) const {
304 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
305 // which isn't a simple VT.
306 if (!VT.isSimple() || VT == MVT::Other)
309 // TODO - CI+ supports unaligned memory accesses, but this requires driver
312 // XXX - The only mention I see of this in the ISA manual is for LDS direct
313 // reads the "byte address and must be dword aligned". Is it also true for the
314 // normal loads and stores?
315 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
316 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
317 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
318 // with adjacent offsets.
319 return Align % 4 == 0;
322 // Smaller than dword value must be aligned.
323 // FIXME: This should be allowed on CI+
324 if (VT.bitsLT(MVT::i32))
327 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
328 // byte-address are ignored, thus forcing Dword alignment.
329 // This applies to private, global, and constant memory.
333 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
336 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
337 unsigned SrcAlign, bool IsMemset,
340 MachineFunction &MF) const {
341 // FIXME: Should account for address space here.
343 // The default fallback uses the private pointer size as a guess for a type to
344 // use. Make sure we switch these to 64-bit accesses.
346 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
349 if (Size >= 8 && DstAlign >= 4)
356 TargetLoweringBase::LegalizeTypeAction
357 SITargetLowering::getPreferredVectorAction(EVT VT) const {
358 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
359 return TypeSplitVector;
361 return TargetLoweringBase::getPreferredVectorAction(VT);
364 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
366 const SIInstrInfo *TII =
367 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
368 return TII->isInlineConstant(Imm);
371 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
372 SDLoc SL, SDValue Chain,
373 unsigned Offset, bool Signed) const {
374 const DataLayout *DL = getDataLayout();
375 MachineFunction &MF = DAG.getMachineFunction();
376 const SIRegisterInfo *TRI =
377 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
378 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
380 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
382 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
383 MVT PtrVT = getPointerTy(AMDGPUAS::CONSTANT_ADDRESS);
384 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
385 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
386 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
387 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
388 DAG.getConstant(Offset, SL, PtrVT));
389 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
390 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
392 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
393 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
395 true, // isNonTemporal
397 DL->getABITypeAlignment(Ty)); // Alignment
400 SDValue SITargetLowering::LowerFormalArguments(
401 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
402 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
403 SmallVectorImpl<SDValue> &InVals) const {
404 const SIRegisterInfo *TRI =
405 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
407 MachineFunction &MF = DAG.getMachineFunction();
408 FunctionType *FType = MF.getFunction()->getFunctionType();
409 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
411 assert(CallConv == CallingConv::C);
413 SmallVector<ISD::InputArg, 16> Splits;
414 BitVector Skipped(Ins.size());
416 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
417 const ISD::InputArg &Arg = Ins[i];
419 // First check if it's a PS input addr
420 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
421 !Arg.Flags.isByVal()) {
423 assert((PSInputNum <= 15) && "Too many PS inputs!");
426 // We can savely skip PS inputs
432 Info->PSInputAddr |= 1 << PSInputNum++;
435 // Second split vertices into their elements
436 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
437 ISD::InputArg NewArg = Arg;
438 NewArg.Flags.setSplit();
439 NewArg.VT = Arg.VT.getVectorElementType();
441 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
442 // three or five element vertex only needs three or five registers,
443 // NOT four or eigth.
444 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
445 unsigned NumElements = ParamType->getVectorNumElements();
447 for (unsigned j = 0; j != NumElements; ++j) {
448 Splits.push_back(NewArg);
449 NewArg.PartOffset += NewArg.VT.getStoreSize();
452 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
453 Splits.push_back(Arg);
457 SmallVector<CCValAssign, 16> ArgLocs;
458 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
461 // At least one interpolation mode must be enabled or else the GPU will hang.
462 if (Info->getShaderType() == ShaderType::PIXEL &&
463 (Info->PSInputAddr & 0x7F) == 0) {
464 Info->PSInputAddr |= 1;
465 CCInfo.AllocateReg(AMDGPU::VGPR0);
466 CCInfo.AllocateReg(AMDGPU::VGPR1);
469 // The pointer to the list of arguments is stored in SGPR0, SGPR1
470 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
471 if (Info->getShaderType() == ShaderType::COMPUTE) {
472 if (Subtarget->isAmdHsaOS())
473 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
475 Info->NumUserSGPRs = 4;
477 unsigned InputPtrReg =
478 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
479 unsigned InputPtrRegLo =
480 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
481 unsigned InputPtrRegHi =
482 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
484 unsigned ScratchPtrReg =
485 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
486 unsigned ScratchPtrRegLo =
487 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
488 unsigned ScratchPtrRegHi =
489 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
491 CCInfo.AllocateReg(InputPtrRegLo);
492 CCInfo.AllocateReg(InputPtrRegHi);
493 CCInfo.AllocateReg(ScratchPtrRegLo);
494 CCInfo.AllocateReg(ScratchPtrRegHi);
495 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
496 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
499 if (Info->getShaderType() == ShaderType::COMPUTE) {
500 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
504 AnalyzeFormalArguments(CCInfo, Splits);
506 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
508 const ISD::InputArg &Arg = Ins[i];
510 InVals.push_back(DAG.getUNDEF(Arg.VT));
514 CCValAssign &VA = ArgLocs[ArgIdx++];
515 MVT VT = VA.getLocVT();
519 EVT MemVT = Splits[i].VT;
520 const unsigned Offset = 36 + VA.getLocMemOffset();
521 // The first 36 bytes of the input buffer contains information about
522 // thread group and global sizes.
523 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
524 Offset, Ins[i].Flags.isSExt());
526 const PointerType *ParamTy =
527 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
528 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
529 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
530 // On SI local pointers are just offsets into LDS, so they are always
531 // less than 16-bits. On CI and newer they could potentially be
532 // real pointers, so we can't guarantee their size.
533 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
534 DAG.getValueType(MVT::i16));
537 InVals.push_back(Arg);
538 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
541 assert(VA.isRegLoc() && "Parameter must be in a register!");
543 unsigned Reg = VA.getLocReg();
545 if (VT == MVT::i64) {
546 // For now assume it is a pointer
547 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
548 &AMDGPU::SReg_64RegClass);
549 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
550 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
554 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
556 Reg = MF.addLiveIn(Reg, RC);
557 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
559 if (Arg.VT.isVector()) {
561 // Build a vector from the registers
562 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
563 unsigned NumElements = ParamType->getVectorNumElements();
565 SmallVector<SDValue, 4> Regs;
567 for (unsigned j = 1; j != NumElements; ++j) {
568 Reg = ArgLocs[ArgIdx++].getLocReg();
569 Reg = MF.addLiveIn(Reg, RC);
570 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
573 // Fill up the missing vector elements
574 NumElements = Arg.VT.getVectorNumElements() - NumElements;
575 Regs.append(NumElements, DAG.getUNDEF(VT));
577 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
581 InVals.push_back(Val);
584 if (Info->getShaderType() != ShaderType::COMPUTE) {
585 unsigned ScratchIdx = CCInfo.getFirstUnallocated(ArrayRef<MCPhysReg>(
586 AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs()));
587 Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
592 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
593 MachineInstr * MI, MachineBasicBlock * BB) const {
595 MachineBasicBlock::iterator I = *MI;
596 const SIInstrInfo *TII =
597 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
599 switch (MI->getOpcode()) {
601 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
604 case AMDGPU::SI_RegisterStorePseudo: {
605 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
606 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
607 MachineInstrBuilder MIB =
608 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
610 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
611 MIB.addOperand(MI->getOperand(i));
613 MI->eraseFromParent();
620 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
621 // This currently forces unfolding various combinations of fsub into fma with
622 // free fneg'd operands. As long as we have fast FMA (controlled by
623 // isFMAFasterThanFMulAndFAdd), we should perform these.
625 // When fma is quarter rate, for f64 where add / sub are at best half rate,
626 // most of these combines appear to be cycle neutral but save on instruction
627 // count / code size.
631 EVT SITargetLowering::getSetCCResultType(LLVMContext &Ctx, EVT VT) const {
632 if (!VT.isVector()) {
635 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
638 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
642 // Answering this is somewhat tricky and depends on the specific device which
643 // have different rates for fma or all f64 operations.
645 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
646 // regardless of which device (although the number of cycles differs between
647 // devices), so it is always profitable for f64.
649 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
650 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
651 // which we can always do even without fused FP ops since it returns the same
652 // result as the separate operations and since it is always full
653 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
654 // however does not support denormals, so we do report fma as faster if we have
655 // a fast fma device and require denormals.
657 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
658 VT = VT.getScalarType();
663 switch (VT.getSimpleVT().SimpleTy) {
665 // This is as fast on some subtargets. However, we always have full rate f32
666 // mad available which returns the same result as the separate operations
667 // which we should prefer over fma. We can't use this if we want to support
668 // denormals, so only report this in these cases.
669 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
679 //===----------------------------------------------------------------------===//
680 // Custom DAG Lowering Operations
681 //===----------------------------------------------------------------------===//
683 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
684 switch (Op.getOpcode()) {
685 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
686 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
687 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
689 SDValue Result = LowerLOAD(Op, DAG);
690 assert((!Result.getNode() ||
691 Result.getNode()->getNumValues() == 2) &&
692 "Load should return a value and a chain");
698 return LowerTrig(Op, DAG);
699 case ISD::SELECT: return LowerSELECT(Op, DAG);
700 case ISD::FDIV: return LowerFDIV(Op, DAG);
701 case ISD::STORE: return LowerSTORE(Op, DAG);
702 case ISD::GlobalAddress: {
703 MachineFunction &MF = DAG.getMachineFunction();
704 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
705 return LowerGlobalAddress(MFI, Op, DAG);
707 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
708 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
713 /// \brief Helper function for LowerBRCOND
714 static SDNode *findUser(SDValue Value, unsigned Opcode) {
716 SDNode *Parent = Value.getNode();
717 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
720 if (I.getUse().get() != Value)
723 if (I->getOpcode() == Opcode)
729 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
731 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
732 unsigned FrameIndex = FINode->getIndex();
734 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
737 /// This transforms the control flow intrinsics to get the branch destination as
738 /// last parameter, also switches branch target with BR if the need arise
739 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
740 SelectionDAG &DAG) const {
744 SDNode *Intr = BRCOND.getOperand(1).getNode();
745 SDValue Target = BRCOND.getOperand(2);
746 SDNode *BR = nullptr;
748 if (Intr->getOpcode() == ISD::SETCC) {
749 // As long as we negate the condition everything is fine
750 SDNode *SetCC = Intr;
751 assert(SetCC->getConstantOperandVal(1) == 1);
752 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
754 Intr = SetCC->getOperand(0).getNode();
757 // Get the target from BR if we don't negate the condition
758 BR = findUser(BRCOND, ISD::BR);
759 Target = BR->getOperand(1);
762 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
764 // Build the result and
765 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
767 // operands of the new intrinsic call
768 SmallVector<SDValue, 4> Ops;
769 Ops.push_back(BRCOND.getOperand(0));
770 Ops.append(Intr->op_begin() + 1, Intr->op_end());
771 Ops.push_back(Target);
773 // build the new intrinsic call
774 SDNode *Result = DAG.getNode(
775 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
776 DAG.getVTList(Res), Ops).getNode();
779 // Give the branch instruction our target
784 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
785 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
786 BR = NewBR.getNode();
789 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
791 // Copy the intrinsic results to registers
792 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
793 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
797 Chain = DAG.getCopyToReg(
799 CopyToReg->getOperand(1),
800 SDValue(Result, i - 1),
803 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
806 // Remove the old intrinsic from the chain
807 DAG.ReplaceAllUsesOfValueWith(
808 SDValue(Intr, Intr->getNumValues() - 1),
809 Intr->getOperand(0));
814 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
816 SelectionDAG &DAG) const {
817 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
819 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
820 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
823 const GlobalValue *GV = GSD->getGlobal();
824 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
826 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
827 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
829 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
830 DAG.getConstant(0, DL, MVT::i32));
831 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
832 DAG.getConstant(1, DL, MVT::i32));
834 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
836 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
837 PtrHi, DAG.getConstant(0, DL, MVT::i32),
838 SDValue(Lo.getNode(), 1));
839 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
842 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
844 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
845 // so we will end up with redundant moves to m0.
847 // We can't use S_MOV_B32, because there is no way to specify m0 as the
848 // destination register.
850 // We have to use them both. Machine cse will combine all the S_MOV_B32
851 // instructions and the register coalescer eliminate the extra copies.
852 SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
853 return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
854 SDValue(M0, 0), SDValue()); // Glue
855 // A Null SDValue creates
859 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
860 SelectionDAG &DAG) const {
861 MachineFunction &MF = DAG.getMachineFunction();
862 const SIRegisterInfo *TRI =
863 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
865 EVT VT = Op.getValueType();
867 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
869 switch (IntrinsicID) {
870 case Intrinsic::r600_read_ngroups_x:
871 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
872 SI::KernelInputOffsets::NGROUPS_X, false);
873 case Intrinsic::r600_read_ngroups_y:
874 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
875 SI::KernelInputOffsets::NGROUPS_Y, false);
876 case Intrinsic::r600_read_ngroups_z:
877 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
878 SI::KernelInputOffsets::NGROUPS_Z, false);
879 case Intrinsic::r600_read_global_size_x:
880 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
881 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
882 case Intrinsic::r600_read_global_size_y:
883 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
884 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
885 case Intrinsic::r600_read_global_size_z:
886 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
887 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
888 case Intrinsic::r600_read_local_size_x:
889 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
890 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
891 case Intrinsic::r600_read_local_size_y:
892 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
893 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
894 case Intrinsic::r600_read_local_size_z:
895 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
896 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
898 case Intrinsic::AMDGPU_read_workdim:
899 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
900 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
903 case Intrinsic::r600_read_tgid_x:
904 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
905 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
906 case Intrinsic::r600_read_tgid_y:
907 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
908 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
909 case Intrinsic::r600_read_tgid_z:
910 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
911 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
912 case Intrinsic::r600_read_tidig_x:
913 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
914 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
915 case Intrinsic::r600_read_tidig_y:
916 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
917 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
918 case Intrinsic::r600_read_tidig_z:
919 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
920 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
921 case AMDGPUIntrinsic::SI_load_const: {
927 MachineMemOperand *MMO = MF.getMachineMemOperand(
928 MachinePointerInfo(),
929 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
930 VT.getStoreSize(), 4);
931 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
932 Op->getVTList(), Ops, VT, MMO);
934 case AMDGPUIntrinsic::SI_sample:
935 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
936 case AMDGPUIntrinsic::SI_sampleb:
937 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
938 case AMDGPUIntrinsic::SI_sampled:
939 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
940 case AMDGPUIntrinsic::SI_samplel:
941 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
942 case AMDGPUIntrinsic::SI_vs_load_input:
943 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
948 case AMDGPUIntrinsic::AMDGPU_fract:
949 case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
950 return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
951 DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
952 case AMDGPUIntrinsic::SI_fs_constant: {
953 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
954 SDValue Glue = M0.getValue(1);
955 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
956 DAG.getConstant(2, DL, MVT::i32), // P0
957 Op.getOperand(1), Op.getOperand(2), Glue);
959 case AMDGPUIntrinsic::SI_fs_interp: {
960 SDValue IJ = Op.getOperand(4);
961 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
962 DAG.getConstant(0, DL, MVT::i32));
963 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
964 DAG.getConstant(1, DL, MVT::i32));
965 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
966 SDValue Glue = M0.getValue(1);
967 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
968 DAG.getVTList(MVT::f32, MVT::Glue),
969 I, Op.getOperand(1), Op.getOperand(2), Glue);
970 Glue = SDValue(P1.getNode(), 1);
971 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
972 Op.getOperand(1), Op.getOperand(2), Glue);
975 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
979 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
980 SelectionDAG &DAG) const {
981 MachineFunction &MF = DAG.getMachineFunction();
983 SDValue Chain = Op.getOperand(0);
984 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
986 switch (IntrinsicID) {
987 case AMDGPUIntrinsic::SI_sendmsg: {
988 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
989 SDValue Glue = Chain.getValue(1);
990 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
991 Op.getOperand(2), Glue);
993 case AMDGPUIntrinsic::SI_tbuffer_store: {
1011 EVT VT = Op.getOperand(3).getValueType();
1013 MachineMemOperand *MMO = MF.getMachineMemOperand(
1014 MachinePointerInfo(),
1015 MachineMemOperand::MOStore,
1016 VT.getStoreSize(), 4);
1017 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1018 Op->getVTList(), Ops, VT, MMO);
1025 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1027 LoadSDNode *Load = cast<LoadSDNode>(Op);
1029 if (Op.getValueType().isVector()) {
1030 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1031 "Custom lowering for non-i32 vectors hasn't been implemented.");
1032 unsigned NumElements = Op.getValueType().getVectorNumElements();
1033 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1034 switch (Load->getAddressSpace()) {
1036 case AMDGPUAS::GLOBAL_ADDRESS:
1037 case AMDGPUAS::PRIVATE_ADDRESS:
1038 // v4 loads are supported for private and global memory.
1039 if (NumElements <= 4)
1042 case AMDGPUAS::LOCAL_ADDRESS:
1043 return ScalarizeVectorLoad(Op, DAG);
1047 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1050 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1052 SelectionDAG &DAG) const {
1053 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1059 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1060 if (Op.getValueType() != MVT::i64)
1064 SDValue Cond = Op.getOperand(0);
1066 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1067 SDValue One = DAG.getConstant(1, DL, MVT::i32);
1069 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1070 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1072 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1073 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1075 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1077 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1078 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1080 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1082 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1083 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1086 // Catch division cases where we can use shortcuts with rcp and rsq
1088 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1090 SDValue LHS = Op.getOperand(0);
1091 SDValue RHS = Op.getOperand(1);
1092 EVT VT = Op.getValueType();
1093 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1095 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1096 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1097 CLHS->isExactlyValue(1.0)) {
1098 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1099 // the CI documentation has a worst case error of 1 ulp.
1100 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1101 // use it as long as we aren't trying to use denormals.
1103 // 1.0 / sqrt(x) -> rsq(x)
1105 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1106 // error seems really high at 2^29 ULP.
1107 if (RHS.getOpcode() == ISD::FSQRT)
1108 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1110 // 1.0 / x -> rcp(x)
1111 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1116 // Turn into multiply by the reciprocal.
1117 // x / y -> x * (1.0 / y)
1118 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1119 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1125 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1126 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1127 if (FastLowered.getNode())
1130 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1131 // selection error for now rather than do something incorrect.
1132 if (Subtarget->hasFP32Denormals())
1136 SDValue LHS = Op.getOperand(0);
1137 SDValue RHS = Op.getOperand(1);
1139 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1141 const APFloat K0Val(BitsToFloat(0x6f800000));
1142 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1144 const APFloat K1Val(BitsToFloat(0x2f800000));
1145 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1147 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1149 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1151 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1153 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1155 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1157 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1159 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1161 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1164 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1165 if (DAG.getTarget().Options.UnsafeFPMath)
1166 return LowerFastFDIV(Op, DAG);
1169 SDValue X = Op.getOperand(0);
1170 SDValue Y = Op.getOperand(1);
1172 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1174 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1176 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1178 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1180 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1182 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1184 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1186 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1188 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1190 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1191 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1193 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1194 NegDivScale0, Mul, DivScale1);
1198 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1199 // Workaround a hardware bug on SI where the condition output from div_scale
1202 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1204 // Figure out if the scale to use for div_fmas.
1205 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1206 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1207 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1208 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1210 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1211 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1214 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1216 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1218 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1219 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1220 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1222 Scale = DivScale1.getValue(1);
1225 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1226 Fma4, Fma3, Mul, Scale);
1228 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1231 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1232 EVT VT = Op.getValueType();
1235 return LowerFDIV32(Op, DAG);
1238 return LowerFDIV64(Op, DAG);
1240 llvm_unreachable("Unexpected type for fdiv");
1243 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1245 StoreSDNode *Store = cast<StoreSDNode>(Op);
1246 EVT VT = Store->getMemoryVT();
1248 // These stores are legal.
1249 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1250 if (VT.isVector() && VT.getVectorNumElements() > 4)
1251 return ScalarizeVectorStore(Op, DAG);
1255 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1259 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1260 return ScalarizeVectorStore(Op, DAG);
1263 return DAG.getTruncStore(Store->getChain(), DL,
1264 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1265 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1270 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1272 EVT VT = Op.getValueType();
1273 SDValue Arg = Op.getOperand(0);
1274 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1275 DAG.getNode(ISD::FMUL, DL, VT, Arg,
1276 DAG.getConstantFP(0.5/M_PI, DL,
1279 switch (Op.getOpcode()) {
1281 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1283 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1285 llvm_unreachable("Wrong trig opcode");
1289 //===----------------------------------------------------------------------===//
1290 // Custom DAG optimizations
1291 //===----------------------------------------------------------------------===//
1293 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1294 DAGCombinerInfo &DCI) const {
1295 EVT VT = N->getValueType(0);
1296 EVT ScalarVT = VT.getScalarType();
1297 if (ScalarVT != MVT::f32)
1300 SelectionDAG &DAG = DCI.DAG;
1303 SDValue Src = N->getOperand(0);
1304 EVT SrcVT = Src.getValueType();
1306 // TODO: We could try to match extracting the higher bytes, which would be
1307 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1308 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1309 // about in practice.
1310 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1311 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1312 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1313 DCI.AddToWorklist(Cvt.getNode());
1318 // We are primarily trying to catch operations on illegal vector types
1319 // before they are expanded.
1320 // For scalars, we can use the more flexible method of checking masked bits
1321 // after legalization.
1322 if (!DCI.isBeforeLegalize() ||
1323 !SrcVT.isVector() ||
1324 SrcVT.getVectorElementType() != MVT::i8) {
1328 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1330 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1332 unsigned NElts = SrcVT.getVectorNumElements();
1333 if (!SrcVT.isSimple() && NElts != 3)
1336 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1337 // prevent a mess from expanding to v4i32 and repacking.
1338 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1339 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1340 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1341 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1342 LoadSDNode *Load = cast<LoadSDNode>(Src);
1344 unsigned AS = Load->getAddressSpace();
1345 unsigned Align = Load->getAlignment();
1346 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1347 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
1349 // Don't try to replace the load if we have to expand it due to alignment
1350 // problems. Otherwise we will end up scalarizing the load, and trying to
1351 // repack into the vector for no real reason.
1352 if (Align < ABIAlignment &&
1353 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1357 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1361 Load->getMemOperand());
1363 // Make sure successors of the original load stay after it by updating
1364 // them to use the new Chain.
1365 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1367 SmallVector<SDValue, 4> Elts;
1368 if (RegVT.isVector())
1369 DAG.ExtractVectorElements(NewLoad, Elts);
1371 Elts.push_back(NewLoad);
1373 SmallVector<SDValue, 4> Ops;
1375 unsigned EltIdx = 0;
1376 for (SDValue Elt : Elts) {
1377 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1378 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1379 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1380 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1381 DCI.AddToWorklist(Cvt.getNode());
1388 assert(Ops.size() == NElts);
1390 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1396 /// \brief Return true if the given offset Size in bytes can be folded into
1397 /// the immediate offsets of a memory instruction for the given address space.
1398 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1399 const AMDGPUSubtarget &STI) {
1401 case AMDGPUAS::GLOBAL_ADDRESS: {
1402 // MUBUF instructions a 12-bit offset in bytes.
1403 return isUInt<12>(OffsetSize);
1405 case AMDGPUAS::CONSTANT_ADDRESS: {
1406 // SMRD instructions have an 8-bit offset in dwords on SI and
1407 // a 20-bit offset in bytes on VI.
1408 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1409 return isUInt<20>(OffsetSize);
1411 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1413 case AMDGPUAS::LOCAL_ADDRESS:
1414 case AMDGPUAS::REGION_ADDRESS: {
1415 // The single offset versions have a 16-bit offset in bytes.
1416 return isUInt<16>(OffsetSize);
1418 case AMDGPUAS::PRIVATE_ADDRESS:
1419 // Indirect register addressing does not use any offsets.
1425 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1427 // This is a variant of
1428 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1430 // The normal DAG combiner will do this, but only if the add has one use since
1431 // that would increase the number of instructions.
1433 // This prevents us from seeing a constant offset that can be folded into a
1434 // memory instruction's addressing mode. If we know the resulting add offset of
1435 // a pointer can be folded into an addressing offset, we can replace the pointer
1436 // operand with the add of new constant offset. This eliminates one of the uses,
1437 // and may allow the remaining use to also be simplified.
1439 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1441 DAGCombinerInfo &DCI) const {
1442 SDValue N0 = N->getOperand(0);
1443 SDValue N1 = N->getOperand(1);
1445 if (N0.getOpcode() != ISD::ADD)
1448 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1452 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1456 // If the resulting offset is too large, we can't fold it into the addressing
1458 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1459 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1462 SelectionDAG &DAG = DCI.DAG;
1464 EVT VT = N->getValueType(0);
1466 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1467 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1469 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1472 SDValue SITargetLowering::performAndCombine(SDNode *N,
1473 DAGCombinerInfo &DCI) const {
1474 if (DCI.isBeforeLegalize())
1477 SelectionDAG &DAG = DCI.DAG;
1479 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1480 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1481 SDValue LHS = N->getOperand(0);
1482 SDValue RHS = N->getOperand(1);
1484 if (LHS.getOpcode() == ISD::SETCC &&
1485 RHS.getOpcode() == ISD::SETCC) {
1486 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1487 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1489 SDValue X = LHS.getOperand(0);
1490 SDValue Y = RHS.getOperand(0);
1491 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1494 if (LCC == ISD::SETO) {
1495 if (X != LHS.getOperand(1))
1498 if (RCC == ISD::SETUNE) {
1499 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1500 if (!C1 || !C1->isInfinity() || C1->isNegative())
1503 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1504 SIInstrFlags::N_SUBNORMAL |
1505 SIInstrFlags::N_ZERO |
1506 SIInstrFlags::P_ZERO |
1507 SIInstrFlags::P_SUBNORMAL |
1508 SIInstrFlags::P_NORMAL;
1510 static_assert(((~(SIInstrFlags::S_NAN |
1511 SIInstrFlags::Q_NAN |
1512 SIInstrFlags::N_INFINITY |
1513 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1517 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1518 X, DAG.getConstant(Mask, DL, MVT::i32));
1526 SDValue SITargetLowering::performOrCombine(SDNode *N,
1527 DAGCombinerInfo &DCI) const {
1528 SelectionDAG &DAG = DCI.DAG;
1529 SDValue LHS = N->getOperand(0);
1530 SDValue RHS = N->getOperand(1);
1532 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1533 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1534 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1535 SDValue Src = LHS.getOperand(0);
1536 if (Src != RHS.getOperand(0))
1539 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1540 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1544 // Only 10 bits are used.
1545 static const uint32_t MaxMask = 0x3ff;
1547 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1549 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1550 Src, DAG.getConstant(NewMask, DL, MVT::i32));
1556 SDValue SITargetLowering::performClassCombine(SDNode *N,
1557 DAGCombinerInfo &DCI) const {
1558 SelectionDAG &DAG = DCI.DAG;
1559 SDValue Mask = N->getOperand(1);
1561 // fp_class x, 0 -> false
1562 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1563 if (CMask->isNullValue())
1564 return DAG.getConstant(0, SDLoc(N), MVT::i1);
1570 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1573 return AMDGPUISD::FMAX3;
1574 case AMDGPUISD::SMAX:
1575 return AMDGPUISD::SMAX3;
1576 case AMDGPUISD::UMAX:
1577 return AMDGPUISD::UMAX3;
1579 return AMDGPUISD::FMIN3;
1580 case AMDGPUISD::SMIN:
1581 return AMDGPUISD::SMIN3;
1582 case AMDGPUISD::UMIN:
1583 return AMDGPUISD::UMIN3;
1585 llvm_unreachable("Not a min/max opcode");
1589 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1590 DAGCombinerInfo &DCI) const {
1591 SelectionDAG &DAG = DCI.DAG;
1593 unsigned Opc = N->getOpcode();
1594 SDValue Op0 = N->getOperand(0);
1595 SDValue Op1 = N->getOperand(1);
1597 // Only do this if the inner op has one use since this will just increases
1598 // register pressure for no benefit.
1600 // max(max(a, b), c)
1601 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1603 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1611 // max(a, max(b, c))
1612 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1614 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1625 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1626 DAGCombinerInfo &DCI) const {
1627 SelectionDAG &DAG = DCI.DAG;
1630 SDValue LHS = N->getOperand(0);
1631 SDValue RHS = N->getOperand(1);
1632 EVT VT = LHS.getValueType();
1634 if (VT != MVT::f32 && VT != MVT::f64)
1637 // Match isinf pattern
1638 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1639 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1640 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1641 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1645 const APFloat &APF = CRHS->getValueAPF();
1646 if (APF.isInfinity() && !APF.isNegative()) {
1647 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1648 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1649 DAG.getConstant(Mask, SL, MVT::i32));
1656 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1657 DAGCombinerInfo &DCI) const {
1658 SelectionDAG &DAG = DCI.DAG;
1661 switch (N->getOpcode()) {
1663 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1665 return performSetCCCombine(N, DCI);
1666 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1668 case AMDGPUISD::SMAX:
1669 case AMDGPUISD::SMIN:
1670 case AMDGPUISD::UMAX:
1671 case AMDGPUISD::UMIN: {
1672 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1673 N->getValueType(0) != MVT::f64 &&
1674 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1675 return performMin3Max3Combine(N, DCI);
1679 case AMDGPUISD::CVT_F32_UBYTE0:
1680 case AMDGPUISD::CVT_F32_UBYTE1:
1681 case AMDGPUISD::CVT_F32_UBYTE2:
1682 case AMDGPUISD::CVT_F32_UBYTE3: {
1683 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1685 SDValue Src = N->getOperand(0);
1686 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1688 APInt KnownZero, KnownOne;
1689 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1690 !DCI.isBeforeLegalizeOps());
1691 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1692 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1693 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1694 DCI.CommitTargetLoweringOpt(TLO);
1700 case ISD::UINT_TO_FP: {
1701 return performUCharToFloatCombine(N, DCI);
1704 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1707 EVT VT = N->getValueType(0);
1711 // Only do this if we are not trying to support denormals. v_mad_f32 does
1712 // not support denormals ever.
1713 if (Subtarget->hasFP32Denormals())
1716 SDValue LHS = N->getOperand(0);
1717 SDValue RHS = N->getOperand(1);
1719 // These should really be instruction patterns, but writing patterns with
1720 // source modiifiers is a pain.
1722 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1723 if (LHS.getOpcode() == ISD::FADD) {
1724 SDValue A = LHS.getOperand(0);
1725 if (A == LHS.getOperand(1)) {
1726 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1727 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1731 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1732 if (RHS.getOpcode() == ISD::FADD) {
1733 SDValue A = RHS.getOperand(0);
1734 if (A == RHS.getOperand(1)) {
1735 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1736 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1743 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1746 EVT VT = N->getValueType(0);
1748 // Try to get the fneg to fold into the source modifier. This undoes generic
1749 // DAG combines and folds them into the mad.
1751 // Only do this if we are not trying to support denormals. v_mad_f32 does
1752 // not support denormals ever.
1753 if (VT == MVT::f32 &&
1754 !Subtarget->hasFP32Denormals()) {
1755 SDValue LHS = N->getOperand(0);
1756 SDValue RHS = N->getOperand(1);
1757 if (LHS.getOpcode() == ISD::FADD) {
1758 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1760 SDValue A = LHS.getOperand(0);
1761 if (A == LHS.getOperand(1)) {
1762 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1763 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1765 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1769 if (RHS.getOpcode() == ISD::FADD) {
1770 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1772 SDValue A = RHS.getOperand(0);
1773 if (A == RHS.getOperand(1)) {
1774 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
1775 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1787 case ISD::ATOMIC_LOAD:
1788 case ISD::ATOMIC_STORE:
1789 case ISD::ATOMIC_CMP_SWAP:
1790 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1791 case ISD::ATOMIC_SWAP:
1792 case ISD::ATOMIC_LOAD_ADD:
1793 case ISD::ATOMIC_LOAD_SUB:
1794 case ISD::ATOMIC_LOAD_AND:
1795 case ISD::ATOMIC_LOAD_OR:
1796 case ISD::ATOMIC_LOAD_XOR:
1797 case ISD::ATOMIC_LOAD_NAND:
1798 case ISD::ATOMIC_LOAD_MIN:
1799 case ISD::ATOMIC_LOAD_MAX:
1800 case ISD::ATOMIC_LOAD_UMIN:
1801 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1802 if (DCI.isBeforeLegalize())
1805 MemSDNode *MemNode = cast<MemSDNode>(N);
1806 SDValue Ptr = MemNode->getBasePtr();
1808 // TODO: We could also do this for multiplies.
1809 unsigned AS = MemNode->getAddressSpace();
1810 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1811 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1813 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
1815 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1816 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1822 return performAndCombine(N, DCI);
1824 return performOrCombine(N, DCI);
1825 case AMDGPUISD::FP_CLASS:
1826 return performClassCombine(N, DCI);
1828 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1831 /// \brief Analyze the possible immediate value Op
1833 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1834 /// and the immediate value if it's a literal immediate
1835 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1837 const SIInstrInfo *TII =
1838 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1840 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1841 if (TII->isInlineConstant(Node->getAPIntValue()))
1844 uint64_t Val = Node->getZExtValue();
1845 return isUInt<32>(Val) ? Val : -1;
1848 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1849 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1852 if (Node->getValueType(0) == MVT::f32)
1853 return FloatToBits(Node->getValueAPF().convertToFloat());
1861 /// \brief Helper function for adjustWritemask
1862 static unsigned SubIdx2Lane(unsigned Idx) {
1865 case AMDGPU::sub0: return 0;
1866 case AMDGPU::sub1: return 1;
1867 case AMDGPU::sub2: return 2;
1868 case AMDGPU::sub3: return 3;
1872 /// \brief Adjust the writemask of MIMG instructions
1873 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1874 SelectionDAG &DAG) const {
1875 SDNode *Users[4] = { };
1877 unsigned OldDmask = Node->getConstantOperandVal(0);
1878 unsigned NewDmask = 0;
1880 // Try to figure out the used register components
1881 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1884 // Abort if we can't understand the usage
1885 if (!I->isMachineOpcode() ||
1886 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1889 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1890 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1891 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1893 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1895 // Set which texture component corresponds to the lane.
1897 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1899 Comp = countTrailingZeros(Dmask);
1900 Dmask &= ~(1 << Comp);
1903 // Abort if we have more than one user per component
1908 NewDmask |= 1 << Comp;
1911 // Abort if there's no change
1912 if (NewDmask == OldDmask)
1915 // Adjust the writemask in the node
1916 std::vector<SDValue> Ops;
1917 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
1918 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
1919 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1921 // If we only got one lane, replace it with a copy
1922 // (if NewDmask has only one bit set...)
1923 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1924 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
1926 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1927 SDLoc(), Users[Lane]->getValueType(0),
1928 SDValue(Node, 0), RC);
1929 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1933 // Update the users of the node with the new indices
1934 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1936 SDNode *User = Users[i];
1940 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
1941 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1945 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1946 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1947 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1952 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1953 /// with frame index operands.
1954 /// LLVM assumes that inputs are to these instructions are registers.
1955 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1956 SelectionDAG &DAG) const {
1958 SmallVector<SDValue, 8> Ops;
1959 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1960 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1961 Ops.push_back(Node->getOperand(i));
1966 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1967 Node->getOperand(i).getValueType(),
1968 Node->getOperand(i)), 0));
1971 DAG.UpdateNodeOperands(Node, Ops);
1974 /// \brief Fold the instructions after selecting them.
1975 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1976 SelectionDAG &DAG) const {
1977 const SIInstrInfo *TII =
1978 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1980 if (TII->isMIMG(Node->getMachineOpcode()))
1981 adjustWritemask(Node, DAG);
1983 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1984 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1985 legalizeTargetIndependentNode(Node, DAG);
1991 /// \brief Assign the register class depending on the number of
1992 /// bits set in the writemask
1993 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1994 SDNode *Node) const {
1995 const SIInstrInfo *TII =
1996 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1998 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1999 TII->legalizeOperands(MI);
2001 if (TII->isMIMG(MI->getOpcode())) {
2002 unsigned VReg = MI->getOperand(0).getReg();
2003 unsigned Writemask = MI->getOperand(1).getImm();
2004 unsigned BitsSet = 0;
2005 for (unsigned i = 0; i < 4; ++i)
2006 BitsSet += Writemask & (1 << i) ? 1 : 0;
2008 const TargetRegisterClass *RC;
2011 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
2012 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2013 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2016 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2017 MI->setDesc(TII->get(NewOpcode));
2018 MRI.setRegClass(VReg, RC);
2022 // Replace unused atomics with the no return version.
2023 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2024 if (NoRetAtomicOp != -1) {
2025 if (!Node->hasAnyUseOfValue(0)) {
2026 MI->setDesc(TII->get(NoRetAtomicOp));
2027 MI->RemoveOperand(0);
2034 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2035 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2036 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2039 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2041 SDValue Ptr) const {
2042 const SIInstrInfo *TII =
2043 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2045 // XXX - Workaround for moveToVALU not handling different register class
2046 // inserts for REG_SEQUENCE.
2048 // Build the half of the subregister with the constants.
2049 const SDValue Ops0[] = {
2050 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2051 buildSMovImm32(DAG, DL, 0),
2052 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2053 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2054 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2057 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2058 MVT::v2i32, Ops0), 0);
2060 // Combine the constants and the pointer.
2061 const SDValue Ops1[] = {
2062 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2064 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2066 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2069 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2071 const SDValue Ops[] = {
2072 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2074 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2075 buildSMovImm32(DAG, DL, 0),
2076 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2077 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2078 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2081 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2086 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2087 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2088 /// of the resource descriptor) to create an offset, which is added to the
2089 /// resource ponter.
2090 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2093 uint32_t RsrcDword1,
2094 uint64_t RsrcDword2And3) const {
2095 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2096 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2098 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2099 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2103 SDValue DataLo = buildSMovImm32(DAG, DL,
2104 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2105 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2107 const SDValue Ops[] = {
2108 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2110 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2112 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2114 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2116 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2119 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2122 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2124 SDValue Ptr) const {
2125 const SIInstrInfo *TII =
2126 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2127 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2130 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2133 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2134 const TargetRegisterClass *RC,
2135 unsigned Reg, EVT VT) const {
2136 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2138 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2139 cast<RegisterSDNode>(VReg)->getReg(), VT);
2142 //===----------------------------------------------------------------------===//
2143 // SI Inline Assembly Support
2144 //===----------------------------------------------------------------------===//
2146 std::pair<unsigned, const TargetRegisterClass *>
2147 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2148 const std::string &Constraint,
2150 if (Constraint == "r") {
2151 switch(VT.SimpleTy) {
2152 default: llvm_unreachable("Unhandled type for 'r' inline asm constraint");
2154 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2156 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2160 if (Constraint.size() > 1) {
2161 const TargetRegisterClass *RC = nullptr;
2162 if (Constraint[1] == 'v') {
2163 RC = &AMDGPU::VGPR_32RegClass;
2164 } else if (Constraint[1] == 's') {
2165 RC = &AMDGPU::SGPR_32RegClass;
2169 unsigned Idx = std::atoi(Constraint.substr(2).c_str());
2170 if (Idx < RC->getNumRegs())
2171 return std::make_pair(RC->getRegister(Idx), RC);
2174 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);