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::SReg_64RegClass);
37 addRegisterClass(MVT::v16i8, &AMDGPU::SReg_128RegClass);
38 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
39 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
41 addRegisterClass(MVT::i32, &AMDGPU::VReg_32RegClass);
42 addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
44 addRegisterClass(MVT::v1i32, &AMDGPU::VReg_32RegClass);
46 addRegisterClass(MVT::v2i32, &AMDGPU::VReg_64RegClass);
47 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
49 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
50 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
51 addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
53 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
54 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
56 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
57 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
59 computeRegisterProperties();
61 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
62 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
63 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
64 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
66 setOperationAction(ISD::ADD, MVT::i64, Legal);
67 setOperationAction(ISD::ADD, MVT::i32, Legal);
68 setOperationAction(ISD::ADD, MVT::v4i32, Expand);
69 setOperationAction(ISD::ADD, MVT::v2i32, Expand);
71 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
72 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
74 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
76 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
78 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
80 setTargetDAGCombine(ISD::SELECT_CC);
82 setTargetDAGCombine(ISD::SETCC);
84 setSchedulingPreference(Sched::RegPressure);
87 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
88 SDLoc DL, SDValue Chain,
89 unsigned Offset) const {
90 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
91 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
92 AMDGPUAS::CONSTANT_ADDRESS);
93 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
94 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
95 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
96 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
97 DAG.getConstant(Offset, MVT::i64));
98 return DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
99 MachinePointerInfo(UndefValue::get(PtrTy)),
100 VT, false, false, ArgVT.getSizeInBits() >> 3);
104 SDValue SITargetLowering::LowerFormalArguments(
106 CallingConv::ID CallConv,
108 const SmallVectorImpl<ISD::InputArg> &Ins,
109 SDLoc DL, SelectionDAG &DAG,
110 SmallVectorImpl<SDValue> &InVals) const {
112 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
114 MachineFunction &MF = DAG.getMachineFunction();
115 FunctionType *FType = MF.getFunction()->getFunctionType();
116 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
118 assert(CallConv == CallingConv::C);
120 SmallVector<ISD::InputArg, 16> Splits;
121 uint32_t Skipped = 0;
123 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
124 const ISD::InputArg &Arg = Ins[i];
126 // First check if it's a PS input addr
127 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
129 assert((PSInputNum <= 15) && "Too many PS inputs!");
132 // We can savely skip PS inputs
138 Info->PSInputAddr |= 1 << PSInputNum++;
141 // Second split vertices into their elements
142 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
143 ISD::InputArg NewArg = Arg;
144 NewArg.Flags.setSplit();
145 NewArg.VT = Arg.VT.getVectorElementType();
147 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
148 // three or five element vertex only needs three or five registers,
149 // NOT four or eigth.
150 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
151 unsigned NumElements = ParamType->getVectorNumElements();
153 for (unsigned j = 0; j != NumElements; ++j) {
154 Splits.push_back(NewArg);
155 NewArg.PartOffset += NewArg.VT.getStoreSize();
159 Splits.push_back(Arg);
163 SmallVector<CCValAssign, 16> ArgLocs;
164 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
165 getTargetMachine(), ArgLocs, *DAG.getContext());
167 // At least one interpolation mode must be enabled or else the GPU will hang.
168 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
169 Info->PSInputAddr |= 1;
170 CCInfo.AllocateReg(AMDGPU::VGPR0);
171 CCInfo.AllocateReg(AMDGPU::VGPR1);
174 // The pointer to the list of arguments is stored in SGPR0, SGPR1
175 if (Info->ShaderType == ShaderType::COMPUTE) {
176 CCInfo.AllocateReg(AMDGPU::SGPR0);
177 CCInfo.AllocateReg(AMDGPU::SGPR1);
178 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
181 AnalyzeFormalArguments(CCInfo, Splits);
183 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
185 const ISD::InputArg &Arg = Ins[i];
186 if (Skipped & (1 << i)) {
187 InVals.push_back(DAG.getUNDEF(Arg.VT));
191 CCValAssign &VA = ArgLocs[ArgIdx++];
192 EVT VT = VA.getLocVT();
195 // The first 36 bytes of the input buffer contains information about
196 // thread group and global sizes.
197 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
198 36 + VA.getLocMemOffset());
199 InVals.push_back(Arg);
202 assert(VA.isRegLoc() && "Parameter must be in a register!");
204 unsigned Reg = VA.getLocReg();
206 if (VT == MVT::i64) {
207 // For now assume it is a pointer
208 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
209 &AMDGPU::SReg_64RegClass);
210 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
211 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
215 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
217 Reg = MF.addLiveIn(Reg, RC);
218 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
220 if (Arg.VT.isVector()) {
222 // Build a vector from the registers
223 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
224 unsigned NumElements = ParamType->getVectorNumElements();
226 SmallVector<SDValue, 4> Regs;
228 for (unsigned j = 1; j != NumElements; ++j) {
229 Reg = ArgLocs[ArgIdx++].getLocReg();
230 Reg = MF.addLiveIn(Reg, RC);
231 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
234 // Fill up the missing vector elements
235 NumElements = Arg.VT.getVectorNumElements() - NumElements;
236 for (unsigned j = 0; j != NumElements; ++j)
237 Regs.push_back(DAG.getUNDEF(VT));
239 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
240 Regs.data(), Regs.size()));
244 InVals.push_back(Val);
249 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
250 MachineInstr * MI, MachineBasicBlock * BB) const {
252 MachineBasicBlock::iterator I = *MI;
254 switch (MI->getOpcode()) {
256 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
257 case AMDGPU::BRANCH: return BB;
258 case AMDGPU::SI_ADDR64_RSRC: {
259 const SIInstrInfo *TII =
260 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
261 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
262 unsigned SuperReg = MI->getOperand(0).getReg();
263 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
264 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
265 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
266 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
267 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
268 .addOperand(MI->getOperand(1));
269 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
271 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
272 .addImm(RSRC_DATA_FORMAT >> 32);
273 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
275 .addImm(AMDGPU::sub0)
277 .addImm(AMDGPU::sub1);
278 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
280 .addImm(AMDGPU::sub0_sub1)
282 .addImm(AMDGPU::sub2_sub3);
283 MI->eraseFromParent();
290 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
294 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
298 //===----------------------------------------------------------------------===//
299 // Custom DAG Lowering Operations
300 //===----------------------------------------------------------------------===//
302 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
303 switch (Op.getOpcode()) {
304 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
305 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
306 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
307 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
308 case ISD::INTRINSIC_WO_CHAIN: {
309 unsigned IntrinsicID =
310 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
311 EVT VT = Op.getValueType();
313 //XXX: Hardcoded we only use two to store the pointer to the parameters.
314 unsigned NumUserSGPRs = 2;
315 switch (IntrinsicID) {
316 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
317 case Intrinsic::r600_read_ngroups_x:
318 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
319 case Intrinsic::r600_read_ngroups_y:
320 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
321 case Intrinsic::r600_read_ngroups_z:
322 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
323 case Intrinsic::r600_read_global_size_x:
324 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
325 case Intrinsic::r600_read_global_size_y:
326 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
327 case Intrinsic::r600_read_global_size_z:
328 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
329 case Intrinsic::r600_read_local_size_x:
330 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
331 case Intrinsic::r600_read_local_size_y:
332 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
333 case Intrinsic::r600_read_local_size_z:
334 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
335 case Intrinsic::r600_read_tgid_x:
336 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
337 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
338 case Intrinsic::r600_read_tgid_y:
339 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
340 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
341 case Intrinsic::r600_read_tgid_z:
342 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
343 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
344 case Intrinsic::r600_read_tidig_x:
345 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
347 case Intrinsic::r600_read_tidig_y:
348 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
350 case Intrinsic::r600_read_tidig_z:
351 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
360 /// \brief Helper function for LowerBRCOND
361 static SDNode *findUser(SDValue Value, unsigned Opcode) {
363 SDNode *Parent = Value.getNode();
364 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
367 if (I.getUse().get() != Value)
370 if (I->getOpcode() == Opcode)
376 /// This transforms the control flow intrinsics to get the branch destination as
377 /// last parameter, also switches branch target with BR if the need arise
378 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
379 SelectionDAG &DAG) const {
383 SDNode *Intr = BRCOND.getOperand(1).getNode();
384 SDValue Target = BRCOND.getOperand(2);
387 if (Intr->getOpcode() == ISD::SETCC) {
388 // As long as we negate the condition everything is fine
389 SDNode *SetCC = Intr;
390 assert(SetCC->getConstantOperandVal(1) == 1);
391 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
393 Intr = SetCC->getOperand(0).getNode();
396 // Get the target from BR if we don't negate the condition
397 BR = findUser(BRCOND, ISD::BR);
398 Target = BR->getOperand(1);
401 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
403 // Build the result and
404 SmallVector<EVT, 4> Res;
405 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
406 Res.push_back(Intr->getValueType(i));
408 // operands of the new intrinsic call
409 SmallVector<SDValue, 4> Ops;
410 Ops.push_back(BRCOND.getOperand(0));
411 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
412 Ops.push_back(Intr->getOperand(i));
413 Ops.push_back(Target);
415 // build the new intrinsic call
416 SDNode *Result = DAG.getNode(
417 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
418 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
421 // Give the branch instruction our target
426 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
429 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
431 // Copy the intrinsic results to registers
432 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
433 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
437 Chain = DAG.getCopyToReg(
439 CopyToReg->getOperand(1),
440 SDValue(Result, i - 1),
443 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
446 // Remove the old intrinsic from the chain
447 DAG.ReplaceAllUsesOfValueWith(
448 SDValue(Intr, Intr->getNumValues() - 1),
449 Intr->getOperand(0));
454 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
455 SDValue LHS = Op.getOperand(0);
456 SDValue RHS = Op.getOperand(1);
457 SDValue True = Op.getOperand(2);
458 SDValue False = Op.getOperand(3);
459 SDValue CC = Op.getOperand(4);
460 EVT VT = Op.getValueType();
463 // Possible Min/Max pattern
464 SDValue MinMax = LowerMinMax(Op, DAG);
465 if (MinMax.getNode()) {
469 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
470 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
473 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
474 SelectionDAG &DAG) const {
475 EVT VT = Op.getValueType();
478 if (VT != MVT::i64) {
482 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
483 DAG.getConstant(31, MVT::i32));
485 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
488 //===----------------------------------------------------------------------===//
489 // Custom DAG optimizations
490 //===----------------------------------------------------------------------===//
492 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
493 DAGCombinerInfo &DCI) const {
494 SelectionDAG &DAG = DCI.DAG;
496 EVT VT = N->getValueType(0);
498 switch (N->getOpcode()) {
500 case ISD::SELECT_CC: {
502 ConstantSDNode *True, *False;
503 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
504 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
505 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
506 && True->isAllOnesValue()
507 && False->isNullValue()
509 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
510 N->getOperand(1), N->getOperand(4));
516 SDValue Arg0 = N->getOperand(0);
517 SDValue Arg1 = N->getOperand(1);
518 SDValue CC = N->getOperand(2);
519 ConstantSDNode * C = NULL;
520 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
522 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
524 && Arg0.getOpcode() == ISD::SIGN_EXTEND
525 && Arg0.getOperand(0).getValueType() == MVT::i1
526 && (C = dyn_cast<ConstantSDNode>(Arg1))
528 && CCOp == ISD::SETNE) {
529 return SimplifySetCC(VT, Arg0.getOperand(0),
530 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
538 /// \brief Test if RegClass is one of the VSrc classes
539 static bool isVSrc(unsigned RegClass) {
540 return AMDGPU::VSrc_32RegClassID == RegClass ||
541 AMDGPU::VSrc_64RegClassID == RegClass;
544 /// \brief Test if RegClass is one of the SSrc classes
545 static bool isSSrc(unsigned RegClass) {
546 return AMDGPU::SSrc_32RegClassID == RegClass ||
547 AMDGPU::SSrc_64RegClassID == RegClass;
550 /// \brief Analyze the possible immediate value Op
552 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
553 /// and the immediate value if it's a literal immediate
554 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
561 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
562 if (Node->getZExtValue() >> 32) {
565 Imm.I = Node->getSExtValue();
566 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
567 Imm.F = Node->getValueAPF().convertToFloat();
569 return -1; // It isn't an immediate
571 if ((Imm.I >= -16 && Imm.I <= 64) ||
572 Imm.F == 0.5f || Imm.F == -0.5f ||
573 Imm.F == 1.0f || Imm.F == -1.0f ||
574 Imm.F == 2.0f || Imm.F == -2.0f ||
575 Imm.F == 4.0f || Imm.F == -4.0f)
576 return 0; // It's an inline immediate
578 return Imm.I; // It's a literal immediate
581 /// \brief Try to fold an immediate directly into an instruction
582 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
583 bool &ScalarSlotUsed) const {
585 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
586 const SIInstrInfo *TII =
587 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
588 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
591 const SDValue &Op = Mov->getOperand(0);
592 int32_t Value = analyzeImmediate(Op.getNode());
594 // Not an immediate at all
597 } else if (Value == 0) {
598 // Inline immediates can always be fold
602 } else if (Value == Immediate) {
603 // Already fold literal immediate
607 } else if (!ScalarSlotUsed && !Immediate) {
608 // Fold this literal immediate
609 ScalarSlotUsed = true;
619 /// \brief Does "Op" fit into register class "RegClass" ?
620 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
621 unsigned RegClass) const {
623 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
624 SDNode *Node = Op.getNode();
626 const TargetRegisterClass *OpClass;
627 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
628 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
629 const SIInstrInfo *TII =
630 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
631 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
632 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
633 if (OpClassID == -1) {
634 switch (MN->getMachineOpcode()) {
635 case AMDGPU::REG_SEQUENCE:
636 // Operand 0 is the register class id for REG_SEQUENCE instructions.
637 OpClass = TRI->getRegClass(
638 cast<ConstantSDNode>(MN->getOperand(0))->getZExtValue());
641 OpClass = getRegClassFor(Op.getSimpleValueType());
645 OpClass = TRI->getRegClass(OpClassID);
648 } else if (Node->getOpcode() == ISD::CopyFromReg) {
649 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
650 OpClass = MRI.getRegClass(Reg->getReg());
655 return TRI->getRegClass(RegClass)->hasSubClassEq(OpClass);
658 /// \brief Make sure that we don't exeed the number of allowed scalars
659 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
661 bool &ScalarSlotUsed) const {
663 // First map the operands register class to a destination class
664 if (RegClass == AMDGPU::VSrc_32RegClassID)
665 RegClass = AMDGPU::VReg_32RegClassID;
666 else if (RegClass == AMDGPU::VSrc_64RegClassID)
667 RegClass = AMDGPU::VReg_64RegClassID;
671 // Nothing todo if they fit naturaly
672 if (fitsRegClass(DAG, Operand, RegClass))
675 // If the scalar slot isn't used yet use it now
676 if (!ScalarSlotUsed) {
677 ScalarSlotUsed = true;
681 // This is a conservative aproach, it is possible that we can't determine
682 // the correct register class and copy too often, but better save than sorry.
683 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
684 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
685 Operand.getValueType(), Operand, RC);
686 Operand = SDValue(Node, 0);
689 /// \returns true if \p Node's operands are different from the SDValue list
691 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
692 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
693 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
700 /// \brief Try to fold the Nodes operands into the Node
701 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
702 SelectionDAG &DAG) const {
704 // Original encoding (either e32 or e64)
705 int Opcode = Node->getMachineOpcode();
706 const SIInstrInfo *TII =
707 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
708 const MCInstrDesc *Desc = &TII->get(Opcode);
710 unsigned NumDefs = Desc->getNumDefs();
711 unsigned NumOps = Desc->getNumOperands();
713 // Commuted opcode if available
714 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
715 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
717 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
718 assert(!DescRev || DescRev->getNumOperands() == NumOps);
720 // e64 version if available, -1 otherwise
721 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
722 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
724 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
725 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
727 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
728 bool HaveVSrc = false, HaveSSrc = false;
730 // First figure out what we alread have in this instruction
731 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
732 i != e && Op < NumOps; ++i, ++Op) {
734 unsigned RegClass = Desc->OpInfo[Op].RegClass;
735 if (isVSrc(RegClass))
737 else if (isSSrc(RegClass))
742 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
743 if (Imm != -1 && Imm != 0) {
749 // If we neither have VSrc nor SSrc it makes no sense to continue
750 if (!HaveVSrc && !HaveSSrc)
753 // No scalar allowed when we have both VSrc and SSrc
754 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
756 // Second go over the operands and try to fold them
757 std::vector<SDValue> Ops;
758 bool Promote2e64 = false;
759 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
760 i != e && Op < NumOps; ++i, ++Op) {
762 const SDValue &Operand = Node->getOperand(i);
763 Ops.push_back(Operand);
765 // Already folded immediate ?
766 if (isa<ConstantSDNode>(Operand.getNode()) ||
767 isa<ConstantFPSDNode>(Operand.getNode()))
770 // Is this a VSrc or SSrc operand ?
771 unsigned RegClass = Desc->OpInfo[Op].RegClass;
772 if (isVSrc(RegClass) || isSSrc(RegClass)) {
773 // Try to fold the immediates
774 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
775 // Folding didn't worked, make sure we don't hit the SReg limit
776 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
781 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
783 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
784 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
786 // Test if it makes sense to swap operands
787 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
788 (!fitsRegClass(DAG, Ops[1], RegClass) &&
789 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
791 // Swap commutable operands
792 SDValue Tmp = Ops[1];
802 if (DescE64 && !Immediate) {
804 // Test if it makes sense to switch to e64 encoding
805 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
806 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
810 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
811 (!fitsRegClass(DAG, Ops[i], RegClass) &&
812 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
814 // Switch to e64 encoding
824 // Add the modifier flags while promoting
825 for (unsigned i = 0; i < 4; ++i)
826 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
829 // Add optional chain and glue
830 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
831 Ops.push_back(Node->getOperand(i));
833 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
834 // this case a brand new node is always be created, even if the operands
835 // are the same as before. So, manually check if anything has been changed.
836 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
840 // Create a complete new instruction
841 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
844 /// \brief Helper function for adjustWritemask
845 static unsigned SubIdx2Lane(unsigned Idx) {
848 case AMDGPU::sub0: return 0;
849 case AMDGPU::sub1: return 1;
850 case AMDGPU::sub2: return 2;
851 case AMDGPU::sub3: return 3;
855 /// \brief Adjust the writemask of MIMG instructions
856 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
857 SelectionDAG &DAG) const {
858 SDNode *Users[4] = { };
859 unsigned Writemask = 0, Lane = 0;
861 // Try to figure out the used register components
862 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
865 // Abort if we can't understand the usage
866 if (!I->isMachineOpcode() ||
867 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
870 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
872 // Abort if we have more than one user per component
877 Writemask |= 1 << Lane;
880 // Abort if all components are used
881 if (Writemask == 0xf)
884 // Adjust the writemask in the node
885 std::vector<SDValue> Ops;
886 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
887 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
888 Ops.push_back(Node->getOperand(i));
889 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
891 // If we only got one lane, replace it with a copy
892 if (Writemask == (1U << Lane)) {
893 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
894 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
895 SDLoc(), Users[Lane]->getValueType(0),
896 SDValue(Node, 0), RC);
897 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
901 // Update the users of the node with the new indices
902 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
904 SDNode *User = Users[i];
908 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
909 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
913 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
914 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
915 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
920 /// \brief Fold the instructions after slecting them
921 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
922 SelectionDAG &DAG) const {
923 Node = AdjustRegClass(Node, DAG);
925 if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
926 adjustWritemask(Node, DAG);
928 return foldOperands(Node, DAG);
931 /// \brief Assign the register class depending on the number of
932 /// bits set in the writemask
933 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
934 SDNode *Node) const {
935 if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
938 unsigned VReg = MI->getOperand(0).getReg();
939 unsigned Writemask = MI->getOperand(1).getImm();
940 unsigned BitsSet = 0;
941 for (unsigned i = 0; i < 4; ++i)
942 BitsSet += Writemask & (1 << i) ? 1 : 0;
944 const TargetRegisterClass *RC;
947 case 1: RC = &AMDGPU::VReg_32RegClass; break;
948 case 2: RC = &AMDGPU::VReg_64RegClass; break;
949 case 3: RC = &AMDGPU::VReg_96RegClass; break;
952 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
953 MRI.setRegClass(VReg, RC);
956 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
957 SelectionDAG &DAG) const {
960 unsigned NewOpcode = N->getMachineOpcode();
962 switch (N->getMachineOpcode()) {
964 case AMDGPU::REG_SEQUENCE: {
965 // MVT::i128 only use SGPRs, so i128 REG_SEQUENCEs don't need to be
967 if (N->getValueType(0) == MVT::i128) {
970 const SDValue Ops[] = {
971 DAG.getTargetConstant(AMDGPU::VReg_64RegClassID, MVT::i32),
972 N->getOperand(1) , N->getOperand(2),
973 N->getOperand(3), N->getOperand(4)
975 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::i64, Ops);
978 case AMDGPU::S_LOAD_DWORD_IMM:
979 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
981 case AMDGPU::S_LOAD_DWORDX2_SGPR:
982 if (NewOpcode == N->getMachineOpcode()) {
983 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
986 case AMDGPU::S_LOAD_DWORDX4_IMM:
987 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
988 if (NewOpcode == N->getMachineOpcode()) {
989 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
991 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
994 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
996 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
997 DAG.getConstant(0, MVT::i64)), 0),
999 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1001 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1006 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1007 const TargetRegisterClass *RC,
1008 unsigned Reg, EVT VT) const {
1009 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1011 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1012 cast<RegisterSDNode>(VReg)->getReg(), VT);