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::FP_TO_SINT, MVT::i64, Expand);
172 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
174 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
175 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
176 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
178 // These should use UDIVREM, so set them to expand
179 setOperationAction(ISD::UDIV, MVT::i64, Expand);
180 setOperationAction(ISD::UREM, MVT::i64, Expand);
182 // We only support LOAD/STORE and vector manipulation ops for vectors
183 // with > 4 elements.
185 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
188 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
189 setOperationAction(ISD::SELECT, MVT::i1, Promote);
191 for (MVT VT : VecTypes) {
192 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
196 case ISD::BUILD_VECTOR:
198 case ISD::EXTRACT_VECTOR_ELT:
199 case ISD::INSERT_VECTOR_ELT:
200 case ISD::INSERT_SUBVECTOR:
201 case ISD::EXTRACT_SUBVECTOR:
203 case ISD::CONCAT_VECTORS:
204 setOperationAction(Op, VT, Custom);
207 setOperationAction(Op, VT, Expand);
213 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
214 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
215 setOperationAction(ISD::FTRUNC, VT, Expand);
216 setOperationAction(ISD::FCEIL, VT, Expand);
217 setOperationAction(ISD::FFLOOR, VT, Expand);
220 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
221 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
222 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
223 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
224 setOperationAction(ISD::FRINT, MVT::f64, Legal);
227 setOperationAction(ISD::FDIV, MVT::f32, Custom);
229 setTargetDAGCombine(ISD::FSUB);
230 setTargetDAGCombine(ISD::SELECT_CC);
231 setTargetDAGCombine(ISD::SETCC);
233 setTargetDAGCombine(ISD::UINT_TO_FP);
235 // All memory operations. Some folding on the pointer operand is done to help
236 // matching the constant offsets in the addressing modes.
237 setTargetDAGCombine(ISD::LOAD);
238 setTargetDAGCombine(ISD::STORE);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD);
240 setTargetDAGCombine(ISD::ATOMIC_STORE);
241 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
242 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
243 setTargetDAGCombine(ISD::ATOMIC_SWAP);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
245 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
246 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
247 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
248 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
252 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
253 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
255 setSchedulingPreference(Sched::RegPressure);
258 //===----------------------------------------------------------------------===//
259 // TargetLowering queries
260 //===----------------------------------------------------------------------===//
262 // FIXME: This really needs an address space argument. The immediate offset
263 // size is different for different sets of memory instruction sets.
265 // The single offset DS instructions have a 16-bit unsigned byte offset.
267 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
268 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
269 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
271 // SMRD instructions have an 8-bit, dword offset.
273 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
275 // No global is ever allowed as a base.
279 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
281 if (!isUInt<16>(AM.BaseOffs))
286 case 0: // "r+i" or just "i", depending on HasBaseReg.
289 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
291 // Otherwise we have r+r or r+i.
294 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
298 default: // Don't allow n * r
305 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
308 bool *IsFast) const {
312 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
313 // which isn't a simple VT.
314 if (!VT.isSimple() || VT == MVT::Other)
317 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
318 // see what for specifically. The wording everywhere else seems to be the
321 // XXX - The only mention I see of this in the ISA manual is for LDS direct
322 // reads the "byte address and must be dword aligned". Is it also true for the
323 // normal loads and stores?
324 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
325 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
326 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
327 // with adjacent offsets.
328 return Align % 4 == 0;
331 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
332 // byte-address are ignored, thus forcing Dword alignment.
333 // This applies to private, global, and constant memory.
336 return VT.bitsGT(MVT::i32);
339 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
340 unsigned SrcAlign, bool IsMemset,
343 MachineFunction &MF) const {
344 // FIXME: Should account for address space here.
346 // The default fallback uses the private pointer size as a guess for a type to
347 // use. Make sure we switch these to 64-bit accesses.
349 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
352 if (Size >= 8 && DstAlign >= 4)
359 TargetLoweringBase::LegalizeTypeAction
360 SITargetLowering::getPreferredVectorAction(EVT VT) const {
361 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
362 return TypeSplitVector;
364 return TargetLoweringBase::getPreferredVectorAction(VT);
367 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
369 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
370 getTargetMachine().getSubtargetImpl()->getInstrInfo());
371 return TII->isInlineConstant(Imm);
374 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
375 SDLoc SL, SDValue Chain,
376 unsigned Offset, bool Signed) const {
377 const DataLayout *DL = getDataLayout();
378 MachineFunction &MF = DAG.getMachineFunction();
379 const SIRegisterInfo *TRI =
380 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
381 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
383 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
385 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
386 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
387 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
388 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
389 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
390 DAG.getConstant(Offset, MVT::i64));
391 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
392 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
394 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
395 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
397 true, // isNonTemporal
399 DL->getABITypeAlignment(Ty)); // Alignment
402 SDValue SITargetLowering::LowerFormalArguments(
404 CallingConv::ID CallConv,
406 const SmallVectorImpl<ISD::InputArg> &Ins,
407 SDLoc DL, SelectionDAG &DAG,
408 SmallVectorImpl<SDValue> &InVals) const {
410 const TargetMachine &TM = getTargetMachine();
411 const SIRegisterInfo *TRI =
412 static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
414 MachineFunction &MF = DAG.getMachineFunction();
415 FunctionType *FType = MF.getFunction()->getFunctionType();
416 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
418 assert(CallConv == CallingConv::C);
420 SmallVector<ISD::InputArg, 16> Splits;
421 BitVector Skipped(Ins.size());
423 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
424 const ISD::InputArg &Arg = Ins[i];
426 // First check if it's a PS input addr
427 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
428 !Arg.Flags.isByVal()) {
430 assert((PSInputNum <= 15) && "Too many PS inputs!");
433 // We can savely skip PS inputs
439 Info->PSInputAddr |= 1 << PSInputNum++;
442 // Second split vertices into their elements
443 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
444 ISD::InputArg NewArg = Arg;
445 NewArg.Flags.setSplit();
446 NewArg.VT = Arg.VT.getVectorElementType();
448 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
449 // three or five element vertex only needs three or five registers,
450 // NOT four or eigth.
451 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
452 unsigned NumElements = ParamType->getVectorNumElements();
454 for (unsigned j = 0; j != NumElements; ++j) {
455 Splits.push_back(NewArg);
456 NewArg.PartOffset += NewArg.VT.getStoreSize();
459 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
460 Splits.push_back(Arg);
464 SmallVector<CCValAssign, 16> ArgLocs;
465 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
468 // At least one interpolation mode must be enabled or else the GPU will hang.
469 if (Info->getShaderType() == ShaderType::PIXEL &&
470 (Info->PSInputAddr & 0x7F) == 0) {
471 Info->PSInputAddr |= 1;
472 CCInfo.AllocateReg(AMDGPU::VGPR0);
473 CCInfo.AllocateReg(AMDGPU::VGPR1);
476 // The pointer to the list of arguments is stored in SGPR0, SGPR1
477 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
478 if (Info->getShaderType() == ShaderType::COMPUTE) {
479 Info->NumUserSGPRs = 4;
481 unsigned InputPtrReg =
482 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
483 unsigned InputPtrRegLo =
484 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
485 unsigned InputPtrRegHi =
486 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
488 unsigned ScratchPtrReg =
489 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
490 unsigned ScratchPtrRegLo =
491 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
492 unsigned ScratchPtrRegHi =
493 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
495 CCInfo.AllocateReg(InputPtrRegLo);
496 CCInfo.AllocateReg(InputPtrRegHi);
497 CCInfo.AllocateReg(ScratchPtrRegLo);
498 CCInfo.AllocateReg(ScratchPtrRegHi);
499 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
500 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
503 if (Info->getShaderType() == ShaderType::COMPUTE) {
504 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
508 AnalyzeFormalArguments(CCInfo, Splits);
510 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
512 const ISD::InputArg &Arg = Ins[i];
514 InVals.push_back(DAG.getUNDEF(Arg.VT));
518 CCValAssign &VA = ArgLocs[ArgIdx++];
519 EVT VT = VA.getLocVT();
523 EVT MemVT = Splits[i].VT;
524 // The first 36 bytes of the input buffer contains information about
525 // thread group and global sizes.
526 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
527 36 + VA.getLocMemOffset(),
528 Ins[i].Flags.isSExt());
530 const PointerType *ParamTy =
531 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
532 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
533 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
534 // On SI local pointers are just offsets into LDS, so they are always
535 // less than 16-bits. On CI and newer they could potentially be
536 // real pointers, so we can't guarantee their size.
537 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
538 DAG.getValueType(MVT::i16));
541 InVals.push_back(Arg);
544 assert(VA.isRegLoc() && "Parameter must be in a register!");
546 unsigned Reg = VA.getLocReg();
548 if (VT == MVT::i64) {
549 // For now assume it is a pointer
550 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
551 &AMDGPU::SReg_64RegClass);
552 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
553 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
557 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
559 Reg = MF.addLiveIn(Reg, RC);
560 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
562 if (Arg.VT.isVector()) {
564 // Build a vector from the registers
565 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
566 unsigned NumElements = ParamType->getVectorNumElements();
568 SmallVector<SDValue, 4> Regs;
570 for (unsigned j = 1; j != NumElements; ++j) {
571 Reg = ArgLocs[ArgIdx++].getLocReg();
572 Reg = MF.addLiveIn(Reg, RC);
573 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
576 // Fill up the missing vector elements
577 NumElements = Arg.VT.getVectorNumElements() - NumElements;
578 for (unsigned j = 0; j != NumElements; ++j)
579 Regs.push_back(DAG.getUNDEF(VT));
581 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
585 InVals.push_back(Val);
590 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
591 MachineInstr * MI, MachineBasicBlock * BB) const {
593 MachineBasicBlock::iterator I = *MI;
594 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
595 getTargetMachine().getSubtargetImpl()->getInstrInfo());
596 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
598 switch (MI->getOpcode()) {
600 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
601 case AMDGPU::BRANCH: return BB;
602 case AMDGPU::SI_ADDR64_RSRC: {
603 unsigned SuperReg = MI->getOperand(0).getReg();
604 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
605 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
606 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
607 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
608 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
609 .addOperand(MI->getOperand(1));
610 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
612 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
613 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
614 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
616 .addImm(AMDGPU::sub0)
618 .addImm(AMDGPU::sub1);
619 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
621 .addImm(AMDGPU::sub0_sub1)
623 .addImm(AMDGPU::sub2_sub3);
624 MI->eraseFromParent();
627 case AMDGPU::SI_BUFFER_RSRC: {
628 unsigned SuperReg = MI->getOperand(0).getReg();
630 for (unsigned i = 0, e = 4; i < e; ++i) {
631 MachineOperand &Arg = MI->getOperand(i + 1);
634 Args[i] = Arg.getReg();
639 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
640 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), Reg)
641 .addImm(Arg.getImm());
644 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE),
647 .addImm(AMDGPU::sub0)
649 .addImm(AMDGPU::sub1)
651 .addImm(AMDGPU::sub2)
653 .addImm(AMDGPU::sub3);
654 MI->eraseFromParent();
657 case AMDGPU::V_SUB_F64: {
658 unsigned DestReg = MI->getOperand(0).getReg();
659 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
660 .addImm(0) // SRC0 modifiers
661 .addReg(MI->getOperand(1).getReg())
662 .addImm(1) // SRC1 modifiers
663 .addReg(MI->getOperand(2).getReg())
666 MI->eraseFromParent();
669 case AMDGPU::SI_RegisterStorePseudo: {
670 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
671 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
672 MachineInstrBuilder MIB =
673 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
675 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
676 MIB.addOperand(MI->getOperand(i));
678 MI->eraseFromParent();
681 case AMDGPU::FCLAMP_SI: {
682 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
683 getTargetMachine().getSubtargetImpl()->getInstrInfo());
684 DebugLoc DL = MI->getDebugLoc();
685 unsigned DestReg = MI->getOperand(0).getReg();
686 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
687 .addImm(0) // SRC0 modifiers
688 .addOperand(MI->getOperand(1))
689 .addImm(0) // SRC1 modifiers
693 MI->eraseFromParent();
699 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
700 if (!VT.isVector()) {
703 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
706 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
710 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
711 VT = VT.getScalarType();
716 switch (VT.getSimpleVT().SimpleTy) {
718 return false; /* There is V_MAD_F32 for f32 */
728 //===----------------------------------------------------------------------===//
729 // Custom DAG Lowering Operations
730 //===----------------------------------------------------------------------===//
732 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
733 switch (Op.getOpcode()) {
734 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
735 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
736 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
738 SDValue Result = LowerLOAD(Op, DAG);
739 assert((!Result.getNode() ||
740 Result.getNode()->getNumValues() == 2) &&
741 "Load should return a value and a chain");
747 return LowerTrig(Op, DAG);
748 case ISD::SELECT: return LowerSELECT(Op, DAG);
749 case ISD::FDIV: return LowerFDIV(Op, DAG);
750 case ISD::STORE: return LowerSTORE(Op, DAG);
751 case ISD::GlobalAddress: {
752 MachineFunction &MF = DAG.getMachineFunction();
753 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
754 return LowerGlobalAddress(MFI, Op, DAG);
756 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
757 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
762 /// \brief Helper function for LowerBRCOND
763 static SDNode *findUser(SDValue Value, unsigned Opcode) {
765 SDNode *Parent = Value.getNode();
766 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
769 if (I.getUse().get() != Value)
772 if (I->getOpcode() == Opcode)
778 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
780 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
781 unsigned FrameIndex = FINode->getIndex();
783 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
786 /// This transforms the control flow intrinsics to get the branch destination as
787 /// last parameter, also switches branch target with BR if the need arise
788 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
789 SelectionDAG &DAG) const {
793 SDNode *Intr = BRCOND.getOperand(1).getNode();
794 SDValue Target = BRCOND.getOperand(2);
795 SDNode *BR = nullptr;
797 if (Intr->getOpcode() == ISD::SETCC) {
798 // As long as we negate the condition everything is fine
799 SDNode *SetCC = Intr;
800 assert(SetCC->getConstantOperandVal(1) == 1);
801 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
803 Intr = SetCC->getOperand(0).getNode();
806 // Get the target from BR if we don't negate the condition
807 BR = findUser(BRCOND, ISD::BR);
808 Target = BR->getOperand(1);
811 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
813 // Build the result and
814 SmallVector<EVT, 4> Res;
815 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
816 Res.push_back(Intr->getValueType(i));
818 // operands of the new intrinsic call
819 SmallVector<SDValue, 4> Ops;
820 Ops.push_back(BRCOND.getOperand(0));
821 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
822 Ops.push_back(Intr->getOperand(i));
823 Ops.push_back(Target);
825 // build the new intrinsic call
826 SDNode *Result = DAG.getNode(
827 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
828 DAG.getVTList(Res), Ops).getNode();
831 // Give the branch instruction our target
836 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
837 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
838 BR = NewBR.getNode();
841 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
843 // Copy the intrinsic results to registers
844 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
845 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
849 Chain = DAG.getCopyToReg(
851 CopyToReg->getOperand(1),
852 SDValue(Result, i - 1),
855 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
858 // Remove the old intrinsic from the chain
859 DAG.ReplaceAllUsesOfValueWith(
860 SDValue(Intr, Intr->getNumValues() - 1),
861 Intr->getOperand(0));
866 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
868 SelectionDAG &DAG) const {
869 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
871 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
872 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
875 const GlobalValue *GV = GSD->getGlobal();
876 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
878 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
879 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
881 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
882 DAG.getConstant(0, MVT::i32));
883 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
884 DAG.getConstant(1, MVT::i32));
886 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
888 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
889 PtrHi, DAG.getConstant(0, MVT::i32),
890 SDValue(Lo.getNode(), 1));
891 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
894 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
895 SelectionDAG &DAG) const {
896 MachineFunction &MF = DAG.getMachineFunction();
897 const SIRegisterInfo *TRI =
898 static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
900 EVT VT = Op.getValueType();
902 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
904 switch (IntrinsicID) {
905 case Intrinsic::r600_read_ngroups_x:
906 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
907 SI::KernelInputOffsets::NGROUPS_X, false);
908 case Intrinsic::r600_read_ngroups_y:
909 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
910 SI::KernelInputOffsets::NGROUPS_Y, false);
911 case Intrinsic::r600_read_ngroups_z:
912 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
913 SI::KernelInputOffsets::NGROUPS_Z, false);
914 case Intrinsic::r600_read_global_size_x:
915 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
916 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
917 case Intrinsic::r600_read_global_size_y:
918 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
919 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
920 case Intrinsic::r600_read_global_size_z:
921 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
922 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
923 case Intrinsic::r600_read_local_size_x:
924 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
925 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
926 case Intrinsic::r600_read_local_size_y:
927 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
928 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
929 case Intrinsic::r600_read_local_size_z:
930 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
931 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
932 case Intrinsic::r600_read_tgid_x:
933 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
934 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
935 case Intrinsic::r600_read_tgid_y:
936 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
937 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
938 case Intrinsic::r600_read_tgid_z:
939 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
940 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
941 case Intrinsic::r600_read_tidig_x:
942 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
943 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
944 case Intrinsic::r600_read_tidig_y:
945 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
946 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
947 case Intrinsic::r600_read_tidig_z:
948 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
949 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
950 case AMDGPUIntrinsic::SI_load_const: {
956 MachineMemOperand *MMO = MF.getMachineMemOperand(
957 MachinePointerInfo(),
958 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
959 VT.getStoreSize(), 4);
960 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
961 Op->getVTList(), Ops, VT, MMO);
963 case AMDGPUIntrinsic::SI_sample:
964 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
965 case AMDGPUIntrinsic::SI_sampleb:
966 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
967 case AMDGPUIntrinsic::SI_sampled:
968 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
969 case AMDGPUIntrinsic::SI_samplel:
970 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
971 case AMDGPUIntrinsic::SI_vs_load_input:
972 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
977 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
981 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
982 SelectionDAG &DAG) const {
983 MachineFunction &MF = DAG.getMachineFunction();
984 SDValue Chain = Op.getOperand(0);
985 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
987 switch (IntrinsicID) {
988 case AMDGPUIntrinsic::SI_tbuffer_store: {
1007 EVT VT = Op.getOperand(3).getValueType();
1009 MachineMemOperand *MMO = MF.getMachineMemOperand(
1010 MachinePointerInfo(),
1011 MachineMemOperand::MOStore,
1012 VT.getStoreSize(), 4);
1013 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1014 Op->getVTList(), Ops, VT, MMO);
1021 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1023 LoadSDNode *Load = cast<LoadSDNode>(Op);
1025 if (Op.getValueType().isVector()) {
1026 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1027 "Custom lowering for non-i32 vectors hasn't been implemented.");
1028 unsigned NumElements = Op.getValueType().getVectorNumElements();
1029 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1030 switch (Load->getAddressSpace()) {
1032 case AMDGPUAS::GLOBAL_ADDRESS:
1033 case AMDGPUAS::PRIVATE_ADDRESS:
1034 // v4 loads are supported for private and global memory.
1035 if (NumElements <= 4)
1038 case AMDGPUAS::LOCAL_ADDRESS:
1039 return ScalarizeVectorLoad(Op, DAG);
1043 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1046 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1048 SelectionDAG &DAG) const {
1049 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1055 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1056 if (Op.getValueType() != MVT::i64)
1060 SDValue Cond = Op.getOperand(0);
1062 SDValue Zero = DAG.getConstant(0, MVT::i32);
1063 SDValue One = DAG.getConstant(1, MVT::i32);
1065 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1066 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1068 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1069 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1071 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1073 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1074 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1076 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1078 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1079 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1082 // Catch division cases where we can use shortcuts with rcp and rsq
1084 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1086 SDValue LHS = Op.getOperand(0);
1087 SDValue RHS = Op.getOperand(1);
1088 EVT VT = Op.getValueType();
1089 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1091 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1092 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1093 CLHS->isExactlyValue(1.0)) {
1094 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1095 // the CI documentation has a worst case error of 1 ulp.
1096 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1097 // use it as long as we aren't trying to use denormals.
1099 // 1.0 / sqrt(x) -> rsq(x)
1101 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1102 // error seems really high at 2^29 ULP.
1103 if (RHS.getOpcode() == ISD::FSQRT)
1104 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1106 // 1.0 / x -> rcp(x)
1107 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1112 // Turn into multiply by the reciprocal.
1113 // x / y -> x * (1.0 / y)
1114 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1115 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1121 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1122 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1123 if (FastLowered.getNode())
1126 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1127 // selection error for now rather than do something incorrect.
1128 if (Subtarget->hasFP32Denormals())
1132 SDValue LHS = Op.getOperand(0);
1133 SDValue RHS = Op.getOperand(1);
1135 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1137 const APFloat K0Val(BitsToFloat(0x6f800000));
1138 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1140 const APFloat K1Val(BitsToFloat(0x2f800000));
1141 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1143 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1145 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1147 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1149 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1151 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1153 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1155 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1157 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1160 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1164 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1165 EVT VT = Op.getValueType();
1168 return LowerFDIV32(Op, DAG);
1171 return LowerFDIV64(Op, DAG);
1173 llvm_unreachable("Unexpected type for fdiv");
1176 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1178 StoreSDNode *Store = cast<StoreSDNode>(Op);
1179 EVT VT = Store->getMemoryVT();
1181 // These stores are legal.
1182 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1183 VT.isVector() && VT.getVectorNumElements() == 2 &&
1184 VT.getVectorElementType() == MVT::i32)
1187 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1188 if (VT.isVector() && VT.getVectorNumElements() > 4)
1189 return ScalarizeVectorStore(Op, DAG);
1193 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1197 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1198 return ScalarizeVectorStore(Op, DAG);
1201 return DAG.getTruncStore(Store->getChain(), DL,
1202 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1203 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1208 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1209 EVT VT = Op.getValueType();
1210 SDValue Arg = Op.getOperand(0);
1211 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1212 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1213 DAG.getConstantFP(0.5 / M_PI, VT)));
1215 switch (Op.getOpcode()) {
1217 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1219 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1221 llvm_unreachable("Wrong trig opcode");
1225 //===----------------------------------------------------------------------===//
1226 // Custom DAG optimizations
1227 //===----------------------------------------------------------------------===//
1229 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1230 DAGCombinerInfo &DCI) {
1231 EVT VT = N->getValueType(0);
1232 EVT ScalarVT = VT.getScalarType();
1233 if (ScalarVT != MVT::f32)
1236 SelectionDAG &DAG = DCI.DAG;
1239 SDValue Src = N->getOperand(0);
1240 EVT SrcVT = Src.getValueType();
1242 // TODO: We could try to match extracting the higher bytes, which would be
1243 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1244 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1245 // about in practice.
1246 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1247 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1248 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1249 DCI.AddToWorklist(Cvt.getNode());
1254 // We are primarily trying to catch operations on illegal vector types
1255 // before they are expanded.
1256 // For scalars, we can use the more flexible method of checking masked bits
1257 // after legalization.
1258 if (!DCI.isBeforeLegalize() ||
1259 !SrcVT.isVector() ||
1260 SrcVT.getVectorElementType() != MVT::i8) {
1264 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1266 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1268 unsigned NElts = SrcVT.getVectorNumElements();
1269 if (!SrcVT.isSimple() && NElts != 3)
1272 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1273 // prevent a mess from expanding to v4i32 and repacking.
1274 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1275 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1276 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1277 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1279 LoadSDNode *Load = cast<LoadSDNode>(Src);
1280 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1284 Load->getMemOperand());
1286 // Make sure successors of the original load stay after it by updating
1287 // them to use the new Chain.
1288 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1290 SmallVector<SDValue, 4> Elts;
1291 if (RegVT.isVector())
1292 DAG.ExtractVectorElements(NewLoad, Elts);
1294 Elts.push_back(NewLoad);
1296 SmallVector<SDValue, 4> Ops;
1298 unsigned EltIdx = 0;
1299 for (SDValue Elt : Elts) {
1300 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1301 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1302 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1303 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1304 DCI.AddToWorklist(Cvt.getNode());
1311 assert(Ops.size() == NElts);
1313 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1319 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1321 // This is a variant of
1322 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1324 // The normal DAG combiner will do this, but only if the add has one use since
1325 // that would increase the number of instructions.
1327 // This prevents us from seeing a constant offset that can be folded into a
1328 // memory instruction's addressing mode. If we know the resulting add offset of
1329 // a pointer can be folded into an addressing offset, we can replace the pointer
1330 // operand with the add of new constant offset. This eliminates one of the uses,
1331 // and may allow the remaining use to also be simplified.
1333 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1335 DAGCombinerInfo &DCI) const {
1336 SDValue N0 = N->getOperand(0);
1337 SDValue N1 = N->getOperand(1);
1339 if (N0.getOpcode() != ISD::ADD)
1342 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1346 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1350 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1351 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1353 // If the resulting offset is too large, we can't fold it into the addressing
1355 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1356 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1359 SelectionDAG &DAG = DCI.DAG;
1361 EVT VT = N->getValueType(0);
1363 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1364 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1366 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1369 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1370 DAGCombinerInfo &DCI) const {
1371 SelectionDAG &DAG = DCI.DAG;
1373 EVT VT = N->getValueType(0);
1375 switch (N->getOpcode()) {
1376 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1378 SDValue Arg0 = N->getOperand(0);
1379 SDValue Arg1 = N->getOperand(1);
1380 SDValue CC = N->getOperand(2);
1381 ConstantSDNode * C = nullptr;
1382 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1384 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1386 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1387 && Arg0.getOperand(0).getValueType() == MVT::i1
1388 && (C = dyn_cast<ConstantSDNode>(Arg1))
1390 && CCOp == ISD::SETNE) {
1391 return SimplifySetCC(VT, Arg0.getOperand(0),
1392 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1397 case AMDGPUISD::CVT_F32_UBYTE0:
1398 case AMDGPUISD::CVT_F32_UBYTE1:
1399 case AMDGPUISD::CVT_F32_UBYTE2:
1400 case AMDGPUISD::CVT_F32_UBYTE3: {
1401 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1403 SDValue Src = N->getOperand(0);
1404 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1406 APInt KnownZero, KnownOne;
1407 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1408 !DCI.isBeforeLegalizeOps());
1409 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1410 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1411 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1412 DCI.CommitTargetLoweringOpt(TLO);
1418 case ISD::UINT_TO_FP: {
1419 return performUCharToFloatCombine(N, DCI);
1422 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1425 EVT VT = N->getValueType(0);
1427 // Try to get the fneg to fold into the source modifier. This undoes generic
1428 // DAG combines and folds them into the mad.
1429 if (VT == MVT::f32) {
1430 SDValue LHS = N->getOperand(0);
1431 SDValue RHS = N->getOperand(1);
1433 if (LHS.getOpcode() == ISD::FMUL) {
1434 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1436 SDValue A = LHS.getOperand(0);
1437 SDValue B = LHS.getOperand(1);
1438 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1440 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1443 if (RHS.getOpcode() == ISD::FMUL) {
1444 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1446 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1447 SDValue B = RHS.getOperand(1);
1450 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1459 case ISD::ATOMIC_LOAD:
1460 case ISD::ATOMIC_STORE:
1461 case ISD::ATOMIC_CMP_SWAP:
1462 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1463 case ISD::ATOMIC_SWAP:
1464 case ISD::ATOMIC_LOAD_ADD:
1465 case ISD::ATOMIC_LOAD_SUB:
1466 case ISD::ATOMIC_LOAD_AND:
1467 case ISD::ATOMIC_LOAD_OR:
1468 case ISD::ATOMIC_LOAD_XOR:
1469 case ISD::ATOMIC_LOAD_NAND:
1470 case ISD::ATOMIC_LOAD_MIN:
1471 case ISD::ATOMIC_LOAD_MAX:
1472 case ISD::ATOMIC_LOAD_UMIN:
1473 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1474 if (DCI.isBeforeLegalize())
1477 MemSDNode *MemNode = cast<MemSDNode>(N);
1478 SDValue Ptr = MemNode->getBasePtr();
1480 // TODO: We could also do this for multiplies.
1481 unsigned AS = MemNode->getAddressSpace();
1482 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1483 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1485 SmallVector<SDValue, 8> NewOps;
1486 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1487 NewOps.push_back(MemNode->getOperand(I));
1489 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1490 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1496 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1499 /// \brief Test if RegClass is one of the VSrc classes
1500 static bool isVSrc(unsigned RegClass) {
1502 default: return false;
1503 case AMDGPU::VSrc_32RegClassID:
1504 case AMDGPU::VCSrc_32RegClassID:
1505 case AMDGPU::VSrc_64RegClassID:
1506 case AMDGPU::VCSrc_64RegClassID:
1511 /// \brief Test if RegClass is one of the SSrc classes
1512 static bool isSSrc(unsigned RegClass) {
1513 return AMDGPU::SSrc_32RegClassID == RegClass ||
1514 AMDGPU::SSrc_64RegClassID == RegClass;
1517 /// \brief Analyze the possible immediate value Op
1519 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1520 /// and the immediate value if it's a literal immediate
1521 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1528 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1529 if (Node->getZExtValue() >> 32) {
1532 Imm.I = Node->getSExtValue();
1533 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1534 if (N->getValueType(0) != MVT::f32)
1536 Imm.F = Node->getValueAPF().convertToFloat();
1538 return -1; // It isn't an immediate
1540 if ((Imm.I >= -16 && Imm.I <= 64) ||
1541 Imm.F == 0.5f || Imm.F == -0.5f ||
1542 Imm.F == 1.0f || Imm.F == -1.0f ||
1543 Imm.F == 2.0f || Imm.F == -2.0f ||
1544 Imm.F == 4.0f || Imm.F == -4.0f)
1545 return 0; // It's an inline immediate
1547 return Imm.I; // It's a literal immediate
1550 /// \brief Try to fold an immediate directly into an instruction
1551 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1552 bool &ScalarSlotUsed) const {
1554 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1555 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1556 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1557 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1560 const SDValue &Op = Mov->getOperand(0);
1561 int32_t Value = analyzeImmediate(Op.getNode());
1563 // Not an immediate at all
1566 } else if (Value == 0) {
1567 // Inline immediates can always be fold
1571 } else if (Value == Immediate) {
1572 // Already fold literal immediate
1576 } else if (!ScalarSlotUsed && !Immediate) {
1577 // Fold this literal immediate
1578 ScalarSlotUsed = true;
1588 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1589 SelectionDAG &DAG, const SDValue &Op) const {
1590 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1591 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1592 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1594 if (!Op->isMachineOpcode()) {
1595 switch(Op->getOpcode()) {
1596 case ISD::CopyFromReg: {
1597 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1598 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1599 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1600 return MRI.getRegClass(Reg);
1602 return TRI.getPhysRegClass(Reg);
1604 default: return nullptr;
1607 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1608 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1609 if (OpClassID != -1) {
1610 return TRI.getRegClass(OpClassID);
1612 switch(Op.getMachineOpcode()) {
1613 case AMDGPU::COPY_TO_REGCLASS:
1614 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1615 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1617 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1618 // class, then the register class for the value could be either a
1619 // VReg or and SReg. In order to get a more accurate
1620 if (isVSrc(OpClassID))
1621 return getRegClassForNode(DAG, Op.getOperand(0));
1623 return TRI.getRegClass(OpClassID);
1624 case AMDGPU::EXTRACT_SUBREG: {
1625 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1626 const TargetRegisterClass *SuperClass =
1627 getRegClassForNode(DAG, Op.getOperand(0));
1628 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1630 case AMDGPU::REG_SEQUENCE:
1631 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1632 return TRI.getRegClass(
1633 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1635 return getRegClassFor(Op.getSimpleValueType());
1639 /// \brief Does "Op" fit into register class "RegClass" ?
1640 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1641 unsigned RegClass) const {
1642 const TargetRegisterInfo *TRI =
1643 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1644 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1648 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1651 /// \brief Make sure that we don't exeed the number of allowed scalars
1652 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1654 bool &ScalarSlotUsed) const {
1656 if (!isVSrc(RegClass))
1659 // First map the operands register class to a destination class
1661 case AMDGPU::VSrc_32RegClassID:
1662 case AMDGPU::VCSrc_32RegClassID:
1663 RegClass = AMDGPU::VReg_32RegClassID;
1665 case AMDGPU::VSrc_64RegClassID:
1666 case AMDGPU::VCSrc_64RegClassID:
1667 RegClass = AMDGPU::VReg_64RegClassID;
1670 llvm_unreachable("Unknown vsrc reg class");
1673 // Nothing to do if they fit naturally
1674 if (fitsRegClass(DAG, Operand, RegClass))
1677 // If the scalar slot isn't used yet use it now
1678 if (!ScalarSlotUsed) {
1679 ScalarSlotUsed = true;
1683 // This is a conservative aproach. It is possible that we can't determine the
1684 // correct register class and copy too often, but better safe than sorry.
1687 // We can't use COPY_TO_REGCLASS with FrameIndex arguments.
1688 if (isa<FrameIndexSDNode>(Operand) ||
1689 isa<GlobalAddressSDNode>(Operand)) {
1690 unsigned Opcode = Operand.getValueType() == MVT::i32 ?
1691 AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
1692 Node = DAG.getMachineNode(Opcode, SDLoc(), Operand.getValueType(),
1695 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1696 Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1697 Operand.getValueType(), Operand, RC);
1699 Operand = SDValue(Node, 0);
1702 /// \returns true if \p Node's operands are different from the SDValue list
1704 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1705 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1706 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1713 /// \brief Try to commute instructions and insert copies in order to satisfy the
1714 /// operand constraints.
1715 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1716 SelectionDAG &DAG) const {
1717 // Original encoding (either e32 or e64)
1718 int Opcode = Node->getMachineOpcode();
1719 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1720 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1721 const MCInstrDesc *Desc = &TII->get(Opcode);
1723 unsigned NumDefs = Desc->getNumDefs();
1724 unsigned NumOps = Desc->getNumOperands();
1726 // Commuted opcode if available
1727 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1728 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1730 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1731 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1733 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1734 bool HaveVSrc = false, HaveSSrc = false;
1736 // First figure out what we already have in this instruction.
1737 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1738 i != e && Op < NumOps; ++i, ++Op) {
1740 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1741 if (isVSrc(RegClass))
1743 else if (isSSrc(RegClass))
1748 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1749 if (Imm != -1 && Imm != 0) {
1750 // Literal immediate
1755 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1756 if (!HaveVSrc && !HaveSSrc)
1759 // No scalar allowed when we have both VSrc and SSrc
1760 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1762 // If this instruction has an implicit use of VCC, then it can't use the
1764 for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1765 if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1766 ScalarSlotUsed = true;
1771 // Second go over the operands and try to fold them
1772 std::vector<SDValue> Ops;
1773 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1774 i != e && Op < NumOps; ++i, ++Op) {
1776 const SDValue &Operand = Node->getOperand(i);
1777 Ops.push_back(Operand);
1779 // Already folded immediate?
1780 if (isa<ConstantSDNode>(Operand.getNode()) ||
1781 isa<ConstantFPSDNode>(Operand.getNode()))
1784 // Is this a VSrc or SSrc operand?
1785 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1786 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1787 // Try to fold the immediates
1788 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1789 // Folding didn't work, make sure we don't hit the SReg limit.
1790 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1794 // If it's not a VSrc or SSrc operand check if we have a GlobalAddress.
1795 // These will be lowered to immediates, so we will need to insert a MOV.
1796 if (isa<GlobalAddressSDNode>(Ops[i])) {
1797 SDNode *Node = DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, SDLoc(),
1798 Operand.getValueType(), Operand);
1799 Ops[i] = SDValue(Node, 0);
1803 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1805 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1806 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1808 // Test if it makes sense to swap operands
1809 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1810 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1811 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1813 // Swap commutable operands
1814 std::swap(Ops[0], Ops[1]);
1823 // Add optional chain and glue
1824 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1825 Ops.push_back(Node->getOperand(i));
1827 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1828 // this case a brand new node is always be created, even if the operands
1829 // are the same as before. So, manually check if anything has been changed.
1830 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1834 // Create a complete new instruction
1835 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1838 /// \brief Helper function for adjustWritemask
1839 static unsigned SubIdx2Lane(unsigned Idx) {
1842 case AMDGPU::sub0: return 0;
1843 case AMDGPU::sub1: return 1;
1844 case AMDGPU::sub2: return 2;
1845 case AMDGPU::sub3: return 3;
1849 /// \brief Adjust the writemask of MIMG instructions
1850 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1851 SelectionDAG &DAG) const {
1852 SDNode *Users[4] = { };
1854 unsigned OldDmask = Node->getConstantOperandVal(0);
1855 unsigned NewDmask = 0;
1857 // Try to figure out the used register components
1858 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1861 // Abort if we can't understand the usage
1862 if (!I->isMachineOpcode() ||
1863 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1866 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1867 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1868 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1870 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1872 // Set which texture component corresponds to the lane.
1874 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1876 Comp = countTrailingZeros(Dmask);
1877 Dmask &= ~(1 << Comp);
1880 // Abort if we have more than one user per component
1885 NewDmask |= 1 << Comp;
1888 // Abort if there's no change
1889 if (NewDmask == OldDmask)
1892 // Adjust the writemask in the node
1893 std::vector<SDValue> Ops;
1894 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1895 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1896 Ops.push_back(Node->getOperand(i));
1897 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1899 // If we only got one lane, replace it with a copy
1900 // (if NewDmask has only one bit set...)
1901 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1902 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1903 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1904 SDLoc(), Users[Lane]->getValueType(0),
1905 SDValue(Node, 0), RC);
1906 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1910 // Update the users of the node with the new indices
1911 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1913 SDNode *User = Users[i];
1917 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1918 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1922 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1923 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1924 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1929 /// \brief Fold the instructions after selecting them.
1930 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1931 SelectionDAG &DAG) const {
1932 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1933 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1934 Node = AdjustRegClass(Node, DAG);
1936 if (TII->isMIMG(Node->getMachineOpcode()))
1937 adjustWritemask(Node, DAG);
1939 return legalizeOperands(Node, DAG);
1942 /// \brief Assign the register class depending on the number of
1943 /// bits set in the writemask
1944 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1945 SDNode *Node) const {
1946 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1947 getTargetMachine().getSubtargetImpl()->getInstrInfo());
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);