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 // We need to custom lower vector stores from local memory
94 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
95 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
96 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
98 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
99 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
101 setOperationAction(ISD::STORE, MVT::i1, Custom);
102 setOperationAction(ISD::STORE, MVT::i32, Custom);
103 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
104 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
106 setOperationAction(ISD::SELECT, MVT::f32, Promote);
107 AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
108 setOperationAction(ISD::SELECT, MVT::i64, Custom);
109 setOperationAction(ISD::SELECT, MVT::f64, Promote);
110 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
112 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
113 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
114 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
115 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
117 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
118 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
130 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
132 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
134 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
136 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
137 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
138 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
139 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
141 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
142 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
144 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
145 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
146 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
147 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
148 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
149 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
151 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
152 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
153 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
154 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
156 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
157 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
158 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
159 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
160 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
162 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
163 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
164 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
165 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
166 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
167 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
169 setOperationAction(ISD::LOAD, MVT::i1, Custom);
171 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
172 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
173 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
175 // These should use UDIVREM, so set them to expand
176 setOperationAction(ISD::UDIV, MVT::i64, Expand);
177 setOperationAction(ISD::UREM, MVT::i64, Expand);
179 // We only support LOAD/STORE and vector manipulation ops for vectors
180 // with > 4 elements.
182 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
185 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
186 setOperationAction(ISD::SELECT, MVT::i1, Promote);
188 for (MVT VT : VecTypes) {
189 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
193 case ISD::BUILD_VECTOR:
195 case ISD::EXTRACT_VECTOR_ELT:
196 case ISD::INSERT_VECTOR_ELT:
197 case ISD::INSERT_SUBVECTOR:
198 case ISD::EXTRACT_SUBVECTOR:
200 case ISD::CONCAT_VECTORS:
201 setOperationAction(Op, VT, Custom);
204 setOperationAction(Op, VT, Expand);
210 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
211 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
212 setOperationAction(ISD::FTRUNC, VT, Expand);
213 setOperationAction(ISD::FCEIL, VT, Expand);
214 setOperationAction(ISD::FFLOOR, VT, Expand);
217 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
218 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
219 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
220 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
221 setOperationAction(ISD::FRINT, MVT::f64, Legal);
224 setOperationAction(ISD::FDIV, MVT::f32, Custom);
226 setTargetDAGCombine(ISD::FADD);
227 setTargetDAGCombine(ISD::FSUB);
228 setTargetDAGCombine(ISD::SELECT_CC);
229 setTargetDAGCombine(ISD::SETCC);
231 setTargetDAGCombine(ISD::UINT_TO_FP);
233 // All memory operations. Some folding on the pointer operand is done to help
234 // matching the constant offsets in the addressing modes.
235 setTargetDAGCombine(ISD::LOAD);
236 setTargetDAGCombine(ISD::STORE);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD);
238 setTargetDAGCombine(ISD::ATOMIC_STORE);
239 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
240 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
241 setTargetDAGCombine(ISD::ATOMIC_SWAP);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
243 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
245 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
246 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
247 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
248 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
253 setSchedulingPreference(Sched::RegPressure);
256 //===----------------------------------------------------------------------===//
257 // TargetLowering queries
258 //===----------------------------------------------------------------------===//
260 // FIXME: This really needs an address space argument. The immediate offset
261 // size is different for different sets of memory instruction sets.
263 // The single offset DS instructions have a 16-bit unsigned byte offset.
265 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
266 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
267 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
269 // SMRD instructions have an 8-bit, dword offset.
271 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
273 // No global is ever allowed as a base.
277 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
279 if (!isUInt<16>(AM.BaseOffs))
284 case 0: // "r+i" or just "i", depending on HasBaseReg.
287 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
289 // Otherwise we have r+r or r+i.
292 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
296 default: // Don't allow n * r
303 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
306 bool *IsFast) const {
310 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
311 // which isn't a simple VT.
312 if (!VT.isSimple() || VT == MVT::Other)
315 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
316 // see what for specifically. The wording everywhere else seems to be the
319 // XXX - The only mention I see of this in the ISA manual is for LDS direct
320 // reads the "byte address and must be dword aligned". Is it also true for the
321 // normal loads and stores?
322 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
323 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
324 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
325 // with adjacent offsets.
326 return Align % 4 == 0;
329 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
330 // byte-address are ignored, thus forcing Dword alignment.
331 // This applies to private, global, and constant memory.
334 return VT.bitsGT(MVT::i32);
337 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
338 unsigned SrcAlign, bool IsMemset,
341 MachineFunction &MF) const {
342 // FIXME: Should account for address space here.
344 // The default fallback uses the private pointer size as a guess for a type to
345 // use. Make sure we switch these to 64-bit accesses.
347 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
350 if (Size >= 8 && DstAlign >= 4)
357 TargetLoweringBase::LegalizeTypeAction
358 SITargetLowering::getPreferredVectorAction(EVT VT) const {
359 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
360 return TypeSplitVector;
362 return TargetLoweringBase::getPreferredVectorAction(VT);
365 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
367 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
368 getTargetMachine().getSubtargetImpl()->getInstrInfo());
369 return TII->isInlineConstant(Imm);
372 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
373 SDLoc SL, SDValue Chain,
374 unsigned Offset, bool Signed) const {
375 const DataLayout *DL = getDataLayout();
376 MachineFunction &MF = DAG.getMachineFunction();
377 const SIRegisterInfo *TRI =
378 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
379 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
381 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
383 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
384 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
385 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
386 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
387 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
388 DAG.getConstant(Offset, MVT::i64));
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(
402 CallingConv::ID CallConv,
404 const SmallVectorImpl<ISD::InputArg> &Ins,
405 SDLoc DL, SelectionDAG &DAG,
406 SmallVectorImpl<SDValue> &InVals) const {
408 const TargetMachine &TM = getTargetMachine();
409 const SIRegisterInfo *TRI =
410 static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
412 MachineFunction &MF = DAG.getMachineFunction();
413 FunctionType *FType = MF.getFunction()->getFunctionType();
414 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
416 assert(CallConv == CallingConv::C);
418 SmallVector<ISD::InputArg, 16> Splits;
419 BitVector Skipped(Ins.size());
421 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
422 const ISD::InputArg &Arg = Ins[i];
424 // First check if it's a PS input addr
425 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
426 !Arg.Flags.isByVal()) {
428 assert((PSInputNum <= 15) && "Too many PS inputs!");
431 // We can savely skip PS inputs
437 Info->PSInputAddr |= 1 << PSInputNum++;
440 // Second split vertices into their elements
441 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
442 ISD::InputArg NewArg = Arg;
443 NewArg.Flags.setSplit();
444 NewArg.VT = Arg.VT.getVectorElementType();
446 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
447 // three or five element vertex only needs three or five registers,
448 // NOT four or eigth.
449 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
450 unsigned NumElements = ParamType->getVectorNumElements();
452 for (unsigned j = 0; j != NumElements; ++j) {
453 Splits.push_back(NewArg);
454 NewArg.PartOffset += NewArg.VT.getStoreSize();
457 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
458 Splits.push_back(Arg);
462 SmallVector<CCValAssign, 16> ArgLocs;
463 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
466 // At least one interpolation mode must be enabled or else the GPU will hang.
467 if (Info->getShaderType() == ShaderType::PIXEL &&
468 (Info->PSInputAddr & 0x7F) == 0) {
469 Info->PSInputAddr |= 1;
470 CCInfo.AllocateReg(AMDGPU::VGPR0);
471 CCInfo.AllocateReg(AMDGPU::VGPR1);
474 // The pointer to the list of arguments is stored in SGPR0, SGPR1
475 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
476 if (Info->getShaderType() == ShaderType::COMPUTE) {
477 Info->NumUserSGPRs = 4;
479 unsigned InputPtrReg =
480 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
481 unsigned InputPtrRegLo =
482 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
483 unsigned InputPtrRegHi =
484 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
486 unsigned ScratchPtrReg =
487 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
488 unsigned ScratchPtrRegLo =
489 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
490 unsigned ScratchPtrRegHi =
491 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
493 CCInfo.AllocateReg(InputPtrRegLo);
494 CCInfo.AllocateReg(InputPtrRegHi);
495 CCInfo.AllocateReg(ScratchPtrRegLo);
496 CCInfo.AllocateReg(ScratchPtrRegHi);
497 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
498 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
501 if (Info->getShaderType() == ShaderType::COMPUTE) {
502 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
506 AnalyzeFormalArguments(CCInfo, Splits);
508 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
510 const ISD::InputArg &Arg = Ins[i];
512 InVals.push_back(DAG.getUNDEF(Arg.VT));
516 CCValAssign &VA = ArgLocs[ArgIdx++];
517 EVT VT = VA.getLocVT();
521 EVT MemVT = Splits[i].VT;
522 const unsigned Offset = 36 + VA.getLocMemOffset();
523 // The first 36 bytes of the input buffer contains information about
524 // thread group and global sizes.
525 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
526 Offset, Ins[i].Flags.isSExt());
528 const PointerType *ParamTy =
529 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
530 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
531 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
532 // On SI local pointers are just offsets into LDS, so they are always
533 // less than 16-bits. On CI and newer they could potentially be
534 // real pointers, so we can't guarantee their size.
535 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
536 DAG.getValueType(MVT::i16));
539 InVals.push_back(Arg);
540 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
543 assert(VA.isRegLoc() && "Parameter must be in a register!");
545 unsigned Reg = VA.getLocReg();
547 if (VT == MVT::i64) {
548 // For now assume it is a pointer
549 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
550 &AMDGPU::SReg_64RegClass);
551 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
552 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
556 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
558 Reg = MF.addLiveIn(Reg, RC);
559 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
561 if (Arg.VT.isVector()) {
563 // Build a vector from the registers
564 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
565 unsigned NumElements = ParamType->getVectorNumElements();
567 SmallVector<SDValue, 4> Regs;
569 for (unsigned j = 1; j != NumElements; ++j) {
570 Reg = ArgLocs[ArgIdx++].getLocReg();
571 Reg = MF.addLiveIn(Reg, RC);
572 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
575 // Fill up the missing vector elements
576 NumElements = Arg.VT.getVectorNumElements() - NumElements;
577 for (unsigned j = 0; j != NumElements; ++j)
578 Regs.push_back(DAG.getUNDEF(VT));
580 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
584 InVals.push_back(Val);
589 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
590 MachineInstr * MI, MachineBasicBlock * BB) const {
592 MachineBasicBlock::iterator I = *MI;
593 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
594 getTargetMachine().getSubtargetImpl()->getInstrInfo());
595 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
597 switch (MI->getOpcode()) {
599 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
600 case AMDGPU::BRANCH: return BB;
601 case AMDGPU::SI_ADDR64_RSRC: {
602 unsigned SuperReg = MI->getOperand(0).getReg();
603 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
604 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
605 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
606 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
607 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
608 .addOperand(MI->getOperand(1));
609 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
611 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
612 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
613 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
615 .addImm(AMDGPU::sub0)
617 .addImm(AMDGPU::sub1);
618 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
620 .addImm(AMDGPU::sub0_sub1)
622 .addImm(AMDGPU::sub2_sub3);
623 MI->eraseFromParent();
626 case AMDGPU::V_SUB_F64: {
627 unsigned DestReg = MI->getOperand(0).getReg();
628 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
629 .addImm(0) // SRC0 modifiers
630 .addReg(MI->getOperand(1).getReg())
631 .addImm(1) // SRC1 modifiers
632 .addReg(MI->getOperand(2).getReg())
635 MI->eraseFromParent();
638 case AMDGPU::SI_RegisterStorePseudo: {
639 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
640 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
641 MachineInstrBuilder MIB =
642 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
644 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
645 MIB.addOperand(MI->getOperand(i));
647 MI->eraseFromParent();
650 case AMDGPU::FCLAMP_SI: {
651 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
652 getTargetMachine().getSubtargetImpl()->getInstrInfo());
653 DebugLoc DL = MI->getDebugLoc();
654 unsigned DestReg = MI->getOperand(0).getReg();
655 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
656 .addImm(0) // SRC0 modifiers
657 .addOperand(MI->getOperand(1))
658 .addImm(0) // SRC1 modifiers
662 MI->eraseFromParent();
668 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
669 if (!VT.isVector()) {
672 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
675 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
679 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
680 VT = VT.getScalarType();
685 switch (VT.getSimpleVT().SimpleTy) {
687 return false; /* There is V_MAD_F32 for f32 */
697 //===----------------------------------------------------------------------===//
698 // Custom DAG Lowering Operations
699 //===----------------------------------------------------------------------===//
701 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
702 switch (Op.getOpcode()) {
703 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
704 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
705 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
707 SDValue Result = LowerLOAD(Op, DAG);
708 assert((!Result.getNode() ||
709 Result.getNode()->getNumValues() == 2) &&
710 "Load should return a value and a chain");
716 return LowerTrig(Op, DAG);
717 case ISD::SELECT: return LowerSELECT(Op, DAG);
718 case ISD::FDIV: return LowerFDIV(Op, DAG);
719 case ISD::STORE: return LowerSTORE(Op, DAG);
720 case ISD::GlobalAddress: {
721 MachineFunction &MF = DAG.getMachineFunction();
722 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
723 return LowerGlobalAddress(MFI, Op, DAG);
725 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
726 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
731 /// \brief Helper function for LowerBRCOND
732 static SDNode *findUser(SDValue Value, unsigned Opcode) {
734 SDNode *Parent = Value.getNode();
735 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
738 if (I.getUse().get() != Value)
741 if (I->getOpcode() == Opcode)
747 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
749 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
750 unsigned FrameIndex = FINode->getIndex();
752 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
755 /// This transforms the control flow intrinsics to get the branch destination as
756 /// last parameter, also switches branch target with BR if the need arise
757 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
758 SelectionDAG &DAG) const {
762 SDNode *Intr = BRCOND.getOperand(1).getNode();
763 SDValue Target = BRCOND.getOperand(2);
764 SDNode *BR = nullptr;
766 if (Intr->getOpcode() == ISD::SETCC) {
767 // As long as we negate the condition everything is fine
768 SDNode *SetCC = Intr;
769 assert(SetCC->getConstantOperandVal(1) == 1);
770 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
772 Intr = SetCC->getOperand(0).getNode();
775 // Get the target from BR if we don't negate the condition
776 BR = findUser(BRCOND, ISD::BR);
777 Target = BR->getOperand(1);
780 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
782 // Build the result and
783 SmallVector<EVT, 4> Res;
784 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
785 Res.push_back(Intr->getValueType(i));
787 // operands of the new intrinsic call
788 SmallVector<SDValue, 4> Ops;
789 Ops.push_back(BRCOND.getOperand(0));
790 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
791 Ops.push_back(Intr->getOperand(i));
792 Ops.push_back(Target);
794 // build the new intrinsic call
795 SDNode *Result = DAG.getNode(
796 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
797 DAG.getVTList(Res), Ops).getNode();
800 // Give the branch instruction our target
805 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
806 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
807 BR = NewBR.getNode();
810 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
812 // Copy the intrinsic results to registers
813 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
814 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
818 Chain = DAG.getCopyToReg(
820 CopyToReg->getOperand(1),
821 SDValue(Result, i - 1),
824 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
827 // Remove the old intrinsic from the chain
828 DAG.ReplaceAllUsesOfValueWith(
829 SDValue(Intr, Intr->getNumValues() - 1),
830 Intr->getOperand(0));
835 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
837 SelectionDAG &DAG) const {
838 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
840 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
841 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
844 const GlobalValue *GV = GSD->getGlobal();
845 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
847 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
848 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
850 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
851 DAG.getConstant(0, MVT::i32));
852 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
853 DAG.getConstant(1, MVT::i32));
855 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
857 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
858 PtrHi, DAG.getConstant(0, MVT::i32),
859 SDValue(Lo.getNode(), 1));
860 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
863 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
864 SelectionDAG &DAG) const {
865 MachineFunction &MF = DAG.getMachineFunction();
866 const SIRegisterInfo *TRI =
867 static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
869 EVT VT = Op.getValueType();
871 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
873 switch (IntrinsicID) {
874 case Intrinsic::r600_read_ngroups_x:
875 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
876 SI::KernelInputOffsets::NGROUPS_X, false);
877 case Intrinsic::r600_read_ngroups_y:
878 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
879 SI::KernelInputOffsets::NGROUPS_Y, false);
880 case Intrinsic::r600_read_ngroups_z:
881 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
882 SI::KernelInputOffsets::NGROUPS_Z, false);
883 case Intrinsic::r600_read_global_size_x:
884 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
885 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
886 case Intrinsic::r600_read_global_size_y:
887 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
888 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
889 case Intrinsic::r600_read_global_size_z:
890 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
891 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
892 case Intrinsic::r600_read_local_size_x:
893 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
894 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
895 case Intrinsic::r600_read_local_size_y:
896 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
897 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
898 case Intrinsic::r600_read_local_size_z:
899 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
900 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
902 case Intrinsic::AMDGPU_read_workdim:
903 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
904 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
907 case Intrinsic::r600_read_tgid_x:
908 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
909 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
910 case Intrinsic::r600_read_tgid_y:
911 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
912 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
913 case Intrinsic::r600_read_tgid_z:
914 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
915 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
916 case Intrinsic::r600_read_tidig_x:
917 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
918 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
919 case Intrinsic::r600_read_tidig_y:
920 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
921 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
922 case Intrinsic::r600_read_tidig_z:
923 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
924 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
925 case AMDGPUIntrinsic::SI_load_const: {
931 MachineMemOperand *MMO = MF.getMachineMemOperand(
932 MachinePointerInfo(),
933 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
934 VT.getStoreSize(), 4);
935 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
936 Op->getVTList(), Ops, VT, MMO);
938 case AMDGPUIntrinsic::SI_sample:
939 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
940 case AMDGPUIntrinsic::SI_sampleb:
941 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
942 case AMDGPUIntrinsic::SI_sampled:
943 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
944 case AMDGPUIntrinsic::SI_samplel:
945 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
946 case AMDGPUIntrinsic::SI_vs_load_input:
947 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
952 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
956 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
957 SelectionDAG &DAG) const {
958 MachineFunction &MF = DAG.getMachineFunction();
959 SDValue Chain = Op.getOperand(0);
960 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
962 switch (IntrinsicID) {
963 case AMDGPUIntrinsic::SI_tbuffer_store: {
982 EVT VT = Op.getOperand(3).getValueType();
984 MachineMemOperand *MMO = MF.getMachineMemOperand(
985 MachinePointerInfo(),
986 MachineMemOperand::MOStore,
987 VT.getStoreSize(), 4);
988 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
989 Op->getVTList(), Ops, VT, MMO);
996 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
998 LoadSDNode *Load = cast<LoadSDNode>(Op);
1000 if (Op.getValueType().isVector()) {
1001 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1002 "Custom lowering for non-i32 vectors hasn't been implemented.");
1003 unsigned NumElements = Op.getValueType().getVectorNumElements();
1004 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1005 switch (Load->getAddressSpace()) {
1007 case AMDGPUAS::GLOBAL_ADDRESS:
1008 case AMDGPUAS::PRIVATE_ADDRESS:
1009 // v4 loads are supported for private and global memory.
1010 if (NumElements <= 4)
1013 case AMDGPUAS::LOCAL_ADDRESS:
1014 return ScalarizeVectorLoad(Op, DAG);
1018 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1021 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1023 SelectionDAG &DAG) const {
1024 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1030 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1031 if (Op.getValueType() != MVT::i64)
1035 SDValue Cond = Op.getOperand(0);
1037 SDValue Zero = DAG.getConstant(0, MVT::i32);
1038 SDValue One = DAG.getConstant(1, MVT::i32);
1040 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1041 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1043 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1044 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1046 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1048 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1049 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1051 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1053 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1054 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1057 // Catch division cases where we can use shortcuts with rcp and rsq
1059 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1061 SDValue LHS = Op.getOperand(0);
1062 SDValue RHS = Op.getOperand(1);
1063 EVT VT = Op.getValueType();
1064 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1066 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1067 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1068 CLHS->isExactlyValue(1.0)) {
1069 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1070 // the CI documentation has a worst case error of 1 ulp.
1071 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1072 // use it as long as we aren't trying to use denormals.
1074 // 1.0 / sqrt(x) -> rsq(x)
1076 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1077 // error seems really high at 2^29 ULP.
1078 if (RHS.getOpcode() == ISD::FSQRT)
1079 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1081 // 1.0 / x -> rcp(x)
1082 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1087 // Turn into multiply by the reciprocal.
1088 // x / y -> x * (1.0 / y)
1089 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1090 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1096 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1097 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1098 if (FastLowered.getNode())
1101 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1102 // selection error for now rather than do something incorrect.
1103 if (Subtarget->hasFP32Denormals())
1107 SDValue LHS = Op.getOperand(0);
1108 SDValue RHS = Op.getOperand(1);
1110 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1112 const APFloat K0Val(BitsToFloat(0x6f800000));
1113 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1115 const APFloat K1Val(BitsToFloat(0x2f800000));
1116 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1118 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1120 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1122 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1124 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1126 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1128 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1130 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1132 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1135 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1139 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1140 EVT VT = Op.getValueType();
1143 return LowerFDIV32(Op, DAG);
1146 return LowerFDIV64(Op, DAG);
1148 llvm_unreachable("Unexpected type for fdiv");
1151 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1153 StoreSDNode *Store = cast<StoreSDNode>(Op);
1154 EVT VT = Store->getMemoryVT();
1156 // These stores are legal.
1157 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1158 VT.isVector() && VT.getVectorNumElements() == 2 &&
1159 VT.getVectorElementType() == MVT::i32)
1162 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1163 if (VT.isVector() && VT.getVectorNumElements() > 4)
1164 return ScalarizeVectorStore(Op, DAG);
1168 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1172 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1173 return ScalarizeVectorStore(Op, DAG);
1176 return DAG.getTruncStore(Store->getChain(), DL,
1177 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1178 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1183 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1184 EVT VT = Op.getValueType();
1185 SDValue Arg = Op.getOperand(0);
1186 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1187 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1188 DAG.getConstantFP(0.5 / M_PI, VT)));
1190 switch (Op.getOpcode()) {
1192 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1194 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1196 llvm_unreachable("Wrong trig opcode");
1200 //===----------------------------------------------------------------------===//
1201 // Custom DAG optimizations
1202 //===----------------------------------------------------------------------===//
1204 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1205 DAGCombinerInfo &DCI) {
1206 EVT VT = N->getValueType(0);
1207 EVT ScalarVT = VT.getScalarType();
1208 if (ScalarVT != MVT::f32)
1211 SelectionDAG &DAG = DCI.DAG;
1214 SDValue Src = N->getOperand(0);
1215 EVT SrcVT = Src.getValueType();
1217 // TODO: We could try to match extracting the higher bytes, which would be
1218 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1219 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1220 // about in practice.
1221 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1222 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1223 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1224 DCI.AddToWorklist(Cvt.getNode());
1229 // We are primarily trying to catch operations on illegal vector types
1230 // before they are expanded.
1231 // For scalars, we can use the more flexible method of checking masked bits
1232 // after legalization.
1233 if (!DCI.isBeforeLegalize() ||
1234 !SrcVT.isVector() ||
1235 SrcVT.getVectorElementType() != MVT::i8) {
1239 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1241 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1243 unsigned NElts = SrcVT.getVectorNumElements();
1244 if (!SrcVT.isSimple() && NElts != 3)
1247 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1248 // prevent a mess from expanding to v4i32 and repacking.
1249 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1250 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1251 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1252 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1254 LoadSDNode *Load = cast<LoadSDNode>(Src);
1255 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1259 Load->getMemOperand());
1261 // Make sure successors of the original load stay after it by updating
1262 // them to use the new Chain.
1263 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1265 SmallVector<SDValue, 4> Elts;
1266 if (RegVT.isVector())
1267 DAG.ExtractVectorElements(NewLoad, Elts);
1269 Elts.push_back(NewLoad);
1271 SmallVector<SDValue, 4> Ops;
1273 unsigned EltIdx = 0;
1274 for (SDValue Elt : Elts) {
1275 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1276 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1277 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1278 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1279 DCI.AddToWorklist(Cvt.getNode());
1286 assert(Ops.size() == NElts);
1288 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1294 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1296 // This is a variant of
1297 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1299 // The normal DAG combiner will do this, but only if the add has one use since
1300 // that would increase the number of instructions.
1302 // This prevents us from seeing a constant offset that can be folded into a
1303 // memory instruction's addressing mode. If we know the resulting add offset of
1304 // a pointer can be folded into an addressing offset, we can replace the pointer
1305 // operand with the add of new constant offset. This eliminates one of the uses,
1306 // and may allow the remaining use to also be simplified.
1308 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1310 DAGCombinerInfo &DCI) const {
1311 SDValue N0 = N->getOperand(0);
1312 SDValue N1 = N->getOperand(1);
1314 if (N0.getOpcode() != ISD::ADD)
1317 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1321 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1325 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1326 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1328 // If the resulting offset is too large, we can't fold it into the addressing
1330 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1331 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1334 SelectionDAG &DAG = DCI.DAG;
1336 EVT VT = N->getValueType(0);
1338 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1339 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1341 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1344 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1345 DAGCombinerInfo &DCI) const {
1346 SelectionDAG &DAG = DCI.DAG;
1348 EVT VT = N->getValueType(0);
1350 switch (N->getOpcode()) {
1351 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1353 SDValue Arg0 = N->getOperand(0);
1354 SDValue Arg1 = N->getOperand(1);
1355 SDValue CC = N->getOperand(2);
1356 ConstantSDNode * C = nullptr;
1357 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1359 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1361 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1362 && Arg0.getOperand(0).getValueType() == MVT::i1
1363 && (C = dyn_cast<ConstantSDNode>(Arg1))
1365 && CCOp == ISD::SETNE) {
1366 return SimplifySetCC(VT, Arg0.getOperand(0),
1367 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1372 case AMDGPUISD::CVT_F32_UBYTE0:
1373 case AMDGPUISD::CVT_F32_UBYTE1:
1374 case AMDGPUISD::CVT_F32_UBYTE2:
1375 case AMDGPUISD::CVT_F32_UBYTE3: {
1376 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1378 SDValue Src = N->getOperand(0);
1379 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1381 APInt KnownZero, KnownOne;
1382 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1383 !DCI.isBeforeLegalizeOps());
1384 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1385 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1386 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1387 DCI.CommitTargetLoweringOpt(TLO);
1393 case ISD::UINT_TO_FP: {
1394 return performUCharToFloatCombine(N, DCI);
1397 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1400 EVT VT = N->getValueType(0);
1404 SDValue LHS = N->getOperand(0);
1405 SDValue RHS = N->getOperand(1);
1407 // These should really be instruction patterns, but writing patterns with
1408 // source modiifiers is a pain.
1410 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1411 if (LHS.getOpcode() == ISD::FADD) {
1412 SDValue A = LHS.getOperand(0);
1413 if (A == LHS.getOperand(1)) {
1414 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1415 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1419 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1420 if (RHS.getOpcode() == ISD::FADD) {
1421 SDValue A = RHS.getOperand(0);
1422 if (A == RHS.getOperand(1)) {
1423 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1424 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1431 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1434 EVT VT = N->getValueType(0);
1436 // Try to get the fneg to fold into the source modifier. This undoes generic
1437 // DAG combines and folds them into the mad.
1438 if (VT == MVT::f32) {
1439 SDValue LHS = N->getOperand(0);
1440 SDValue RHS = N->getOperand(1);
1442 if (LHS.getOpcode() == ISD::FMUL) {
1443 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1445 SDValue A = LHS.getOperand(0);
1446 SDValue B = LHS.getOperand(1);
1447 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1449 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1452 if (RHS.getOpcode() == ISD::FMUL) {
1453 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1455 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1456 SDValue B = RHS.getOperand(1);
1459 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1462 if (LHS.getOpcode() == ISD::FADD) {
1463 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1465 SDValue A = LHS.getOperand(0);
1466 if (A == LHS.getOperand(1)) {
1467 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1468 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1470 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1474 if (RHS.getOpcode() == ISD::FADD) {
1475 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1477 SDValue A = RHS.getOperand(0);
1478 if (A == RHS.getOperand(1)) {
1479 const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
1480 return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1490 case ISD::ATOMIC_LOAD:
1491 case ISD::ATOMIC_STORE:
1492 case ISD::ATOMIC_CMP_SWAP:
1493 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1494 case ISD::ATOMIC_SWAP:
1495 case ISD::ATOMIC_LOAD_ADD:
1496 case ISD::ATOMIC_LOAD_SUB:
1497 case ISD::ATOMIC_LOAD_AND:
1498 case ISD::ATOMIC_LOAD_OR:
1499 case ISD::ATOMIC_LOAD_XOR:
1500 case ISD::ATOMIC_LOAD_NAND:
1501 case ISD::ATOMIC_LOAD_MIN:
1502 case ISD::ATOMIC_LOAD_MAX:
1503 case ISD::ATOMIC_LOAD_UMIN:
1504 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1505 if (DCI.isBeforeLegalize())
1508 MemSDNode *MemNode = cast<MemSDNode>(N);
1509 SDValue Ptr = MemNode->getBasePtr();
1511 // TODO: We could also do this for multiplies.
1512 unsigned AS = MemNode->getAddressSpace();
1513 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1514 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1516 SmallVector<SDValue, 8> NewOps;
1517 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1518 NewOps.push_back(MemNode->getOperand(I));
1520 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1521 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1527 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1530 /// \brief Test if RegClass is one of the VSrc classes
1531 static bool isVSrc(unsigned RegClass) {
1533 default: return false;
1534 case AMDGPU::VSrc_32RegClassID:
1535 case AMDGPU::VCSrc_32RegClassID:
1536 case AMDGPU::VSrc_64RegClassID:
1537 case AMDGPU::VCSrc_64RegClassID:
1542 /// \brief Test if RegClass is one of the SSrc classes
1543 static bool isSSrc(unsigned RegClass) {
1544 return AMDGPU::SSrc_32RegClassID == RegClass ||
1545 AMDGPU::SSrc_64RegClassID == RegClass;
1548 /// \brief Analyze the possible immediate value Op
1550 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1551 /// and the immediate value if it's a literal immediate
1552 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1559 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1560 if (Node->getZExtValue() >> 32) {
1563 Imm.I = Node->getSExtValue();
1564 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1565 if (N->getValueType(0) != MVT::f32)
1567 Imm.F = Node->getValueAPF().convertToFloat();
1569 return -1; // It isn't an immediate
1571 if ((Imm.I >= -16 && Imm.I <= 64) ||
1572 Imm.F == 0.5f || Imm.F == -0.5f ||
1573 Imm.F == 1.0f || Imm.F == -1.0f ||
1574 Imm.F == 2.0f || Imm.F == -2.0f ||
1575 Imm.F == 4.0f || Imm.F == -4.0f)
1576 return 0; // It's an inline immediate
1578 return Imm.I; // It's a literal immediate
1581 /// \brief Try to fold an immediate directly into an instruction
1582 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1583 bool &ScalarSlotUsed) const {
1585 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1586 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1587 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1588 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1591 const SDValue &Op = Mov->getOperand(0);
1592 int32_t Value = analyzeImmediate(Op.getNode());
1594 // Not an immediate at all
1597 } else if (Value == 0) {
1598 // Inline immediates can always be fold
1602 } else if (Value == Immediate) {
1603 // Already fold literal immediate
1607 } else if (!ScalarSlotUsed && !Immediate) {
1608 // Fold this literal immediate
1609 ScalarSlotUsed = true;
1619 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1620 SelectionDAG &DAG, const SDValue &Op) const {
1621 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1622 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1623 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1625 if (!Op->isMachineOpcode()) {
1626 switch(Op->getOpcode()) {
1627 case ISD::CopyFromReg: {
1628 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1629 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1630 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1631 return MRI.getRegClass(Reg);
1633 return TRI.getPhysRegClass(Reg);
1635 default: return nullptr;
1638 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1639 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1640 if (OpClassID != -1) {
1641 return TRI.getRegClass(OpClassID);
1643 switch(Op.getMachineOpcode()) {
1644 case AMDGPU::COPY_TO_REGCLASS:
1645 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1646 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1648 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1649 // class, then the register class for the value could be either a
1650 // VReg or and SReg. In order to get a more accurate
1651 if (isVSrc(OpClassID))
1652 return getRegClassForNode(DAG, Op.getOperand(0));
1654 return TRI.getRegClass(OpClassID);
1655 case AMDGPU::EXTRACT_SUBREG: {
1656 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1657 const TargetRegisterClass *SuperClass =
1658 getRegClassForNode(DAG, Op.getOperand(0));
1659 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1661 case AMDGPU::REG_SEQUENCE:
1662 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1663 return TRI.getRegClass(
1664 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1666 return getRegClassFor(Op.getSimpleValueType());
1670 /// \brief Does "Op" fit into register class "RegClass" ?
1671 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1672 unsigned RegClass) const {
1673 const TargetRegisterInfo *TRI =
1674 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1675 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1679 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1682 /// \returns true if \p Node's operands are different from the SDValue list
1684 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1685 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1686 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1693 /// TODO: This needs to be removed. It's current primary purpose is to fold
1694 /// immediates into operands when legal. The legalization parts are redundant
1695 /// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
1696 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1697 SelectionDAG &DAG) const {
1698 // Original encoding (either e32 or e64)
1699 int Opcode = Node->getMachineOpcode();
1700 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1701 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1702 const MCInstrDesc *Desc = &TII->get(Opcode);
1704 unsigned NumDefs = Desc->getNumDefs();
1705 unsigned NumOps = Desc->getNumOperands();
1707 // Commuted opcode if available
1708 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1709 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1711 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1712 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1714 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1715 bool HaveVSrc = false, HaveSSrc = false;
1717 // First figure out what we already have in this instruction.
1718 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1719 i != e && Op < NumOps; ++i, ++Op) {
1721 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1722 if (isVSrc(RegClass))
1724 else if (isSSrc(RegClass))
1729 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1730 if (Imm != -1 && Imm != 0) {
1731 // Literal immediate
1736 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1737 if (!HaveVSrc && !HaveSSrc)
1740 // No scalar allowed when we have both VSrc and SSrc
1741 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1743 // If this instruction has an implicit use of VCC, then it can't use the
1745 for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1746 if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1747 ScalarSlotUsed = true;
1752 // Second go over the operands and try to fold them
1753 std::vector<SDValue> Ops;
1754 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1755 i != e && Op < NumOps; ++i, ++Op) {
1757 const SDValue &Operand = Node->getOperand(i);
1758 Ops.push_back(Operand);
1760 // Already folded immediate?
1761 if (isa<ConstantSDNode>(Operand.getNode()) ||
1762 isa<ConstantFPSDNode>(Operand.getNode()))
1765 // Is this a VSrc or SSrc operand?
1766 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1767 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1768 // Try to fold the immediates. If this ends up with multiple constant bus
1769 // uses, it will be legalized later.
1770 foldImm(Ops[i], Immediate, ScalarSlotUsed);
1774 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1776 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1777 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1779 // Test if it makes sense to swap operands
1780 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1781 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1782 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1784 // Swap commutable operands
1785 std::swap(Ops[0], Ops[1]);
1794 // Add optional chain and glue
1795 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1796 Ops.push_back(Node->getOperand(i));
1798 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1799 // this case a brand new node is always be created, even if the operands
1800 // are the same as before. So, manually check if anything has been changed.
1801 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1805 // Create a complete new instruction
1806 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1809 /// \brief Helper function for adjustWritemask
1810 static unsigned SubIdx2Lane(unsigned Idx) {
1813 case AMDGPU::sub0: return 0;
1814 case AMDGPU::sub1: return 1;
1815 case AMDGPU::sub2: return 2;
1816 case AMDGPU::sub3: return 3;
1820 /// \brief Adjust the writemask of MIMG instructions
1821 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1822 SelectionDAG &DAG) const {
1823 SDNode *Users[4] = { };
1825 unsigned OldDmask = Node->getConstantOperandVal(0);
1826 unsigned NewDmask = 0;
1828 // Try to figure out the used register components
1829 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1832 // Abort if we can't understand the usage
1833 if (!I->isMachineOpcode() ||
1834 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1837 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1838 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1839 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1841 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1843 // Set which texture component corresponds to the lane.
1845 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1847 Comp = countTrailingZeros(Dmask);
1848 Dmask &= ~(1 << Comp);
1851 // Abort if we have more than one user per component
1856 NewDmask |= 1 << Comp;
1859 // Abort if there's no change
1860 if (NewDmask == OldDmask)
1863 // Adjust the writemask in the node
1864 std::vector<SDValue> Ops;
1865 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1866 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1867 Ops.push_back(Node->getOperand(i));
1868 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1870 // If we only got one lane, replace it with a copy
1871 // (if NewDmask has only one bit set...)
1872 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1873 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1874 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1875 SDLoc(), Users[Lane]->getValueType(0),
1876 SDValue(Node, 0), RC);
1877 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1881 // Update the users of the node with the new indices
1882 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1884 SDNode *User = Users[i];
1888 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1889 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1893 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1894 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1895 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1900 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1901 /// with frame index operands.
1902 /// LLVM assumes that inputs are to these instructions are registers.
1903 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1904 SelectionDAG &DAG) const {
1906 SmallVector<SDValue, 8> Ops;
1907 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1908 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1909 Ops.push_back(Node->getOperand(i));
1914 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1915 Node->getOperand(i).getValueType(),
1916 Node->getOperand(i)), 0));
1919 DAG.UpdateNodeOperands(Node, Ops);
1922 /// \brief Fold the instructions after selecting them.
1923 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1924 SelectionDAG &DAG) const {
1925 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1926 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1927 Node = AdjustRegClass(Node, DAG);
1929 if (TII->isMIMG(Node->getMachineOpcode()))
1930 adjustWritemask(Node, DAG);
1932 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG) {
1933 legalizeTargetIndependentNode(Node, DAG);
1937 return legalizeOperands(Node, DAG);
1940 /// \brief Assign the register class depending on the number of
1941 /// bits set in the writemask
1942 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1943 SDNode *Node) const {
1944 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1945 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1947 TII->legalizeOperands(MI);
1949 if (TII->isMIMG(MI->getOpcode())) {
1950 unsigned VReg = MI->getOperand(0).getReg();
1951 unsigned Writemask = MI->getOperand(1).getImm();
1952 unsigned BitsSet = 0;
1953 for (unsigned i = 0; i < 4; ++i)
1954 BitsSet += Writemask & (1 << i) ? 1 : 0;
1956 const TargetRegisterClass *RC;
1959 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1960 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1961 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1964 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1965 MI->setDesc(TII->get(NewOpcode));
1966 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1967 MRI.setRegClass(VReg, RC);
1971 // Replace unused atomics with the no return version.
1972 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1973 if (NoRetAtomicOp != -1) {
1974 if (!Node->hasAnyUseOfValue(0)) {
1975 MI->setDesc(TII->get(NoRetAtomicOp));
1976 MI->RemoveOperand(0);
1983 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1984 SelectionDAG &DAG) const {
1987 unsigned NewOpcode = N->getMachineOpcode();
1989 switch (N->getMachineOpcode()) {
1991 case AMDGPU::S_LOAD_DWORD_IMM:
1992 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1994 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1995 if (NewOpcode == N->getMachineOpcode()) {
1996 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1999 case AMDGPU::S_LOAD_DWORDX4_IMM:
2000 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2001 if (NewOpcode == N->getMachineOpcode()) {
2002 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2004 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2007 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2008 MachineSDNode *RSrc = DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL,
2010 DAG.getConstant(0, MVT::i64));
2012 SmallVector<SDValue, 8> Ops;
2013 Ops.push_back(SDValue(RSrc, 0));
2014 Ops.push_back(N->getOperand(0));
2015 Ops.push_back(DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32));
2017 // Copy remaining operands so we keep any chain and glue nodes that follow
2018 // the normal operands.
2019 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2020 Ops.push_back(N->getOperand(I));
2022 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2027 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2028 const TargetRegisterClass *RC,
2029 unsigned Reg, EVT VT) const {
2030 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2032 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2033 cast<RegisterSDNode>(VReg)->getReg(), VT);