1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Custom DAG lowering for SI
13 //===----------------------------------------------------------------------===//
17 #define _USE_MATH_DEFINES
21 #include "SIISelLowering.h"
23 #include "AMDGPUIntrinsicInfo.h"
24 #include "AMDGPUSubtarget.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/ADT/SmallString.h"
38 SITargetLowering::SITargetLowering(TargetMachine &TM) :
39 AMDGPUTargetLowering(TM) {
40 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
41 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
43 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
44 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
46 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
47 addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
49 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
50 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
51 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
53 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
54 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
56 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
57 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
59 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
60 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
62 computeRegisterProperties();
65 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
66 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
67 setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
68 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
69 setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
70 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
72 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
73 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
74 setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
75 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
76 setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
77 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
79 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
80 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
81 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
82 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
84 setOperationAction(ISD::ADD, MVT::i32, Legal);
85 setOperationAction(ISD::ADDC, MVT::i32, Legal);
86 setOperationAction(ISD::ADDE, MVT::i32, Legal);
87 setOperationAction(ISD::SUBC, MVT::i32, Legal);
88 setOperationAction(ISD::SUBE, MVT::i32, Legal);
90 setOperationAction(ISD::FSIN, MVT::f32, Custom);
91 setOperationAction(ISD::FCOS, MVT::f32, Custom);
93 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
94 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
95 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
96 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
98 // We need to custom lower vector stores from local memory
99 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
100 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
101 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
103 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
104 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
106 setOperationAction(ISD::STORE, MVT::i1, Custom);
107 setOperationAction(ISD::STORE, MVT::i32, Custom);
108 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
109 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
111 setOperationAction(ISD::SELECT, MVT::f32, Promote);
112 AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
113 setOperationAction(ISD::SELECT, MVT::i64, Custom);
114 setOperationAction(ISD::SELECT, MVT::f64, Promote);
115 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
117 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
118 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
119 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
120 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
122 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
123 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
125 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
131 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
132 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
133 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
135 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
136 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
137 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
139 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
141 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
143 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
144 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
145 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
146 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
148 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
149 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
151 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
152 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
153 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
154 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
155 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
156 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
158 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
159 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
160 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
161 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
163 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
164 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
165 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
166 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
167 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
169 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
170 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
171 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
172 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
173 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
174 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
176 setOperationAction(ISD::LOAD, MVT::i1, Custom);
178 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
179 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
180 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
182 // These should use UDIVREM, so set them to expand
183 setOperationAction(ISD::UDIV, MVT::i64, Expand);
184 setOperationAction(ISD::UREM, MVT::i64, Expand);
186 // We only support LOAD/STORE and vector manipulation ops for vectors
187 // with > 4 elements.
189 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
192 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
193 setOperationAction(ISD::SELECT, MVT::i1, Promote);
195 for (MVT VT : VecTypes) {
196 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
200 case ISD::BUILD_VECTOR:
202 case ISD::EXTRACT_VECTOR_ELT:
203 case ISD::INSERT_VECTOR_ELT:
204 case ISD::INSERT_SUBVECTOR:
205 case ISD::EXTRACT_SUBVECTOR:
207 case ISD::CONCAT_VECTORS:
208 setOperationAction(Op, VT, Custom);
211 setOperationAction(Op, VT, Expand);
217 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
218 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
219 setOperationAction(ISD::FTRUNC, VT, Expand);
220 setOperationAction(ISD::FCEIL, VT, Expand);
221 setOperationAction(ISD::FFLOOR, VT, Expand);
224 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
225 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
226 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
227 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
228 setOperationAction(ISD::FRINT, MVT::f64, Legal);
231 setOperationAction(ISD::FDIV, MVT::f32, Custom);
233 setTargetDAGCombine(ISD::FADD);
234 setTargetDAGCombine(ISD::FSUB);
235 setTargetDAGCombine(ISD::SELECT_CC);
236 setTargetDAGCombine(ISD::SETCC);
238 setTargetDAGCombine(ISD::UINT_TO_FP);
240 // All memory operations. Some folding on the pointer operand is done to help
241 // matching the constant offsets in the addressing modes.
242 setTargetDAGCombine(ISD::LOAD);
243 setTargetDAGCombine(ISD::STORE);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD);
245 setTargetDAGCombine(ISD::ATOMIC_STORE);
246 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
247 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
248 setTargetDAGCombine(ISD::ATOMIC_SWAP);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
252 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
253 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
254 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
255 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
256 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
257 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
258 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
260 setSchedulingPreference(Sched::RegPressure);
263 //===----------------------------------------------------------------------===//
264 // TargetLowering queries
265 //===----------------------------------------------------------------------===//
267 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
269 // SI has some legal vector types, but no legal vector operations. Say no
270 // shuffles are legal in order to prefer scalarizing some vector operations.
274 // FIXME: This really needs an address space argument. The immediate offset
275 // size is different for different sets of memory instruction sets.
277 // The single offset DS instructions have a 16-bit unsigned byte offset.
279 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
280 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
281 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
283 // SMRD instructions have an 8-bit, dword offset.
285 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
287 // No global is ever allowed as a base.
291 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
293 if (!isUInt<16>(AM.BaseOffs))
298 case 0: // "r+i" or just "i", depending on HasBaseReg.
301 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
303 // Otherwise we have r+r or r+i.
306 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
310 default: // Don't allow n * r
317 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
320 bool *IsFast) const {
324 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
325 // which isn't a simple VT.
326 if (!VT.isSimple() || VT == MVT::Other)
329 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
330 // see what for specifically. The wording everywhere else seems to be the
333 // XXX - The only mention I see of this in the ISA manual is for LDS direct
334 // reads the "byte address and must be dword aligned". Is it also true for the
335 // normal loads and stores?
336 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
337 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
338 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
339 // with adjacent offsets.
340 return Align % 4 == 0;
343 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
344 // byte-address are ignored, thus forcing Dword alignment.
345 // This applies to private, global, and constant memory.
348 return VT.bitsGT(MVT::i32);
351 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
352 unsigned SrcAlign, bool IsMemset,
355 MachineFunction &MF) const {
356 // FIXME: Should account for address space here.
358 // The default fallback uses the private pointer size as a guess for a type to
359 // use. Make sure we switch these to 64-bit accesses.
361 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
364 if (Size >= 8 && DstAlign >= 4)
371 TargetLoweringBase::LegalizeTypeAction
372 SITargetLowering::getPreferredVectorAction(EVT VT) const {
373 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
374 return TypeSplitVector;
376 return TargetLoweringBase::getPreferredVectorAction(VT);
379 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
381 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
382 getTargetMachine().getSubtargetImpl()->getInstrInfo());
383 return TII->isInlineConstant(Imm);
386 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
387 SDLoc SL, SDValue Chain,
388 unsigned Offset, bool Signed) const {
389 const DataLayout *DL = getDataLayout();
390 MachineFunction &MF = DAG.getMachineFunction();
391 const SIRegisterInfo *TRI =
392 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
393 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
395 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
397 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
398 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
399 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
400 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
401 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
402 DAG.getConstant(Offset, MVT::i64));
403 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
404 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
406 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
407 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
409 true, // isNonTemporal
411 DL->getABITypeAlignment(Ty)); // Alignment
414 SDValue SITargetLowering::LowerFormalArguments(
416 CallingConv::ID CallConv,
418 const SmallVectorImpl<ISD::InputArg> &Ins,
419 SDLoc DL, SelectionDAG &DAG,
420 SmallVectorImpl<SDValue> &InVals) const {
422 const TargetMachine &TM = getTargetMachine();
423 const SIRegisterInfo *TRI =
424 static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
426 MachineFunction &MF = DAG.getMachineFunction();
427 FunctionType *FType = MF.getFunction()->getFunctionType();
428 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
430 assert(CallConv == CallingConv::C);
432 SmallVector<ISD::InputArg, 16> Splits;
433 BitVector Skipped(Ins.size());
435 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
436 const ISD::InputArg &Arg = Ins[i];
438 // First check if it's a PS input addr
439 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
440 !Arg.Flags.isByVal()) {
442 assert((PSInputNum <= 15) && "Too many PS inputs!");
445 // We can savely skip PS inputs
451 Info->PSInputAddr |= 1 << PSInputNum++;
454 // Second split vertices into their elements
455 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
456 ISD::InputArg NewArg = Arg;
457 NewArg.Flags.setSplit();
458 NewArg.VT = Arg.VT.getVectorElementType();
460 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
461 // three or five element vertex only needs three or five registers,
462 // NOT four or eigth.
463 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
464 unsigned NumElements = ParamType->getVectorNumElements();
466 for (unsigned j = 0; j != NumElements; ++j) {
467 Splits.push_back(NewArg);
468 NewArg.PartOffset += NewArg.VT.getStoreSize();
471 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
472 Splits.push_back(Arg);
476 SmallVector<CCValAssign, 16> ArgLocs;
477 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
480 // At least one interpolation mode must be enabled or else the GPU will hang.
481 if (Info->getShaderType() == ShaderType::PIXEL &&
482 (Info->PSInputAddr & 0x7F) == 0) {
483 Info->PSInputAddr |= 1;
484 CCInfo.AllocateReg(AMDGPU::VGPR0);
485 CCInfo.AllocateReg(AMDGPU::VGPR1);
488 // The pointer to the list of arguments is stored in SGPR0, SGPR1
489 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
490 if (Info->getShaderType() == ShaderType::COMPUTE) {
491 Info->NumUserSGPRs = 4;
493 unsigned InputPtrReg =
494 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
495 unsigned InputPtrRegLo =
496 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
497 unsigned InputPtrRegHi =
498 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
500 unsigned ScratchPtrReg =
501 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
502 unsigned ScratchPtrRegLo =
503 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
504 unsigned ScratchPtrRegHi =
505 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
507 CCInfo.AllocateReg(InputPtrRegLo);
508 CCInfo.AllocateReg(InputPtrRegHi);
509 CCInfo.AllocateReg(ScratchPtrRegLo);
510 CCInfo.AllocateReg(ScratchPtrRegHi);
511 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
512 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
515 if (Info->getShaderType() == ShaderType::COMPUTE) {
516 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
520 AnalyzeFormalArguments(CCInfo, Splits);
522 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
524 const ISD::InputArg &Arg = Ins[i];
526 InVals.push_back(DAG.getUNDEF(Arg.VT));
530 CCValAssign &VA = ArgLocs[ArgIdx++];
531 EVT VT = VA.getLocVT();
535 EVT MemVT = Splits[i].VT;
536 const unsigned Offset = 36 + VA.getLocMemOffset();
537 // The first 36 bytes of the input buffer contains information about
538 // thread group and global sizes.
539 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
540 Offset, Ins[i].Flags.isSExt());
542 const PointerType *ParamTy =
543 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
544 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
545 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
546 // On SI local pointers are just offsets into LDS, so they are always
547 // less than 16-bits. On CI and newer they could potentially be
548 // real pointers, so we can't guarantee their size.
549 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
550 DAG.getValueType(MVT::i16));
553 InVals.push_back(Arg);
554 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
557 assert(VA.isRegLoc() && "Parameter must be in a register!");
559 unsigned Reg = VA.getLocReg();
561 if (VT == MVT::i64) {
562 // For now assume it is a pointer
563 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
564 &AMDGPU::SReg_64RegClass);
565 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
566 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
570 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
572 Reg = MF.addLiveIn(Reg, RC);
573 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
575 if (Arg.VT.isVector()) {
577 // Build a vector from the registers
578 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
579 unsigned NumElements = ParamType->getVectorNumElements();
581 SmallVector<SDValue, 4> Regs;
583 for (unsigned j = 1; j != NumElements; ++j) {
584 Reg = ArgLocs[ArgIdx++].getLocReg();
585 Reg = MF.addLiveIn(Reg, RC);
586 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
589 // Fill up the missing vector elements
590 NumElements = Arg.VT.getVectorNumElements() - NumElements;
591 for (unsigned j = 0; j != NumElements; ++j)
592 Regs.push_back(DAG.getUNDEF(VT));
594 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
598 InVals.push_back(Val);
603 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
604 MachineInstr * MI, MachineBasicBlock * BB) const {
606 MachineBasicBlock::iterator I = *MI;
607 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
608 getTargetMachine().getSubtargetImpl()->getInstrInfo());
609 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
611 switch (MI->getOpcode()) {
613 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
614 case AMDGPU::BRANCH: return BB;
615 case AMDGPU::SI_ADDR64_RSRC: {
616 unsigned SuperReg = MI->getOperand(0).getReg();
617 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
618 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
619 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
620 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
621 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
622 .addOperand(MI->getOperand(1));
623 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
625 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
626 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
627 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
629 .addImm(AMDGPU::sub0)
631 .addImm(AMDGPU::sub1);
632 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
634 .addImm(AMDGPU::sub0_sub1)
636 .addImm(AMDGPU::sub2_sub3);
637 MI->eraseFromParent();
640 case AMDGPU::V_SUB_F64: {
641 unsigned DestReg = MI->getOperand(0).getReg();
642 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
643 .addImm(0) // SRC0 modifiers
644 .addReg(MI->getOperand(1).getReg())
645 .addImm(1) // SRC1 modifiers
646 .addReg(MI->getOperand(2).getReg())
649 MI->eraseFromParent();
652 case AMDGPU::SI_RegisterStorePseudo: {
653 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
654 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
655 MachineInstrBuilder MIB =
656 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
658 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
659 MIB.addOperand(MI->getOperand(i));
661 MI->eraseFromParent();
664 case AMDGPU::FCLAMP_SI: {
665 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
666 getTargetMachine().getSubtargetImpl()->getInstrInfo());
667 DebugLoc DL = MI->getDebugLoc();
668 unsigned DestReg = MI->getOperand(0).getReg();
669 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
670 .addImm(0) // SRC0 modifiers
671 .addOperand(MI->getOperand(1))
672 .addImm(0) // SRC1 modifiers
676 MI->eraseFromParent();
682 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
683 if (!VT.isVector()) {
686 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
689 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
693 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
694 VT = VT.getScalarType();
699 switch (VT.getSimpleVT().SimpleTy) {
701 return false; /* There is V_MAD_F32 for f32 */
711 //===----------------------------------------------------------------------===//
712 // Custom DAG Lowering Operations
713 //===----------------------------------------------------------------------===//
715 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
716 switch (Op.getOpcode()) {
717 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
718 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
719 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
721 SDValue Result = LowerLOAD(Op, DAG);
722 assert((!Result.getNode() ||
723 Result.getNode()->getNumValues() == 2) &&
724 "Load should return a value and a chain");
730 return LowerTrig(Op, DAG);
731 case ISD::SELECT: return LowerSELECT(Op, DAG);
732 case ISD::FDIV: return LowerFDIV(Op, DAG);
733 case ISD::STORE: return LowerSTORE(Op, DAG);
734 case ISD::GlobalAddress: {
735 MachineFunction &MF = DAG.getMachineFunction();
736 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
737 return LowerGlobalAddress(MFI, Op, DAG);
739 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
740 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
745 /// \brief Helper function for LowerBRCOND
746 static SDNode *findUser(SDValue Value, unsigned Opcode) {
748 SDNode *Parent = Value.getNode();
749 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
752 if (I.getUse().get() != Value)
755 if (I->getOpcode() == Opcode)
761 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
763 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
764 unsigned FrameIndex = FINode->getIndex();
766 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
769 /// This transforms the control flow intrinsics to get the branch destination as
770 /// last parameter, also switches branch target with BR if the need arise
771 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
772 SelectionDAG &DAG) const {
776 SDNode *Intr = BRCOND.getOperand(1).getNode();
777 SDValue Target = BRCOND.getOperand(2);
778 SDNode *BR = nullptr;
780 if (Intr->getOpcode() == ISD::SETCC) {
781 // As long as we negate the condition everything is fine
782 SDNode *SetCC = Intr;
783 assert(SetCC->getConstantOperandVal(1) == 1);
784 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
786 Intr = SetCC->getOperand(0).getNode();
789 // Get the target from BR if we don't negate the condition
790 BR = findUser(BRCOND, ISD::BR);
791 Target = BR->getOperand(1);
794 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
796 // Build the result and
797 SmallVector<EVT, 4> Res;
798 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
799 Res.push_back(Intr->getValueType(i));
801 // operands of the new intrinsic call
802 SmallVector<SDValue, 4> Ops;
803 Ops.push_back(BRCOND.getOperand(0));
804 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
805 Ops.push_back(Intr->getOperand(i));
806 Ops.push_back(Target);
808 // build the new intrinsic call
809 SDNode *Result = DAG.getNode(
810 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
811 DAG.getVTList(Res), Ops).getNode();
814 // Give the branch instruction our target
819 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
820 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
821 BR = NewBR.getNode();
824 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
826 // Copy the intrinsic results to registers
827 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
828 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
832 Chain = DAG.getCopyToReg(
834 CopyToReg->getOperand(1),
835 SDValue(Result, i - 1),
838 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
841 // Remove the old intrinsic from the chain
842 DAG.ReplaceAllUsesOfValueWith(
843 SDValue(Intr, Intr->getNumValues() - 1),
844 Intr->getOperand(0));
849 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
851 SelectionDAG &DAG) const {
852 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
854 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
855 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
858 const GlobalValue *GV = GSD->getGlobal();
859 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
861 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
862 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
864 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
865 DAG.getConstant(0, MVT::i32));
866 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
867 DAG.getConstant(1, MVT::i32));
869 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
871 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
872 PtrHi, DAG.getConstant(0, MVT::i32),
873 SDValue(Lo.getNode(), 1));
874 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
877 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
878 SelectionDAG &DAG) const {
879 MachineFunction &MF = DAG.getMachineFunction();
880 const SIRegisterInfo *TRI =
881 static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
883 EVT VT = Op.getValueType();
885 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
887 switch (IntrinsicID) {
888 case Intrinsic::r600_read_ngroups_x:
889 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
890 SI::KernelInputOffsets::NGROUPS_X, false);
891 case Intrinsic::r600_read_ngroups_y:
892 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
893 SI::KernelInputOffsets::NGROUPS_Y, false);
894 case Intrinsic::r600_read_ngroups_z:
895 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
896 SI::KernelInputOffsets::NGROUPS_Z, false);
897 case Intrinsic::r600_read_global_size_x:
898 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
899 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
900 case Intrinsic::r600_read_global_size_y:
901 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
902 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
903 case Intrinsic::r600_read_global_size_z:
904 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
905 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
906 case Intrinsic::r600_read_local_size_x:
907 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
908 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
909 case Intrinsic::r600_read_local_size_y:
910 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
911 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
912 case Intrinsic::r600_read_local_size_z:
913 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
914 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
916 case Intrinsic::AMDGPU_read_workdim:
917 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
918 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
921 case Intrinsic::r600_read_tgid_x:
922 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
923 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
924 case Intrinsic::r600_read_tgid_y:
925 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
926 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
927 case Intrinsic::r600_read_tgid_z:
928 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
929 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
930 case Intrinsic::r600_read_tidig_x:
931 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
932 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
933 case Intrinsic::r600_read_tidig_y:
934 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
935 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
936 case Intrinsic::r600_read_tidig_z:
937 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
938 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
939 case AMDGPUIntrinsic::SI_load_const: {
945 MachineMemOperand *MMO = MF.getMachineMemOperand(
946 MachinePointerInfo(),
947 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
948 VT.getStoreSize(), 4);
949 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
950 Op->getVTList(), Ops, VT, MMO);
952 case AMDGPUIntrinsic::SI_sample:
953 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
954 case AMDGPUIntrinsic::SI_sampleb:
955 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
956 case AMDGPUIntrinsic::SI_sampled:
957 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
958 case AMDGPUIntrinsic::SI_samplel:
959 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
960 case AMDGPUIntrinsic::SI_vs_load_input:
961 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
966 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
970 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
971 SelectionDAG &DAG) const {
972 MachineFunction &MF = DAG.getMachineFunction();
973 SDValue Chain = Op.getOperand(0);
974 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
976 switch (IntrinsicID) {
977 case AMDGPUIntrinsic::SI_tbuffer_store: {
996 EVT VT = Op.getOperand(3).getValueType();
998 MachineMemOperand *MMO = MF.getMachineMemOperand(
999 MachinePointerInfo(),
1000 MachineMemOperand::MOStore,
1001 VT.getStoreSize(), 4);
1002 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1003 Op->getVTList(), Ops, VT, MMO);
1010 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1012 LoadSDNode *Load = cast<LoadSDNode>(Op);
1014 if (Op.getValueType().isVector()) {
1015 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1016 "Custom lowering for non-i32 vectors hasn't been implemented.");
1017 unsigned NumElements = Op.getValueType().getVectorNumElements();
1018 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1019 switch (Load->getAddressSpace()) {
1021 case AMDGPUAS::GLOBAL_ADDRESS:
1022 case AMDGPUAS::PRIVATE_ADDRESS:
1023 // v4 loads are supported for private and global memory.
1024 if (NumElements <= 4)
1027 case AMDGPUAS::LOCAL_ADDRESS:
1028 return ScalarizeVectorLoad(Op, DAG);
1032 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1035 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1037 SelectionDAG &DAG) const {
1038 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1044 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1045 if (Op.getValueType() != MVT::i64)
1049 SDValue Cond = Op.getOperand(0);
1051 SDValue Zero = DAG.getConstant(0, MVT::i32);
1052 SDValue One = DAG.getConstant(1, MVT::i32);
1054 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1055 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1057 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1058 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1060 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1062 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1063 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1065 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1067 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1068 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1071 // Catch division cases where we can use shortcuts with rcp and rsq
1073 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1075 SDValue LHS = Op.getOperand(0);
1076 SDValue RHS = Op.getOperand(1);
1077 EVT VT = Op.getValueType();
1078 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1080 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1081 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1082 CLHS->isExactlyValue(1.0)) {
1083 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1084 // the CI documentation has a worst case error of 1 ulp.
1085 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1086 // use it as long as we aren't trying to use denormals.
1088 // 1.0 / sqrt(x) -> rsq(x)
1090 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1091 // error seems really high at 2^29 ULP.
1092 if (RHS.getOpcode() == ISD::FSQRT)
1093 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1095 // 1.0 / x -> rcp(x)
1096 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1101 // Turn into multiply by the reciprocal.
1102 // x / y -> x * (1.0 / y)
1103 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1104 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1110 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1111 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1112 if (FastLowered.getNode())
1115 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1116 // selection error for now rather than do something incorrect.
1117 if (Subtarget->hasFP32Denormals())
1121 SDValue LHS = Op.getOperand(0);
1122 SDValue RHS = Op.getOperand(1);
1124 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1126 const APFloat K0Val(BitsToFloat(0x6f800000));
1127 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1129 const APFloat K1Val(BitsToFloat(0x2f800000));
1130 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1132 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1134 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1136 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1138 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1140 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1142 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1144 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1146 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1149 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1153 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1154 EVT VT = Op.getValueType();
1157 return LowerFDIV32(Op, DAG);
1160 return LowerFDIV64(Op, DAG);
1162 llvm_unreachable("Unexpected type for fdiv");
1165 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1167 StoreSDNode *Store = cast<StoreSDNode>(Op);
1168 EVT VT = Store->getMemoryVT();
1170 // These stores are legal.
1171 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1172 VT.isVector() && VT.getVectorNumElements() == 2 &&
1173 VT.getVectorElementType() == MVT::i32)
1176 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1177 if (VT.isVector() && VT.getVectorNumElements() > 4)
1178 return ScalarizeVectorStore(Op, DAG);
1182 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1186 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1187 return ScalarizeVectorStore(Op, DAG);
1190 return DAG.getTruncStore(Store->getChain(), DL,
1191 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1192 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1197 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1198 EVT VT = Op.getValueType();
1199 SDValue Arg = Op.getOperand(0);
1200 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1201 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1202 DAG.getConstantFP(0.5 / M_PI, VT)));
1204 switch (Op.getOpcode()) {
1206 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1208 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1210 llvm_unreachable("Wrong trig opcode");
1214 //===----------------------------------------------------------------------===//
1215 // Custom DAG optimizations
1216 //===----------------------------------------------------------------------===//
1218 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1219 DAGCombinerInfo &DCI) {
1220 EVT VT = N->getValueType(0);
1221 EVT ScalarVT = VT.getScalarType();
1222 if (ScalarVT != MVT::f32)
1225 SelectionDAG &DAG = DCI.DAG;
1228 SDValue Src = N->getOperand(0);
1229 EVT SrcVT = Src.getValueType();
1231 // TODO: We could try to match extracting the higher bytes, which would be
1232 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1233 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1234 // about in practice.
1235 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1236 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1237 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1238 DCI.AddToWorklist(Cvt.getNode());
1243 // We are primarily trying to catch operations on illegal vector types
1244 // before they are expanded.
1245 // For scalars, we can use the more flexible method of checking masked bits
1246 // after legalization.
1247 if (!DCI.isBeforeLegalize() ||
1248 !SrcVT.isVector() ||
1249 SrcVT.getVectorElementType() != MVT::i8) {
1253 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1255 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1257 unsigned NElts = SrcVT.getVectorNumElements();
1258 if (!SrcVT.isSimple() && NElts != 3)
1261 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1262 // prevent a mess from expanding to v4i32 and repacking.
1263 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1264 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1265 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1266 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1268 LoadSDNode *Load = cast<LoadSDNode>(Src);
1269 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1273 Load->getMemOperand());
1275 // Make sure successors of the original load stay after it by updating
1276 // them to use the new Chain.
1277 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1279 SmallVector<SDValue, 4> Elts;
1280 if (RegVT.isVector())
1281 DAG.ExtractVectorElements(NewLoad, Elts);
1283 Elts.push_back(NewLoad);
1285 SmallVector<SDValue, 4> Ops;
1287 unsigned EltIdx = 0;
1288 for (SDValue Elt : Elts) {
1289 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1290 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1291 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1292 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1293 DCI.AddToWorklist(Cvt.getNode());
1300 assert(Ops.size() == NElts);
1302 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1308 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1310 // This is a variant of
1311 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1313 // The normal DAG combiner will do this, but only if the add has one use since
1314 // that would increase the number of instructions.
1316 // This prevents us from seeing a constant offset that can be folded into a
1317 // memory instruction's addressing mode. If we know the resulting add offset of
1318 // a pointer can be folded into an addressing offset, we can replace the pointer
1319 // operand with the add of new constant offset. This eliminates one of the uses,
1320 // and may allow the remaining use to also be simplified.
1322 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1324 DAGCombinerInfo &DCI) const {
1325 SDValue N0 = N->getOperand(0);
1326 SDValue N1 = N->getOperand(1);
1328 if (N0.getOpcode() != ISD::ADD)
1331 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1335 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1339 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1340 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1342 // If the resulting offset is too large, we can't fold it into the addressing
1344 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1345 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1348 SelectionDAG &DAG = DCI.DAG;
1350 EVT VT = N->getValueType(0);
1352 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1353 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1355 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1358 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1359 DAGCombinerInfo &DCI) const {
1360 SelectionDAG &DAG = DCI.DAG;
1362 EVT VT = N->getValueType(0);
1364 switch (N->getOpcode()) {
1365 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1367 SDValue Arg0 = N->getOperand(0);
1368 SDValue Arg1 = N->getOperand(1);
1369 SDValue CC = N->getOperand(2);
1370 ConstantSDNode * C = nullptr;
1371 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1373 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1375 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1376 && Arg0.getOperand(0).getValueType() == MVT::i1
1377 && (C = dyn_cast<ConstantSDNode>(Arg1))
1379 && CCOp == ISD::SETNE) {
1380 return SimplifySetCC(VT, Arg0.getOperand(0),
1381 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1386 case AMDGPUISD::CVT_F32_UBYTE0:
1387 case AMDGPUISD::CVT_F32_UBYTE1:
1388 case AMDGPUISD::CVT_F32_UBYTE2:
1389 case AMDGPUISD::CVT_F32_UBYTE3: {
1390 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1392 SDValue Src = N->getOperand(0);
1393 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1395 APInt KnownZero, KnownOne;
1396 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1397 !DCI.isBeforeLegalizeOps());
1398 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1399 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1400 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1401 DCI.CommitTargetLoweringOpt(TLO);
1407 case ISD::UINT_TO_FP: {
1408 return performUCharToFloatCombine(N, DCI);
1411 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1414 EVT VT = N->getValueType(0);
1418 SDValue LHS = N->getOperand(0);
1419 SDValue RHS = N->getOperand(1);
1421 // These should really be instruction patterns, but writing patterns with
1422 // source modiifiers is a pain.
1424 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1425 if (LHS.getOpcode() == ISD::FADD) {
1426 SDValue A = LHS.getOperand(0);
1427 if (A == LHS.getOperand(1)) {
1428 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1429 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1433 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1434 if (RHS.getOpcode() == ISD::FADD) {
1435 SDValue A = RHS.getOperand(0);
1436 if (A == RHS.getOperand(1)) {
1437 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1438 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1445 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1448 EVT VT = N->getValueType(0);
1450 // Try to get the fneg to fold into the source modifier. This undoes generic
1451 // DAG combines and folds them into the mad.
1452 if (VT == MVT::f32) {
1453 SDValue LHS = N->getOperand(0);
1454 SDValue RHS = N->getOperand(1);
1456 if (LHS.getOpcode() == ISD::FMUL) {
1457 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1459 SDValue A = LHS.getOperand(0);
1460 SDValue B = LHS.getOperand(1);
1461 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1463 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1466 if (RHS.getOpcode() == ISD::FMUL) {
1467 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1469 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1470 SDValue B = RHS.getOperand(1);
1473 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1476 if (LHS.getOpcode() == ISD::FADD) {
1477 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1479 SDValue A = LHS.getOperand(0);
1480 if (A == LHS.getOperand(1)) {
1481 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1482 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1484 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1488 if (RHS.getOpcode() == ISD::FADD) {
1489 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1491 SDValue A = RHS.getOperand(0);
1492 if (A == RHS.getOperand(1)) {
1493 const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
1494 return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1504 case ISD::ATOMIC_LOAD:
1505 case ISD::ATOMIC_STORE:
1506 case ISD::ATOMIC_CMP_SWAP:
1507 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1508 case ISD::ATOMIC_SWAP:
1509 case ISD::ATOMIC_LOAD_ADD:
1510 case ISD::ATOMIC_LOAD_SUB:
1511 case ISD::ATOMIC_LOAD_AND:
1512 case ISD::ATOMIC_LOAD_OR:
1513 case ISD::ATOMIC_LOAD_XOR:
1514 case ISD::ATOMIC_LOAD_NAND:
1515 case ISD::ATOMIC_LOAD_MIN:
1516 case ISD::ATOMIC_LOAD_MAX:
1517 case ISD::ATOMIC_LOAD_UMIN:
1518 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1519 if (DCI.isBeforeLegalize())
1522 MemSDNode *MemNode = cast<MemSDNode>(N);
1523 SDValue Ptr = MemNode->getBasePtr();
1525 // TODO: We could also do this for multiplies.
1526 unsigned AS = MemNode->getAddressSpace();
1527 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1528 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1530 SmallVector<SDValue, 8> NewOps;
1531 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1532 NewOps.push_back(MemNode->getOperand(I));
1534 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1535 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1541 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1544 /// \brief Test if RegClass is one of the VSrc classes
1545 static bool isVSrc(unsigned RegClass) {
1547 default: return false;
1548 case AMDGPU::VSrc_32RegClassID:
1549 case AMDGPU::VCSrc_32RegClassID:
1550 case AMDGPU::VSrc_64RegClassID:
1551 case AMDGPU::VCSrc_64RegClassID:
1556 /// \brief Test if RegClass is one of the SSrc classes
1557 static bool isSSrc(unsigned RegClass) {
1558 return AMDGPU::SSrc_32RegClassID == RegClass ||
1559 AMDGPU::SSrc_64RegClassID == RegClass;
1562 /// \brief Analyze the possible immediate value Op
1564 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1565 /// and the immediate value if it's a literal immediate
1566 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1573 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1574 if (Node->getZExtValue() >> 32) {
1577 Imm.I = Node->getSExtValue();
1578 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1579 if (N->getValueType(0) != MVT::f32)
1581 Imm.F = Node->getValueAPF().convertToFloat();
1583 return -1; // It isn't an immediate
1585 if ((Imm.I >= -16 && Imm.I <= 64) ||
1586 Imm.F == 0.5f || Imm.F == -0.5f ||
1587 Imm.F == 1.0f || Imm.F == -1.0f ||
1588 Imm.F == 2.0f || Imm.F == -2.0f ||
1589 Imm.F == 4.0f || Imm.F == -4.0f)
1590 return 0; // It's an inline immediate
1592 return Imm.I; // It's a literal immediate
1595 /// \brief Try to fold an immediate directly into an instruction
1596 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1597 bool &ScalarSlotUsed) const {
1599 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1600 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1601 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1602 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1605 const SDValue &Op = Mov->getOperand(0);
1606 int32_t Value = analyzeImmediate(Op.getNode());
1608 // Not an immediate at all
1611 } else if (Value == 0) {
1612 // Inline immediates can always be fold
1616 } else if (Value == Immediate) {
1617 // Already fold literal immediate
1621 } else if (!ScalarSlotUsed && !Immediate) {
1622 // Fold this literal immediate
1623 ScalarSlotUsed = true;
1633 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1634 SelectionDAG &DAG, const SDValue &Op) const {
1635 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1636 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1637 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1639 if (!Op->isMachineOpcode()) {
1640 switch(Op->getOpcode()) {
1641 case ISD::CopyFromReg: {
1642 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1643 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1644 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1645 return MRI.getRegClass(Reg);
1647 return TRI.getPhysRegClass(Reg);
1649 default: return nullptr;
1652 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1653 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1654 if (OpClassID != -1) {
1655 return TRI.getRegClass(OpClassID);
1657 switch(Op.getMachineOpcode()) {
1658 case AMDGPU::COPY_TO_REGCLASS:
1659 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1660 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1662 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1663 // class, then the register class for the value could be either a
1664 // VReg or and SReg. In order to get a more accurate
1665 if (isVSrc(OpClassID))
1666 return getRegClassForNode(DAG, Op.getOperand(0));
1668 return TRI.getRegClass(OpClassID);
1669 case AMDGPU::EXTRACT_SUBREG: {
1670 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1671 const TargetRegisterClass *SuperClass =
1672 getRegClassForNode(DAG, Op.getOperand(0));
1673 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1675 case AMDGPU::REG_SEQUENCE:
1676 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1677 return TRI.getRegClass(
1678 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1680 return getRegClassFor(Op.getSimpleValueType());
1684 /// \brief Does "Op" fit into register class "RegClass" ?
1685 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1686 unsigned RegClass) const {
1687 const TargetRegisterInfo *TRI =
1688 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1689 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1693 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1696 /// \returns true if \p Node's operands are different from the SDValue list
1698 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1699 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1700 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1707 /// TODO: This needs to be removed. It's current primary purpose is to fold
1708 /// immediates into operands when legal. The legalization parts are redundant
1709 /// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
1710 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1711 SelectionDAG &DAG) const {
1712 // Original encoding (either e32 or e64)
1713 int Opcode = Node->getMachineOpcode();
1714 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1715 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1716 const MCInstrDesc *Desc = &TII->get(Opcode);
1718 unsigned NumDefs = Desc->getNumDefs();
1719 unsigned NumOps = Desc->getNumOperands();
1721 // Commuted opcode if available
1722 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1723 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1725 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1726 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1728 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1729 bool HaveVSrc = false, HaveSSrc = false;
1731 // First figure out what we already have in this instruction.
1732 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1733 i != e && Op < NumOps; ++i, ++Op) {
1735 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1736 if (isVSrc(RegClass))
1738 else if (isSSrc(RegClass))
1743 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1744 if (Imm != -1 && Imm != 0) {
1745 // Literal immediate
1750 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1751 if (!HaveVSrc && !HaveSSrc)
1754 // No scalar allowed when we have both VSrc and SSrc
1755 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1757 // If this instruction has an implicit use of VCC, then it can't use the
1759 for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1760 if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1761 ScalarSlotUsed = true;
1766 // Second go over the operands and try to fold them
1767 std::vector<SDValue> Ops;
1768 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1769 i != e && Op < NumOps; ++i, ++Op) {
1771 const SDValue &Operand = Node->getOperand(i);
1772 Ops.push_back(Operand);
1774 // Already folded immediate?
1775 if (isa<ConstantSDNode>(Operand.getNode()) ||
1776 isa<ConstantFPSDNode>(Operand.getNode()))
1779 // Is this a VSrc or SSrc operand?
1780 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1781 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1782 // Try to fold the immediates. If this ends up with multiple constant bus
1783 // uses, it will be legalized later.
1784 foldImm(Ops[i], Immediate, ScalarSlotUsed);
1788 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1790 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1791 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1793 // Test if it makes sense to swap operands
1794 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1795 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1796 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1798 // Swap commutable operands
1799 std::swap(Ops[0], Ops[1]);
1808 // Add optional chain and glue
1809 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1810 Ops.push_back(Node->getOperand(i));
1812 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1813 // this case a brand new node is always be created, even if the operands
1814 // are the same as before. So, manually check if anything has been changed.
1815 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1819 // Create a complete new instruction
1820 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1823 /// \brief Helper function for adjustWritemask
1824 static unsigned SubIdx2Lane(unsigned Idx) {
1827 case AMDGPU::sub0: return 0;
1828 case AMDGPU::sub1: return 1;
1829 case AMDGPU::sub2: return 2;
1830 case AMDGPU::sub3: return 3;
1834 /// \brief Adjust the writemask of MIMG instructions
1835 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1836 SelectionDAG &DAG) const {
1837 SDNode *Users[4] = { };
1839 unsigned OldDmask = Node->getConstantOperandVal(0);
1840 unsigned NewDmask = 0;
1842 // Try to figure out the used register components
1843 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1846 // Abort if we can't understand the usage
1847 if (!I->isMachineOpcode() ||
1848 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1851 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1852 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1853 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1855 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1857 // Set which texture component corresponds to the lane.
1859 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1861 Comp = countTrailingZeros(Dmask);
1862 Dmask &= ~(1 << Comp);
1865 // Abort if we have more than one user per component
1870 NewDmask |= 1 << Comp;
1873 // Abort if there's no change
1874 if (NewDmask == OldDmask)
1877 // Adjust the writemask in the node
1878 std::vector<SDValue> Ops;
1879 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1880 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1881 Ops.push_back(Node->getOperand(i));
1882 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1884 // If we only got one lane, replace it with a copy
1885 // (if NewDmask has only one bit set...)
1886 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1887 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1888 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1889 SDLoc(), Users[Lane]->getValueType(0),
1890 SDValue(Node, 0), RC);
1891 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1895 // Update the users of the node with the new indices
1896 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1898 SDNode *User = Users[i];
1902 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1903 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1907 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1908 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1909 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1914 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1915 /// with frame index operands.
1916 /// LLVM assumes that inputs are to these instructions are registers.
1917 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1918 SelectionDAG &DAG) const {
1920 SmallVector<SDValue, 8> Ops;
1921 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1922 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1923 Ops.push_back(Node->getOperand(i));
1928 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1929 Node->getOperand(i).getValueType(),
1930 Node->getOperand(i)), 0));
1933 DAG.UpdateNodeOperands(Node, Ops);
1936 /// \brief Fold the instructions after selecting them.
1937 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1938 SelectionDAG &DAG) const {
1939 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1940 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1941 Node = AdjustRegClass(Node, DAG);
1943 if (TII->isMIMG(Node->getMachineOpcode()))
1944 adjustWritemask(Node, DAG);
1946 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1947 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1948 legalizeTargetIndependentNode(Node, DAG);
1952 return legalizeOperands(Node, DAG);
1955 /// \brief Assign the register class depending on the number of
1956 /// bits set in the writemask
1957 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1958 SDNode *Node) const {
1959 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1960 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1962 TII->legalizeOperands(MI);
1964 if (TII->isMIMG(MI->getOpcode())) {
1965 unsigned VReg = MI->getOperand(0).getReg();
1966 unsigned Writemask = MI->getOperand(1).getImm();
1967 unsigned BitsSet = 0;
1968 for (unsigned i = 0; i < 4; ++i)
1969 BitsSet += Writemask & (1 << i) ? 1 : 0;
1971 const TargetRegisterClass *RC;
1974 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1975 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1976 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1979 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1980 MI->setDesc(TII->get(NewOpcode));
1981 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1982 MRI.setRegClass(VReg, RC);
1986 // Replace unused atomics with the no return version.
1987 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1988 if (NoRetAtomicOp != -1) {
1989 if (!Node->hasAnyUseOfValue(0)) {
1990 MI->setDesc(TII->get(NoRetAtomicOp));
1991 MI->RemoveOperand(0);
1998 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1999 SelectionDAG &DAG) const {
2002 unsigned NewOpcode = N->getMachineOpcode();
2004 switch (N->getMachineOpcode()) {
2006 case AMDGPU::S_LOAD_DWORD_IMM:
2007 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2009 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2010 if (NewOpcode == N->getMachineOpcode()) {
2011 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2014 case AMDGPU::S_LOAD_DWORDX4_IMM:
2015 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2016 if (NewOpcode == N->getMachineOpcode()) {
2017 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2019 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2022 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2023 MachineSDNode *RSrc = DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL,
2025 DAG.getConstant(0, MVT::i64));
2027 SmallVector<SDValue, 8> Ops;
2028 Ops.push_back(SDValue(RSrc, 0));
2029 Ops.push_back(N->getOperand(0));
2030 Ops.push_back(DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32));
2032 // Copy remaining operands so we keep any chain and glue nodes that follow
2033 // the normal operands.
2034 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2035 Ops.push_back(N->getOperand(I));
2037 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2042 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2043 const TargetRegisterClass *RC,
2044 unsigned Reg, EVT VT) const {
2045 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2047 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2048 cast<RegisterSDNode>(VReg)->getReg(), VT);