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);
69 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
70 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
72 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
74 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
76 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
78 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
80 setTargetDAGCombine(ISD::SELECT_CC);
82 setTargetDAGCombine(ISD::SETCC);
84 setSchedulingPreference(Sched::RegPressure);
87 //===----------------------------------------------------------------------===//
88 // TargetLowering queries
89 //===----------------------------------------------------------------------===//
91 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
93 // XXX: This depends on the address space and also we may want to revist
94 // the alignment values we specify in the DataLayout.
95 return VT.bitsGT(MVT::i32);
99 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
100 SDLoc DL, SDValue Chain,
101 unsigned Offset) const {
102 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
103 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
104 AMDGPUAS::CONSTANT_ADDRESS);
105 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
106 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
107 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
108 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
109 DAG.getConstant(Offset, MVT::i64));
110 return DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
111 MachinePointerInfo(UndefValue::get(PtrTy)),
112 VT, false, false, ArgVT.getSizeInBits() >> 3);
116 SDValue SITargetLowering::LowerFormalArguments(
118 CallingConv::ID CallConv,
120 const SmallVectorImpl<ISD::InputArg> &Ins,
121 SDLoc DL, SelectionDAG &DAG,
122 SmallVectorImpl<SDValue> &InVals) const {
124 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
126 MachineFunction &MF = DAG.getMachineFunction();
127 FunctionType *FType = MF.getFunction()->getFunctionType();
128 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
130 assert(CallConv == CallingConv::C);
132 SmallVector<ISD::InputArg, 16> Splits;
133 uint32_t Skipped = 0;
135 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
136 const ISD::InputArg &Arg = Ins[i];
138 // First check if it's a PS input addr
139 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
141 assert((PSInputNum <= 15) && "Too many PS inputs!");
144 // We can savely skip PS inputs
150 Info->PSInputAddr |= 1 << PSInputNum++;
153 // Second split vertices into their elements
154 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
155 ISD::InputArg NewArg = Arg;
156 NewArg.Flags.setSplit();
157 NewArg.VT = Arg.VT.getVectorElementType();
159 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
160 // three or five element vertex only needs three or five registers,
161 // NOT four or eigth.
162 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
163 unsigned NumElements = ParamType->getVectorNumElements();
165 for (unsigned j = 0; j != NumElements; ++j) {
166 Splits.push_back(NewArg);
167 NewArg.PartOffset += NewArg.VT.getStoreSize();
171 Splits.push_back(Arg);
175 SmallVector<CCValAssign, 16> ArgLocs;
176 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
177 getTargetMachine(), ArgLocs, *DAG.getContext());
179 // At least one interpolation mode must be enabled or else the GPU will hang.
180 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
181 Info->PSInputAddr |= 1;
182 CCInfo.AllocateReg(AMDGPU::VGPR0);
183 CCInfo.AllocateReg(AMDGPU::VGPR1);
186 // The pointer to the list of arguments is stored in SGPR0, SGPR1
187 if (Info->ShaderType == ShaderType::COMPUTE) {
188 CCInfo.AllocateReg(AMDGPU::SGPR0);
189 CCInfo.AllocateReg(AMDGPU::SGPR1);
190 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
193 AnalyzeFormalArguments(CCInfo, Splits);
195 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
197 const ISD::InputArg &Arg = Ins[i];
198 if (Skipped & (1 << i)) {
199 InVals.push_back(DAG.getUNDEF(Arg.VT));
203 CCValAssign &VA = ArgLocs[ArgIdx++];
204 EVT VT = VA.getLocVT();
207 // The first 36 bytes of the input buffer contains information about
208 // thread group and global sizes.
209 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
210 36 + VA.getLocMemOffset());
211 InVals.push_back(Arg);
214 assert(VA.isRegLoc() && "Parameter must be in a register!");
216 unsigned Reg = VA.getLocReg();
218 if (VT == MVT::i64) {
219 // For now assume it is a pointer
220 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
221 &AMDGPU::SReg_64RegClass);
222 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
223 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
227 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
229 Reg = MF.addLiveIn(Reg, RC);
230 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
232 if (Arg.VT.isVector()) {
234 // Build a vector from the registers
235 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
236 unsigned NumElements = ParamType->getVectorNumElements();
238 SmallVector<SDValue, 4> Regs;
240 for (unsigned j = 1; j != NumElements; ++j) {
241 Reg = ArgLocs[ArgIdx++].getLocReg();
242 Reg = MF.addLiveIn(Reg, RC);
243 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
246 // Fill up the missing vector elements
247 NumElements = Arg.VT.getVectorNumElements() - NumElements;
248 for (unsigned j = 0; j != NumElements; ++j)
249 Regs.push_back(DAG.getUNDEF(VT));
251 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
252 Regs.data(), Regs.size()));
256 InVals.push_back(Val);
261 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
262 MachineInstr * MI, MachineBasicBlock * BB) const {
264 MachineBasicBlock::iterator I = *MI;
266 switch (MI->getOpcode()) {
268 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
269 case AMDGPU::BRANCH: return BB;
270 case AMDGPU::SI_ADDR64_RSRC: {
271 const SIInstrInfo *TII =
272 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
273 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
274 unsigned SuperReg = MI->getOperand(0).getReg();
275 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
276 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
277 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
278 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
279 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
280 .addOperand(MI->getOperand(1));
281 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
283 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
284 .addImm(RSRC_DATA_FORMAT >> 32);
285 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
287 .addImm(AMDGPU::sub0)
289 .addImm(AMDGPU::sub1);
290 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
292 .addImm(AMDGPU::sub0_sub1)
294 .addImm(AMDGPU::sub2_sub3);
295 MI->eraseFromParent();
302 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
306 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
310 //===----------------------------------------------------------------------===//
311 // Custom DAG Lowering Operations
312 //===----------------------------------------------------------------------===//
314 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
315 MachineFunction &MF = DAG.getMachineFunction();
316 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
317 switch (Op.getOpcode()) {
318 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
319 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
320 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
321 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
322 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
323 case ISD::INTRINSIC_WO_CHAIN: {
324 unsigned IntrinsicID =
325 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
326 EVT VT = Op.getValueType();
328 //XXX: Hardcoded we only use two to store the pointer to the parameters.
329 unsigned NumUserSGPRs = 2;
330 switch (IntrinsicID) {
331 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
332 case Intrinsic::r600_read_ngroups_x:
333 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
334 case Intrinsic::r600_read_ngroups_y:
335 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
336 case Intrinsic::r600_read_ngroups_z:
337 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
338 case Intrinsic::r600_read_global_size_x:
339 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
340 case Intrinsic::r600_read_global_size_y:
341 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
342 case Intrinsic::r600_read_global_size_z:
343 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
344 case Intrinsic::r600_read_local_size_x:
345 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
346 case Intrinsic::r600_read_local_size_y:
347 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
348 case Intrinsic::r600_read_local_size_z:
349 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
350 case Intrinsic::r600_read_tgid_x:
351 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
352 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
353 case Intrinsic::r600_read_tgid_y:
354 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
355 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
356 case Intrinsic::r600_read_tgid_z:
357 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
358 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
359 case Intrinsic::r600_read_tidig_x:
360 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
362 case Intrinsic::r600_read_tidig_y:
363 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
365 case Intrinsic::r600_read_tidig_z:
366 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
375 /// \brief Helper function for LowerBRCOND
376 static SDNode *findUser(SDValue Value, unsigned Opcode) {
378 SDNode *Parent = Value.getNode();
379 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
382 if (I.getUse().get() != Value)
385 if (I->getOpcode() == Opcode)
391 /// This transforms the control flow intrinsics to get the branch destination as
392 /// last parameter, also switches branch target with BR if the need arise
393 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
394 SelectionDAG &DAG) const {
398 SDNode *Intr = BRCOND.getOperand(1).getNode();
399 SDValue Target = BRCOND.getOperand(2);
402 if (Intr->getOpcode() == ISD::SETCC) {
403 // As long as we negate the condition everything is fine
404 SDNode *SetCC = Intr;
405 assert(SetCC->getConstantOperandVal(1) == 1);
406 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
408 Intr = SetCC->getOperand(0).getNode();
411 // Get the target from BR if we don't negate the condition
412 BR = findUser(BRCOND, ISD::BR);
413 Target = BR->getOperand(1);
416 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
418 // Build the result and
419 SmallVector<EVT, 4> Res;
420 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
421 Res.push_back(Intr->getValueType(i));
423 // operands of the new intrinsic call
424 SmallVector<SDValue, 4> Ops;
425 Ops.push_back(BRCOND.getOperand(0));
426 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
427 Ops.push_back(Intr->getOperand(i));
428 Ops.push_back(Target);
430 // build the new intrinsic call
431 SDNode *Result = DAG.getNode(
432 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
433 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
436 // Give the branch instruction our target
441 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
444 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
446 // Copy the intrinsic results to registers
447 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
448 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
452 Chain = DAG.getCopyToReg(
454 CopyToReg->getOperand(1),
455 SDValue(Result, i - 1),
458 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
461 // Remove the old intrinsic from the chain
462 DAG.ReplaceAllUsesOfValueWith(
463 SDValue(Intr, Intr->getNumValues() - 1),
464 Intr->getOperand(0));
469 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
470 SDValue LHS = Op.getOperand(0);
471 SDValue RHS = Op.getOperand(1);
472 SDValue True = Op.getOperand(2);
473 SDValue False = Op.getOperand(3);
474 SDValue CC = Op.getOperand(4);
475 EVT VT = Op.getValueType();
478 // Possible Min/Max pattern
479 SDValue MinMax = LowerMinMax(Op, DAG);
480 if (MinMax.getNode()) {
484 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
485 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
488 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
489 SelectionDAG &DAG) const {
490 EVT VT = Op.getValueType();
493 if (VT != MVT::i64) {
497 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
498 DAG.getConstant(31, MVT::i32));
500 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
503 //===----------------------------------------------------------------------===//
504 // Custom DAG optimizations
505 //===----------------------------------------------------------------------===//
507 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
508 DAGCombinerInfo &DCI) const {
509 SelectionDAG &DAG = DCI.DAG;
511 EVT VT = N->getValueType(0);
513 switch (N->getOpcode()) {
515 case ISD::SELECT_CC: {
517 ConstantSDNode *True, *False;
518 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
519 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
520 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
521 && True->isAllOnesValue()
522 && False->isNullValue()
524 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
525 N->getOperand(1), N->getOperand(4));
531 SDValue Arg0 = N->getOperand(0);
532 SDValue Arg1 = N->getOperand(1);
533 SDValue CC = N->getOperand(2);
534 ConstantSDNode * C = NULL;
535 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
537 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
539 && Arg0.getOpcode() == ISD::SIGN_EXTEND
540 && Arg0.getOperand(0).getValueType() == MVT::i1
541 && (C = dyn_cast<ConstantSDNode>(Arg1))
543 && CCOp == ISD::SETNE) {
544 return SimplifySetCC(VT, Arg0.getOperand(0),
545 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
553 /// \brief Test if RegClass is one of the VSrc classes
554 static bool isVSrc(unsigned RegClass) {
555 return AMDGPU::VSrc_32RegClassID == RegClass ||
556 AMDGPU::VSrc_64RegClassID == RegClass;
559 /// \brief Test if RegClass is one of the SSrc classes
560 static bool isSSrc(unsigned RegClass) {
561 return AMDGPU::SSrc_32RegClassID == RegClass ||
562 AMDGPU::SSrc_64RegClassID == RegClass;
565 /// \brief Analyze the possible immediate value Op
567 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
568 /// and the immediate value if it's a literal immediate
569 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
576 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
577 if (Node->getZExtValue() >> 32) {
580 Imm.I = Node->getSExtValue();
581 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
582 Imm.F = Node->getValueAPF().convertToFloat();
584 return -1; // It isn't an immediate
586 if ((Imm.I >= -16 && Imm.I <= 64) ||
587 Imm.F == 0.5f || Imm.F == -0.5f ||
588 Imm.F == 1.0f || Imm.F == -1.0f ||
589 Imm.F == 2.0f || Imm.F == -2.0f ||
590 Imm.F == 4.0f || Imm.F == -4.0f)
591 return 0; // It's an inline immediate
593 return Imm.I; // It's a literal immediate
596 /// \brief Try to fold an immediate directly into an instruction
597 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
598 bool &ScalarSlotUsed) const {
600 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
601 const SIInstrInfo *TII =
602 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
603 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
606 const SDValue &Op = Mov->getOperand(0);
607 int32_t Value = analyzeImmediate(Op.getNode());
609 // Not an immediate at all
612 } else if (Value == 0) {
613 // Inline immediates can always be fold
617 } else if (Value == Immediate) {
618 // Already fold literal immediate
622 } else if (!ScalarSlotUsed && !Immediate) {
623 // Fold this literal immediate
624 ScalarSlotUsed = true;
634 /// \brief Does "Op" fit into register class "RegClass" ?
635 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
636 unsigned RegClass) const {
638 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
639 SDNode *Node = Op.getNode();
641 const TargetRegisterClass *OpClass;
642 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
643 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
644 const SIInstrInfo *TII =
645 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
646 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
647 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
648 if (OpClassID == -1) {
649 switch (MN->getMachineOpcode()) {
650 case AMDGPU::REG_SEQUENCE:
651 // Operand 0 is the register class id for REG_SEQUENCE instructions.
652 OpClass = TRI->getRegClass(
653 cast<ConstantSDNode>(MN->getOperand(0))->getZExtValue());
656 OpClass = getRegClassFor(Op.getSimpleValueType());
660 OpClass = TRI->getRegClass(OpClassID);
663 } else if (Node->getOpcode() == ISD::CopyFromReg) {
664 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
665 OpClass = MRI.getRegClass(Reg->getReg());
670 return TRI->getRegClass(RegClass)->hasSubClassEq(OpClass);
673 /// \brief Make sure that we don't exeed the number of allowed scalars
674 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
676 bool &ScalarSlotUsed) const {
678 // First map the operands register class to a destination class
679 if (RegClass == AMDGPU::VSrc_32RegClassID)
680 RegClass = AMDGPU::VReg_32RegClassID;
681 else if (RegClass == AMDGPU::VSrc_64RegClassID)
682 RegClass = AMDGPU::VReg_64RegClassID;
686 // Nothing todo if they fit naturaly
687 if (fitsRegClass(DAG, Operand, RegClass))
690 // If the scalar slot isn't used yet use it now
691 if (!ScalarSlotUsed) {
692 ScalarSlotUsed = true;
696 // This is a conservative aproach, it is possible that we can't determine
697 // the correct register class and copy too often, but better save than sorry.
698 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
699 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
700 Operand.getValueType(), Operand, RC);
701 Operand = SDValue(Node, 0);
704 /// \returns true if \p Node's operands are different from the SDValue list
706 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
707 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
708 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
715 /// \brief Try to fold the Nodes operands into the Node
716 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
717 SelectionDAG &DAG) const {
719 // Original encoding (either e32 or e64)
720 int Opcode = Node->getMachineOpcode();
721 const SIInstrInfo *TII =
722 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
723 const MCInstrDesc *Desc = &TII->get(Opcode);
725 unsigned NumDefs = Desc->getNumDefs();
726 unsigned NumOps = Desc->getNumOperands();
728 // Commuted opcode if available
729 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
730 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
732 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
733 assert(!DescRev || DescRev->getNumOperands() == NumOps);
735 // e64 version if available, -1 otherwise
736 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
737 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
739 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
740 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
742 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
743 bool HaveVSrc = false, HaveSSrc = false;
745 // First figure out what we alread have in this instruction
746 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
747 i != e && Op < NumOps; ++i, ++Op) {
749 unsigned RegClass = Desc->OpInfo[Op].RegClass;
750 if (isVSrc(RegClass))
752 else if (isSSrc(RegClass))
757 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
758 if (Imm != -1 && Imm != 0) {
764 // If we neither have VSrc nor SSrc it makes no sense to continue
765 if (!HaveVSrc && !HaveSSrc)
768 // No scalar allowed when we have both VSrc and SSrc
769 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
771 // Second go over the operands and try to fold them
772 std::vector<SDValue> Ops;
773 bool Promote2e64 = false;
774 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
775 i != e && Op < NumOps; ++i, ++Op) {
777 const SDValue &Operand = Node->getOperand(i);
778 Ops.push_back(Operand);
780 // Already folded immediate ?
781 if (isa<ConstantSDNode>(Operand.getNode()) ||
782 isa<ConstantFPSDNode>(Operand.getNode()))
785 // Is this a VSrc or SSrc operand ?
786 unsigned RegClass = Desc->OpInfo[Op].RegClass;
787 if (isVSrc(RegClass) || isSSrc(RegClass)) {
788 // Try to fold the immediates
789 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
790 // Folding didn't worked, make sure we don't hit the SReg limit
791 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
796 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
798 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
799 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
801 // Test if it makes sense to swap operands
802 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
803 (!fitsRegClass(DAG, Ops[1], RegClass) &&
804 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
806 // Swap commutable operands
807 SDValue Tmp = Ops[1];
817 if (DescE64 && !Immediate) {
819 // Test if it makes sense to switch to e64 encoding
820 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
821 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
825 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
826 (!fitsRegClass(DAG, Ops[i], RegClass) &&
827 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
829 // Switch to e64 encoding
839 // Add the modifier flags while promoting
840 for (unsigned i = 0; i < 4; ++i)
841 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
844 // Add optional chain and glue
845 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
846 Ops.push_back(Node->getOperand(i));
848 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
849 // this case a brand new node is always be created, even if the operands
850 // are the same as before. So, manually check if anything has been changed.
851 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
855 // Create a complete new instruction
856 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
859 /// \brief Helper function for adjustWritemask
860 static unsigned SubIdx2Lane(unsigned Idx) {
863 case AMDGPU::sub0: return 0;
864 case AMDGPU::sub1: return 1;
865 case AMDGPU::sub2: return 2;
866 case AMDGPU::sub3: return 3;
870 /// \brief Adjust the writemask of MIMG instructions
871 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
872 SelectionDAG &DAG) const {
873 SDNode *Users[4] = { };
874 unsigned Writemask = 0, Lane = 0;
876 // Try to figure out the used register components
877 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
880 // Abort if we can't understand the usage
881 if (!I->isMachineOpcode() ||
882 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
885 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
887 // Abort if we have more than one user per component
892 Writemask |= 1 << Lane;
895 // Abort if all components are used
896 if (Writemask == 0xf)
899 // Adjust the writemask in the node
900 std::vector<SDValue> Ops;
901 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
902 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
903 Ops.push_back(Node->getOperand(i));
904 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
906 // If we only got one lane, replace it with a copy
907 if (Writemask == (1U << Lane)) {
908 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
909 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
910 SDLoc(), Users[Lane]->getValueType(0),
911 SDValue(Node, 0), RC);
912 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
916 // Update the users of the node with the new indices
917 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
919 SDNode *User = Users[i];
923 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
924 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
928 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
929 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
930 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
935 /// \brief Fold the instructions after slecting them
936 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
937 SelectionDAG &DAG) const {
938 Node = AdjustRegClass(Node, DAG);
940 if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
941 adjustWritemask(Node, DAG);
943 return foldOperands(Node, DAG);
946 /// \brief Assign the register class depending on the number of
947 /// bits set in the writemask
948 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
949 SDNode *Node) const {
950 if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
953 unsigned VReg = MI->getOperand(0).getReg();
954 unsigned Writemask = MI->getOperand(1).getImm();
955 unsigned BitsSet = 0;
956 for (unsigned i = 0; i < 4; ++i)
957 BitsSet += Writemask & (1 << i) ? 1 : 0;
959 const TargetRegisterClass *RC;
962 case 1: RC = &AMDGPU::VReg_32RegClass; break;
963 case 2: RC = &AMDGPU::VReg_64RegClass; break;
964 case 3: RC = &AMDGPU::VReg_96RegClass; break;
967 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
968 MRI.setRegClass(VReg, RC);
971 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
972 SelectionDAG &DAG) const {
975 unsigned NewOpcode = N->getMachineOpcode();
977 switch (N->getMachineOpcode()) {
979 case AMDGPU::REG_SEQUENCE: {
980 // MVT::i128 only use SGPRs, so i128 REG_SEQUENCEs don't need to be
982 if (N->getValueType(0) == MVT::i128) {
985 const SDValue Ops[] = {
986 DAG.getTargetConstant(AMDGPU::VReg_64RegClassID, MVT::i32),
987 N->getOperand(1) , N->getOperand(2),
988 N->getOperand(3), N->getOperand(4)
990 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::i64, Ops);
993 case AMDGPU::S_LOAD_DWORD_IMM:
994 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
996 case AMDGPU::S_LOAD_DWORDX2_SGPR:
997 if (NewOpcode == N->getMachineOpcode()) {
998 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1001 case AMDGPU::S_LOAD_DWORDX4_IMM:
1002 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1003 if (NewOpcode == N->getMachineOpcode()) {
1004 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1006 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1009 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1011 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1012 DAG.getConstant(0, MVT::i64)), 0),
1014 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1016 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1021 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1022 const TargetRegisterClass *RC,
1023 unsigned Reg, EVT VT) const {
1024 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1026 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1027 cast<RegisterSDNode>(VReg)->getReg(), VT);