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 //===----------------------------------------------------------------------===//
15 #include "SIISelLowering.h"
17 #include "AMDILIntrinsicInfo.h"
18 #include "SIInstrInfo.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "SIRegisterInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/IR/Function.h"
27 const uint64_t RSRC_DATA_FORMAT = 0xf00000000000LL;
31 SITargetLowering::SITargetLowering(TargetMachine &TM) :
32 AMDGPUTargetLowering(TM) {
34 addRegisterClass(MVT::i1, &AMDGPU::SReg_64RegClass);
35 addRegisterClass(MVT::i64, &AMDGPU::VSrc_64RegClass);
37 addRegisterClass(MVT::v2i1, &AMDGPU::VReg_64RegClass);
38 addRegisterClass(MVT::v4i1, &AMDGPU::VReg_128RegClass);
40 addRegisterClass(MVT::v16i8, &AMDGPU::SReg_128RegClass);
41 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
42 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
44 addRegisterClass(MVT::i32, &AMDGPU::VSrc_32RegClass);
45 addRegisterClass(MVT::f32, &AMDGPU::VSrc_32RegClass);
47 addRegisterClass(MVT::v1i32, &AMDGPU::VSrc_32RegClass);
49 addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
50 addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
51 addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
53 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
54 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
55 addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
57 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
58 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
60 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
61 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
63 computeRegisterProperties();
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
68 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
70 setOperationAction(ISD::ADD, MVT::i64, Legal);
71 setOperationAction(ISD::ADD, MVT::i32, Legal);
73 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
74 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
76 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
78 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
79 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
81 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
82 setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
84 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
86 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
88 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
89 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
91 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
93 setTargetDAGCombine(ISD::SELECT_CC);
95 setTargetDAGCombine(ISD::SETCC);
97 setSchedulingPreference(Sched::RegPressure);
100 //===----------------------------------------------------------------------===//
101 // TargetLowering queries
102 //===----------------------------------------------------------------------===//
104 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
105 bool *IsFast) const {
106 // XXX: This depends on the address space and also we may want to revist
107 // the alignment values we specify in the DataLayout.
108 return VT.bitsGT(MVT::i32);
112 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
113 SDLoc DL, SDValue Chain,
114 unsigned Offset) const {
115 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
116 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
117 AMDGPUAS::CONSTANT_ADDRESS);
118 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
119 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
120 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
121 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
122 DAG.getConstant(Offset, MVT::i64));
123 return DAG.getLoad(VT, DL, Chain, Ptr,
124 MachinePointerInfo(UndefValue::get(PtrTy)),
125 false, false, false, ArgVT.getSizeInBits() >> 3);
129 SDValue SITargetLowering::LowerFormalArguments(
131 CallingConv::ID CallConv,
133 const SmallVectorImpl<ISD::InputArg> &Ins,
134 SDLoc DL, SelectionDAG &DAG,
135 SmallVectorImpl<SDValue> &InVals) const {
137 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
139 MachineFunction &MF = DAG.getMachineFunction();
140 FunctionType *FType = MF.getFunction()->getFunctionType();
141 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
143 assert(CallConv == CallingConv::C);
145 SmallVector<ISD::InputArg, 16> Splits;
146 uint32_t Skipped = 0;
148 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
149 const ISD::InputArg &Arg = Ins[i];
151 // First check if it's a PS input addr
152 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
154 assert((PSInputNum <= 15) && "Too many PS inputs!");
157 // We can savely skip PS inputs
163 Info->PSInputAddr |= 1 << PSInputNum++;
166 // Second split vertices into their elements
167 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
168 ISD::InputArg NewArg = Arg;
169 NewArg.Flags.setSplit();
170 NewArg.VT = Arg.VT.getVectorElementType();
172 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
173 // three or five element vertex only needs three or five registers,
174 // NOT four or eigth.
175 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
176 unsigned NumElements = ParamType->getVectorNumElements();
178 for (unsigned j = 0; j != NumElements; ++j) {
179 Splits.push_back(NewArg);
180 NewArg.PartOffset += NewArg.VT.getStoreSize();
184 Splits.push_back(Arg);
188 SmallVector<CCValAssign, 16> ArgLocs;
189 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
190 getTargetMachine(), ArgLocs, *DAG.getContext());
192 // At least one interpolation mode must be enabled or else the GPU will hang.
193 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
194 Info->PSInputAddr |= 1;
195 CCInfo.AllocateReg(AMDGPU::VGPR0);
196 CCInfo.AllocateReg(AMDGPU::VGPR1);
199 // The pointer to the list of arguments is stored in SGPR0, SGPR1
200 if (Info->ShaderType == ShaderType::COMPUTE) {
201 CCInfo.AllocateReg(AMDGPU::SGPR0);
202 CCInfo.AllocateReg(AMDGPU::SGPR1);
203 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
206 AnalyzeFormalArguments(CCInfo, Splits);
208 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
210 const ISD::InputArg &Arg = Ins[i];
211 if (Skipped & (1 << i)) {
212 InVals.push_back(DAG.getUNDEF(Arg.VT));
216 CCValAssign &VA = ArgLocs[ArgIdx++];
217 EVT VT = VA.getLocVT();
220 // The first 36 bytes of the input buffer contains information about
221 // thread group and global sizes.
222 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
223 36 + VA.getLocMemOffset());
224 InVals.push_back(Arg);
227 assert(VA.isRegLoc() && "Parameter must be in a register!");
229 unsigned Reg = VA.getLocReg();
231 if (VT == MVT::i64) {
232 // For now assume it is a pointer
233 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
234 &AMDGPU::SReg_64RegClass);
235 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
236 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
240 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
242 Reg = MF.addLiveIn(Reg, RC);
243 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
245 if (Arg.VT.isVector()) {
247 // Build a vector from the registers
248 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
249 unsigned NumElements = ParamType->getVectorNumElements();
251 SmallVector<SDValue, 4> Regs;
253 for (unsigned j = 1; j != NumElements; ++j) {
254 Reg = ArgLocs[ArgIdx++].getLocReg();
255 Reg = MF.addLiveIn(Reg, RC);
256 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
259 // Fill up the missing vector elements
260 NumElements = Arg.VT.getVectorNumElements() - NumElements;
261 for (unsigned j = 0; j != NumElements; ++j)
262 Regs.push_back(DAG.getUNDEF(VT));
264 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
265 Regs.data(), Regs.size()));
269 InVals.push_back(Val);
274 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
275 MachineInstr * MI, MachineBasicBlock * BB) const {
277 MachineBasicBlock::iterator I = *MI;
279 switch (MI->getOpcode()) {
281 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
282 case AMDGPU::BRANCH: return BB;
283 case AMDGPU::SI_ADDR64_RSRC: {
284 const SIInstrInfo *TII =
285 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
286 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
287 unsigned SuperReg = MI->getOperand(0).getReg();
288 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
289 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
290 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
291 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
292 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
293 .addOperand(MI->getOperand(1));
294 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
296 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
297 .addImm(RSRC_DATA_FORMAT >> 32);
298 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
300 .addImm(AMDGPU::sub0)
302 .addImm(AMDGPU::sub1);
303 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
305 .addImm(AMDGPU::sub0_sub1)
307 .addImm(AMDGPU::sub2_sub3);
308 MI->eraseFromParent();
311 case AMDGPU::V_SUB_F64: {
312 const SIInstrInfo *TII =
313 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
314 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
315 MI->getOperand(0).getReg())
316 .addReg(MI->getOperand(1).getReg())
317 .addReg(MI->getOperand(2).getReg())
318 .addImm(0) /* src2 */
320 .addImm(0) /* CLAMP */
321 .addImm(0) /* OMOD */
322 .addImm(2); /* NEG */
323 MI->eraseFromParent();
330 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
331 if (!VT.isVector()) {
334 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
337 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
341 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
342 VT = VT.getScalarType();
347 switch (VT.getSimpleVT().SimpleTy) {
349 return false; /* There is V_MAD_F32 for f32 */
359 //===----------------------------------------------------------------------===//
360 // Custom DAG Lowering Operations
361 //===----------------------------------------------------------------------===//
363 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
364 MachineFunction &MF = DAG.getMachineFunction();
365 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
366 switch (Op.getOpcode()) {
367 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
368 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
369 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
370 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
371 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
372 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
373 case ISD::INTRINSIC_WO_CHAIN: {
374 unsigned IntrinsicID =
375 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
376 EVT VT = Op.getValueType();
378 //XXX: Hardcoded we only use two to store the pointer to the parameters.
379 unsigned NumUserSGPRs = 2;
380 switch (IntrinsicID) {
381 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
382 case Intrinsic::r600_read_ngroups_x:
383 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
384 case Intrinsic::r600_read_ngroups_y:
385 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
386 case Intrinsic::r600_read_ngroups_z:
387 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
388 case Intrinsic::r600_read_global_size_x:
389 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
390 case Intrinsic::r600_read_global_size_y:
391 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
392 case Intrinsic::r600_read_global_size_z:
393 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
394 case Intrinsic::r600_read_local_size_x:
395 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
396 case Intrinsic::r600_read_local_size_y:
397 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
398 case Intrinsic::r600_read_local_size_z:
399 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
400 case Intrinsic::r600_read_tgid_x:
401 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
402 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
403 case Intrinsic::r600_read_tgid_y:
404 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
405 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
406 case Intrinsic::r600_read_tgid_z:
407 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
408 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
409 case Intrinsic::r600_read_tidig_x:
410 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
412 case Intrinsic::r600_read_tidig_y:
413 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
415 case Intrinsic::r600_read_tidig_z:
416 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
425 /// \brief Helper function for LowerBRCOND
426 static SDNode *findUser(SDValue Value, unsigned Opcode) {
428 SDNode *Parent = Value.getNode();
429 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
432 if (I.getUse().get() != Value)
435 if (I->getOpcode() == Opcode)
441 /// This transforms the control flow intrinsics to get the branch destination as
442 /// last parameter, also switches branch target with BR if the need arise
443 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
444 SelectionDAG &DAG) const {
448 SDNode *Intr = BRCOND.getOperand(1).getNode();
449 SDValue Target = BRCOND.getOperand(2);
452 if (Intr->getOpcode() == ISD::SETCC) {
453 // As long as we negate the condition everything is fine
454 SDNode *SetCC = Intr;
455 assert(SetCC->getConstantOperandVal(1) == 1);
456 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
458 Intr = SetCC->getOperand(0).getNode();
461 // Get the target from BR if we don't negate the condition
462 BR = findUser(BRCOND, ISD::BR);
463 Target = BR->getOperand(1);
466 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
468 // Build the result and
469 SmallVector<EVT, 4> Res;
470 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
471 Res.push_back(Intr->getValueType(i));
473 // operands of the new intrinsic call
474 SmallVector<SDValue, 4> Ops;
475 Ops.push_back(BRCOND.getOperand(0));
476 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
477 Ops.push_back(Intr->getOperand(i));
478 Ops.push_back(Target);
480 // build the new intrinsic call
481 SDNode *Result = DAG.getNode(
482 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
483 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
486 // Give the branch instruction our target
491 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
494 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
496 // Copy the intrinsic results to registers
497 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
498 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
502 Chain = DAG.getCopyToReg(
504 CopyToReg->getOperand(1),
505 SDValue(Result, i - 1),
508 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
511 // Remove the old intrinsic from the chain
512 DAG.ReplaceAllUsesOfValueWith(
513 SDValue(Intr, Intr->getNumValues() - 1),
514 Intr->getOperand(0));
519 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
520 SDValue LHS = Op.getOperand(0);
521 SDValue RHS = Op.getOperand(1);
522 SDValue True = Op.getOperand(2);
523 SDValue False = Op.getOperand(3);
524 SDValue CC = Op.getOperand(4);
525 EVT VT = Op.getValueType();
528 // Possible Min/Max pattern
529 SDValue MinMax = LowerMinMax(Op, DAG);
530 if (MinMax.getNode()) {
534 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
535 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
538 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
539 SelectionDAG &DAG) const {
540 EVT VT = Op.getValueType();
543 if (VT != MVT::i64) {
547 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
548 DAG.getConstant(31, MVT::i32));
550 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
553 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
554 SelectionDAG &DAG) const {
555 EVT VT = Op.getValueType();
558 if (VT != MVT::i64) {
562 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
563 DAG.getConstant(0, MVT::i32));
566 //===----------------------------------------------------------------------===//
567 // Custom DAG optimizations
568 //===----------------------------------------------------------------------===//
570 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
571 DAGCombinerInfo &DCI) const {
572 SelectionDAG &DAG = DCI.DAG;
574 EVT VT = N->getValueType(0);
576 switch (N->getOpcode()) {
578 case ISD::SELECT_CC: {
580 ConstantSDNode *True, *False;
581 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
582 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
583 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
584 && True->isAllOnesValue()
585 && False->isNullValue()
587 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
588 N->getOperand(1), N->getOperand(4));
594 SDValue Arg0 = N->getOperand(0);
595 SDValue Arg1 = N->getOperand(1);
596 SDValue CC = N->getOperand(2);
597 ConstantSDNode * C = NULL;
598 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
600 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
602 && Arg0.getOpcode() == ISD::SIGN_EXTEND
603 && Arg0.getOperand(0).getValueType() == MVT::i1
604 && (C = dyn_cast<ConstantSDNode>(Arg1))
606 && CCOp == ISD::SETNE) {
607 return SimplifySetCC(VT, Arg0.getOperand(0),
608 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
616 /// \brief Test if RegClass is one of the VSrc classes
617 static bool isVSrc(unsigned RegClass) {
618 return AMDGPU::VSrc_32RegClassID == RegClass ||
619 AMDGPU::VSrc_64RegClassID == RegClass;
622 /// \brief Test if RegClass is one of the SSrc classes
623 static bool isSSrc(unsigned RegClass) {
624 return AMDGPU::SSrc_32RegClassID == RegClass ||
625 AMDGPU::SSrc_64RegClassID == RegClass;
628 /// \brief Analyze the possible immediate value Op
630 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
631 /// and the immediate value if it's a literal immediate
632 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
639 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
640 if (Node->getZExtValue() >> 32) {
643 Imm.I = Node->getSExtValue();
644 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
645 Imm.F = Node->getValueAPF().convertToFloat();
647 return -1; // It isn't an immediate
649 if ((Imm.I >= -16 && Imm.I <= 64) ||
650 Imm.F == 0.5f || Imm.F == -0.5f ||
651 Imm.F == 1.0f || Imm.F == -1.0f ||
652 Imm.F == 2.0f || Imm.F == -2.0f ||
653 Imm.F == 4.0f || Imm.F == -4.0f)
654 return 0; // It's an inline immediate
656 return Imm.I; // It's a literal immediate
659 /// \brief Try to fold an immediate directly into an instruction
660 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
661 bool &ScalarSlotUsed) const {
663 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
664 const SIInstrInfo *TII =
665 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
666 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
669 const SDValue &Op = Mov->getOperand(0);
670 int32_t Value = analyzeImmediate(Op.getNode());
672 // Not an immediate at all
675 } else if (Value == 0) {
676 // Inline immediates can always be fold
680 } else if (Value == Immediate) {
681 // Already fold literal immediate
685 } else if (!ScalarSlotUsed && !Immediate) {
686 // Fold this literal immediate
687 ScalarSlotUsed = true;
697 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
698 SelectionDAG &DAG, const SDValue &Op) const {
699 const SIInstrInfo *TII =
700 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
701 const SIRegisterInfo &TRI = TII->getRegisterInfo();
703 if (!Op->isMachineOpcode()) {
704 switch(Op->getOpcode()) {
705 case ISD::CopyFromReg: {
706 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
707 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
708 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
709 return MRI.getRegClass(Reg);
711 return TRI.getPhysRegClass(Reg);
713 default: return NULL;
716 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
717 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
718 if (OpClassID != -1) {
719 return TRI.getRegClass(OpClassID);
721 switch(Op.getMachineOpcode()) {
722 case AMDGPU::COPY_TO_REGCLASS:
723 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
724 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
726 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
727 // class, then the register class for the value could be either a
728 // VReg or and SReg. In order to get a more accurate
729 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
730 OpClassID == AMDGPU::VSrc_64RegClassID) {
731 return getRegClassForNode(DAG, Op.getOperand(0));
733 return TRI.getRegClass(OpClassID);
734 case AMDGPU::EXTRACT_SUBREG: {
735 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
736 const TargetRegisterClass *SuperClass =
737 getRegClassForNode(DAG, Op.getOperand(0));
738 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
740 case AMDGPU::REG_SEQUENCE:
741 // Operand 0 is the register class id for REG_SEQUENCE instructions.
742 return TRI.getRegClass(
743 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
745 return getRegClassFor(Op.getSimpleValueType());
749 /// \brief Does "Op" fit into register class "RegClass" ?
750 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
751 unsigned RegClass) const {
752 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
753 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
757 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
760 /// \brief Make sure that we don't exeed the number of allowed scalars
761 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
763 bool &ScalarSlotUsed) const {
765 // First map the operands register class to a destination class
766 if (RegClass == AMDGPU::VSrc_32RegClassID)
767 RegClass = AMDGPU::VReg_32RegClassID;
768 else if (RegClass == AMDGPU::VSrc_64RegClassID)
769 RegClass = AMDGPU::VReg_64RegClassID;
773 // Nothing todo if they fit naturaly
774 if (fitsRegClass(DAG, Operand, RegClass))
777 // If the scalar slot isn't used yet use it now
778 if (!ScalarSlotUsed) {
779 ScalarSlotUsed = true;
783 // This is a conservative aproach, it is possible that we can't determine
784 // the correct register class and copy too often, but better save than sorry.
785 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
786 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
787 Operand.getValueType(), Operand, RC);
788 Operand = SDValue(Node, 0);
791 /// \returns true if \p Node's operands are different from the SDValue list
793 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
794 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
795 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
802 /// \brief Try to fold the Nodes operands into the Node
803 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
804 SelectionDAG &DAG) const {
806 // Original encoding (either e32 or e64)
807 int Opcode = Node->getMachineOpcode();
808 const SIInstrInfo *TII =
809 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
810 const MCInstrDesc *Desc = &TII->get(Opcode);
812 unsigned NumDefs = Desc->getNumDefs();
813 unsigned NumOps = Desc->getNumOperands();
815 // Commuted opcode if available
816 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
817 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
819 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
820 assert(!DescRev || DescRev->getNumOperands() == NumOps);
822 // e64 version if available, -1 otherwise
823 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
824 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
826 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
827 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
829 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
830 bool HaveVSrc = false, HaveSSrc = false;
832 // First figure out what we alread have in this instruction
833 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
834 i != e && Op < NumOps; ++i, ++Op) {
836 unsigned RegClass = Desc->OpInfo[Op].RegClass;
837 if (isVSrc(RegClass))
839 else if (isSSrc(RegClass))
844 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
845 if (Imm != -1 && Imm != 0) {
851 // If we neither have VSrc nor SSrc it makes no sense to continue
852 if (!HaveVSrc && !HaveSSrc)
855 // No scalar allowed when we have both VSrc and SSrc
856 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
858 // Second go over the operands and try to fold them
859 std::vector<SDValue> Ops;
860 bool Promote2e64 = false;
861 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
862 i != e && Op < NumOps; ++i, ++Op) {
864 const SDValue &Operand = Node->getOperand(i);
865 Ops.push_back(Operand);
867 // Already folded immediate ?
868 if (isa<ConstantSDNode>(Operand.getNode()) ||
869 isa<ConstantFPSDNode>(Operand.getNode()))
872 // Is this a VSrc or SSrc operand ?
873 unsigned RegClass = Desc->OpInfo[Op].RegClass;
874 if (isVSrc(RegClass) || isSSrc(RegClass)) {
875 // Try to fold the immediates
876 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
877 // Folding didn't worked, make sure we don't hit the SReg limit
878 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
883 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
885 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
886 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
888 // Test if it makes sense to swap operands
889 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
890 (!fitsRegClass(DAG, Ops[1], RegClass) &&
891 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
893 // Swap commutable operands
894 SDValue Tmp = Ops[1];
904 if (DescE64 && !Immediate) {
906 // Test if it makes sense to switch to e64 encoding
907 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
908 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
912 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
913 (!fitsRegClass(DAG, Ops[i], RegClass) &&
914 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
916 // Switch to e64 encoding
926 // Add the modifier flags while promoting
927 for (unsigned i = 0; i < 4; ++i)
928 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
931 // Add optional chain and glue
932 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
933 Ops.push_back(Node->getOperand(i));
935 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
936 // this case a brand new node is always be created, even if the operands
937 // are the same as before. So, manually check if anything has been changed.
938 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
942 // Create a complete new instruction
943 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
946 /// \brief Helper function for adjustWritemask
947 static unsigned SubIdx2Lane(unsigned Idx) {
950 case AMDGPU::sub0: return 0;
951 case AMDGPU::sub1: return 1;
952 case AMDGPU::sub2: return 2;
953 case AMDGPU::sub3: return 3;
957 /// \brief Adjust the writemask of MIMG instructions
958 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
959 SelectionDAG &DAG) const {
960 SDNode *Users[4] = { };
961 unsigned Writemask = 0, Lane = 0;
963 // Try to figure out the used register components
964 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
967 // Abort if we can't understand the usage
968 if (!I->isMachineOpcode() ||
969 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
972 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
974 // Abort if we have more than one user per component
979 Writemask |= 1 << Lane;
982 // Abort if all components are used
983 if (Writemask == 0xf)
986 // Adjust the writemask in the node
987 std::vector<SDValue> Ops;
988 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
989 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
990 Ops.push_back(Node->getOperand(i));
991 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
993 // If we only got one lane, replace it with a copy
994 if (Writemask == (1U << Lane)) {
995 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
996 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
997 SDLoc(), Users[Lane]->getValueType(0),
998 SDValue(Node, 0), RC);
999 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1003 // Update the users of the node with the new indices
1004 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1006 SDNode *User = Users[i];
1010 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1011 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1015 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1016 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1017 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1022 /// \brief Fold the instructions after slecting them
1023 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1024 SelectionDAG &DAG) const {
1025 Node = AdjustRegClass(Node, DAG);
1027 if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
1028 adjustWritemask(Node, DAG);
1030 return foldOperands(Node, DAG);
1033 /// \brief Assign the register class depending on the number of
1034 /// bits set in the writemask
1035 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1036 SDNode *Node) const {
1037 if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
1040 unsigned VReg = MI->getOperand(0).getReg();
1041 unsigned Writemask = MI->getOperand(1).getImm();
1042 unsigned BitsSet = 0;
1043 for (unsigned i = 0; i < 4; ++i)
1044 BitsSet += Writemask & (1 << i) ? 1 : 0;
1046 const TargetRegisterClass *RC;
1049 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1050 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1051 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1054 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1055 MRI.setRegClass(VReg, RC);
1058 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1059 SelectionDAG &DAG) const {
1062 unsigned NewOpcode = N->getMachineOpcode();
1064 switch (N->getMachineOpcode()) {
1066 case AMDGPU::S_LOAD_DWORD_IMM:
1067 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1069 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1070 if (NewOpcode == N->getMachineOpcode()) {
1071 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1074 case AMDGPU::S_LOAD_DWORDX4_IMM:
1075 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1076 if (NewOpcode == N->getMachineOpcode()) {
1077 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1079 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1082 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1084 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1085 DAG.getConstant(0, MVT::i64)), 0),
1087 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1089 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1094 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1095 const TargetRegisterClass *RC,
1096 unsigned Reg, EVT VT) const {
1097 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1099 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1100 cast<RegisterSDNode>(VReg)->getReg(), VT);