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::AND, MVT::v2i32, Expand);
72 setOperationAction(ISD::AND, MVT::v4i32, Expand);
74 setOperationAction(ISD::MUL, MVT::v2i32, Expand);
75 setOperationAction(ISD::MUL, MVT::v4i32, Expand);
77 setOperationAction(ISD::SUB, MVT::v2i32, Expand);
78 setOperationAction(ISD::SUB, MVT::v4i32, Expand);
80 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
81 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
83 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
85 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
87 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
89 setTargetDAGCombine(ISD::SELECT_CC);
91 setTargetDAGCombine(ISD::SETCC);
93 setSchedulingPreference(Sched::RegPressure);
96 //===----------------------------------------------------------------------===//
97 // TargetLowering queries
98 //===----------------------------------------------------------------------===//
100 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
101 bool *IsFast) const {
102 // XXX: This depends on the address space and also we may want to revist
103 // the alignment values we specify in the DataLayout.
104 return VT.bitsGT(MVT::i32);
108 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
109 SDLoc DL, SDValue Chain,
110 unsigned Offset) const {
111 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
112 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
113 AMDGPUAS::CONSTANT_ADDRESS);
114 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
115 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
116 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
117 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
118 DAG.getConstant(Offset, MVT::i64));
119 return DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
120 MachinePointerInfo(UndefValue::get(PtrTy)),
121 VT, false, false, ArgVT.getSizeInBits() >> 3);
125 SDValue SITargetLowering::LowerFormalArguments(
127 CallingConv::ID CallConv,
129 const SmallVectorImpl<ISD::InputArg> &Ins,
130 SDLoc DL, SelectionDAG &DAG,
131 SmallVectorImpl<SDValue> &InVals) const {
133 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
135 MachineFunction &MF = DAG.getMachineFunction();
136 FunctionType *FType = MF.getFunction()->getFunctionType();
137 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
139 assert(CallConv == CallingConv::C);
141 SmallVector<ISD::InputArg, 16> Splits;
142 uint32_t Skipped = 0;
144 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
145 const ISD::InputArg &Arg = Ins[i];
147 // First check if it's a PS input addr
148 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
150 assert((PSInputNum <= 15) && "Too many PS inputs!");
153 // We can savely skip PS inputs
159 Info->PSInputAddr |= 1 << PSInputNum++;
162 // Second split vertices into their elements
163 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
164 ISD::InputArg NewArg = Arg;
165 NewArg.Flags.setSplit();
166 NewArg.VT = Arg.VT.getVectorElementType();
168 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
169 // three or five element vertex only needs three or five registers,
170 // NOT four or eigth.
171 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
172 unsigned NumElements = ParamType->getVectorNumElements();
174 for (unsigned j = 0; j != NumElements; ++j) {
175 Splits.push_back(NewArg);
176 NewArg.PartOffset += NewArg.VT.getStoreSize();
180 Splits.push_back(Arg);
184 SmallVector<CCValAssign, 16> ArgLocs;
185 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
186 getTargetMachine(), ArgLocs, *DAG.getContext());
188 // At least one interpolation mode must be enabled or else the GPU will hang.
189 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
190 Info->PSInputAddr |= 1;
191 CCInfo.AllocateReg(AMDGPU::VGPR0);
192 CCInfo.AllocateReg(AMDGPU::VGPR1);
195 // The pointer to the list of arguments is stored in SGPR0, SGPR1
196 if (Info->ShaderType == ShaderType::COMPUTE) {
197 CCInfo.AllocateReg(AMDGPU::SGPR0);
198 CCInfo.AllocateReg(AMDGPU::SGPR1);
199 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
202 AnalyzeFormalArguments(CCInfo, Splits);
204 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
206 const ISD::InputArg &Arg = Ins[i];
207 if (Skipped & (1 << i)) {
208 InVals.push_back(DAG.getUNDEF(Arg.VT));
212 CCValAssign &VA = ArgLocs[ArgIdx++];
213 EVT VT = VA.getLocVT();
216 // The first 36 bytes of the input buffer contains information about
217 // thread group and global sizes.
218 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
219 36 + VA.getLocMemOffset());
220 InVals.push_back(Arg);
223 assert(VA.isRegLoc() && "Parameter must be in a register!");
225 unsigned Reg = VA.getLocReg();
227 if (VT == MVT::i64) {
228 // For now assume it is a pointer
229 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
230 &AMDGPU::SReg_64RegClass);
231 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
232 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
236 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
238 Reg = MF.addLiveIn(Reg, RC);
239 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
241 if (Arg.VT.isVector()) {
243 // Build a vector from the registers
244 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
245 unsigned NumElements = ParamType->getVectorNumElements();
247 SmallVector<SDValue, 4> Regs;
249 for (unsigned j = 1; j != NumElements; ++j) {
250 Reg = ArgLocs[ArgIdx++].getLocReg();
251 Reg = MF.addLiveIn(Reg, RC);
252 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
255 // Fill up the missing vector elements
256 NumElements = Arg.VT.getVectorNumElements() - NumElements;
257 for (unsigned j = 0; j != NumElements; ++j)
258 Regs.push_back(DAG.getUNDEF(VT));
260 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
261 Regs.data(), Regs.size()));
265 InVals.push_back(Val);
270 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
271 MachineInstr * MI, MachineBasicBlock * BB) const {
273 MachineBasicBlock::iterator I = *MI;
275 switch (MI->getOpcode()) {
277 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
278 case AMDGPU::BRANCH: return BB;
279 case AMDGPU::SI_ADDR64_RSRC: {
280 const SIInstrInfo *TII =
281 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
282 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
283 unsigned SuperReg = MI->getOperand(0).getReg();
284 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
285 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
286 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
287 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
288 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
289 .addOperand(MI->getOperand(1));
290 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
292 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
293 .addImm(RSRC_DATA_FORMAT >> 32);
294 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
296 .addImm(AMDGPU::sub0)
298 .addImm(AMDGPU::sub1);
299 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
301 .addImm(AMDGPU::sub0_sub1)
303 .addImm(AMDGPU::sub2_sub3);
304 MI->eraseFromParent();
311 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
315 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
319 //===----------------------------------------------------------------------===//
320 // Custom DAG Lowering Operations
321 //===----------------------------------------------------------------------===//
323 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
324 switch (Op.getOpcode()) {
325 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
326 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
327 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
328 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
329 case ISD::INTRINSIC_WO_CHAIN: {
330 unsigned IntrinsicID =
331 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
332 EVT VT = Op.getValueType();
334 //XXX: Hardcoded we only use two to store the pointer to the parameters.
335 unsigned NumUserSGPRs = 2;
336 switch (IntrinsicID) {
337 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
338 case Intrinsic::r600_read_ngroups_x:
339 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
340 case Intrinsic::r600_read_ngroups_y:
341 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
342 case Intrinsic::r600_read_ngroups_z:
343 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
344 case Intrinsic::r600_read_global_size_x:
345 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
346 case Intrinsic::r600_read_global_size_y:
347 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
348 case Intrinsic::r600_read_global_size_z:
349 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
350 case Intrinsic::r600_read_local_size_x:
351 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
352 case Intrinsic::r600_read_local_size_y:
353 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
354 case Intrinsic::r600_read_local_size_z:
355 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
356 case Intrinsic::r600_read_tgid_x:
357 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
358 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
359 case Intrinsic::r600_read_tgid_y:
360 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
361 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
362 case Intrinsic::r600_read_tgid_z:
363 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
364 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
365 case Intrinsic::r600_read_tidig_x:
366 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
368 case Intrinsic::r600_read_tidig_y:
369 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
371 case Intrinsic::r600_read_tidig_z:
372 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
381 /// \brief Helper function for LowerBRCOND
382 static SDNode *findUser(SDValue Value, unsigned Opcode) {
384 SDNode *Parent = Value.getNode();
385 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
388 if (I.getUse().get() != Value)
391 if (I->getOpcode() == Opcode)
397 /// This transforms the control flow intrinsics to get the branch destination as
398 /// last parameter, also switches branch target with BR if the need arise
399 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
400 SelectionDAG &DAG) const {
404 SDNode *Intr = BRCOND.getOperand(1).getNode();
405 SDValue Target = BRCOND.getOperand(2);
408 if (Intr->getOpcode() == ISD::SETCC) {
409 // As long as we negate the condition everything is fine
410 SDNode *SetCC = Intr;
411 assert(SetCC->getConstantOperandVal(1) == 1);
412 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
414 Intr = SetCC->getOperand(0).getNode();
417 // Get the target from BR if we don't negate the condition
418 BR = findUser(BRCOND, ISD::BR);
419 Target = BR->getOperand(1);
422 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
424 // Build the result and
425 SmallVector<EVT, 4> Res;
426 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
427 Res.push_back(Intr->getValueType(i));
429 // operands of the new intrinsic call
430 SmallVector<SDValue, 4> Ops;
431 Ops.push_back(BRCOND.getOperand(0));
432 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
433 Ops.push_back(Intr->getOperand(i));
434 Ops.push_back(Target);
436 // build the new intrinsic call
437 SDNode *Result = DAG.getNode(
438 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
439 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
442 // Give the branch instruction our target
447 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
450 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
452 // Copy the intrinsic results to registers
453 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
454 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
458 Chain = DAG.getCopyToReg(
460 CopyToReg->getOperand(1),
461 SDValue(Result, i - 1),
464 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
467 // Remove the old intrinsic from the chain
468 DAG.ReplaceAllUsesOfValueWith(
469 SDValue(Intr, Intr->getNumValues() - 1),
470 Intr->getOperand(0));
475 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
476 SDValue LHS = Op.getOperand(0);
477 SDValue RHS = Op.getOperand(1);
478 SDValue True = Op.getOperand(2);
479 SDValue False = Op.getOperand(3);
480 SDValue CC = Op.getOperand(4);
481 EVT VT = Op.getValueType();
484 // Possible Min/Max pattern
485 SDValue MinMax = LowerMinMax(Op, DAG);
486 if (MinMax.getNode()) {
490 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
491 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
494 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
495 SelectionDAG &DAG) const {
496 EVT VT = Op.getValueType();
499 if (VT != MVT::i64) {
503 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
504 DAG.getConstant(31, MVT::i32));
506 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
509 //===----------------------------------------------------------------------===//
510 // Custom DAG optimizations
511 //===----------------------------------------------------------------------===//
513 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
514 DAGCombinerInfo &DCI) const {
515 SelectionDAG &DAG = DCI.DAG;
517 EVT VT = N->getValueType(0);
519 switch (N->getOpcode()) {
521 case ISD::SELECT_CC: {
523 ConstantSDNode *True, *False;
524 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
525 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
526 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
527 && True->isAllOnesValue()
528 && False->isNullValue()
530 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
531 N->getOperand(1), N->getOperand(4));
537 SDValue Arg0 = N->getOperand(0);
538 SDValue Arg1 = N->getOperand(1);
539 SDValue CC = N->getOperand(2);
540 ConstantSDNode * C = NULL;
541 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
543 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
545 && Arg0.getOpcode() == ISD::SIGN_EXTEND
546 && Arg0.getOperand(0).getValueType() == MVT::i1
547 && (C = dyn_cast<ConstantSDNode>(Arg1))
549 && CCOp == ISD::SETNE) {
550 return SimplifySetCC(VT, Arg0.getOperand(0),
551 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
559 /// \brief Test if RegClass is one of the VSrc classes
560 static bool isVSrc(unsigned RegClass) {
561 return AMDGPU::VSrc_32RegClassID == RegClass ||
562 AMDGPU::VSrc_64RegClassID == RegClass;
565 /// \brief Test if RegClass is one of the SSrc classes
566 static bool isSSrc(unsigned RegClass) {
567 return AMDGPU::SSrc_32RegClassID == RegClass ||
568 AMDGPU::SSrc_64RegClassID == RegClass;
571 /// \brief Analyze the possible immediate value Op
573 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
574 /// and the immediate value if it's a literal immediate
575 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
582 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
583 if (Node->getZExtValue() >> 32) {
586 Imm.I = Node->getSExtValue();
587 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
588 Imm.F = Node->getValueAPF().convertToFloat();
590 return -1; // It isn't an immediate
592 if ((Imm.I >= -16 && Imm.I <= 64) ||
593 Imm.F == 0.5f || Imm.F == -0.5f ||
594 Imm.F == 1.0f || Imm.F == -1.0f ||
595 Imm.F == 2.0f || Imm.F == -2.0f ||
596 Imm.F == 4.0f || Imm.F == -4.0f)
597 return 0; // It's an inline immediate
599 return Imm.I; // It's a literal immediate
602 /// \brief Try to fold an immediate directly into an instruction
603 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
604 bool &ScalarSlotUsed) const {
606 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
607 const SIInstrInfo *TII =
608 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
609 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
612 const SDValue &Op = Mov->getOperand(0);
613 int32_t Value = analyzeImmediate(Op.getNode());
615 // Not an immediate at all
618 } else if (Value == 0) {
619 // Inline immediates can always be fold
623 } else if (Value == Immediate) {
624 // Already fold literal immediate
628 } else if (!ScalarSlotUsed && !Immediate) {
629 // Fold this literal immediate
630 ScalarSlotUsed = true;
640 /// \brief Does "Op" fit into register class "RegClass" ?
641 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
642 unsigned RegClass) const {
644 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
645 SDNode *Node = Op.getNode();
647 const TargetRegisterClass *OpClass;
648 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
649 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
650 const SIInstrInfo *TII =
651 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
652 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
653 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
654 if (OpClassID == -1) {
655 switch (MN->getMachineOpcode()) {
656 case AMDGPU::REG_SEQUENCE:
657 // Operand 0 is the register class id for REG_SEQUENCE instructions.
658 OpClass = TRI->getRegClass(
659 cast<ConstantSDNode>(MN->getOperand(0))->getZExtValue());
662 OpClass = getRegClassFor(Op.getSimpleValueType());
666 OpClass = TRI->getRegClass(OpClassID);
669 } else if (Node->getOpcode() == ISD::CopyFromReg) {
670 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
671 OpClass = MRI.getRegClass(Reg->getReg());
676 return TRI->getRegClass(RegClass)->hasSubClassEq(OpClass);
679 /// \brief Make sure that we don't exeed the number of allowed scalars
680 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
682 bool &ScalarSlotUsed) const {
684 // First map the operands register class to a destination class
685 if (RegClass == AMDGPU::VSrc_32RegClassID)
686 RegClass = AMDGPU::VReg_32RegClassID;
687 else if (RegClass == AMDGPU::VSrc_64RegClassID)
688 RegClass = AMDGPU::VReg_64RegClassID;
692 // Nothing todo if they fit naturaly
693 if (fitsRegClass(DAG, Operand, RegClass))
696 // If the scalar slot isn't used yet use it now
697 if (!ScalarSlotUsed) {
698 ScalarSlotUsed = true;
702 // This is a conservative aproach, it is possible that we can't determine
703 // the correct register class and copy too often, but better save than sorry.
704 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
705 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
706 Operand.getValueType(), Operand, RC);
707 Operand = SDValue(Node, 0);
710 /// \returns true if \p Node's operands are different from the SDValue list
712 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
713 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
714 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
721 /// \brief Try to fold the Nodes operands into the Node
722 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
723 SelectionDAG &DAG) const {
725 // Original encoding (either e32 or e64)
726 int Opcode = Node->getMachineOpcode();
727 const SIInstrInfo *TII =
728 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
729 const MCInstrDesc *Desc = &TII->get(Opcode);
731 unsigned NumDefs = Desc->getNumDefs();
732 unsigned NumOps = Desc->getNumOperands();
734 // Commuted opcode if available
735 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
736 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
738 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
739 assert(!DescRev || DescRev->getNumOperands() == NumOps);
741 // e64 version if available, -1 otherwise
742 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
743 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
745 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
746 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
748 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
749 bool HaveVSrc = false, HaveSSrc = false;
751 // First figure out what we alread have in this instruction
752 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
753 i != e && Op < NumOps; ++i, ++Op) {
755 unsigned RegClass = Desc->OpInfo[Op].RegClass;
756 if (isVSrc(RegClass))
758 else if (isSSrc(RegClass))
763 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
764 if (Imm != -1 && Imm != 0) {
770 // If we neither have VSrc nor SSrc it makes no sense to continue
771 if (!HaveVSrc && !HaveSSrc)
774 // No scalar allowed when we have both VSrc and SSrc
775 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
777 // Second go over the operands and try to fold them
778 std::vector<SDValue> Ops;
779 bool Promote2e64 = false;
780 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
781 i != e && Op < NumOps; ++i, ++Op) {
783 const SDValue &Operand = Node->getOperand(i);
784 Ops.push_back(Operand);
786 // Already folded immediate ?
787 if (isa<ConstantSDNode>(Operand.getNode()) ||
788 isa<ConstantFPSDNode>(Operand.getNode()))
791 // Is this a VSrc or SSrc operand ?
792 unsigned RegClass = Desc->OpInfo[Op].RegClass;
793 if (isVSrc(RegClass) || isSSrc(RegClass)) {
794 // Try to fold the immediates
795 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
796 // Folding didn't worked, make sure we don't hit the SReg limit
797 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
802 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
804 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
805 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
807 // Test if it makes sense to swap operands
808 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
809 (!fitsRegClass(DAG, Ops[1], RegClass) &&
810 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
812 // Swap commutable operands
813 SDValue Tmp = Ops[1];
823 if (DescE64 && !Immediate) {
825 // Test if it makes sense to switch to e64 encoding
826 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
827 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
831 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
832 (!fitsRegClass(DAG, Ops[i], RegClass) &&
833 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
835 // Switch to e64 encoding
845 // Add the modifier flags while promoting
846 for (unsigned i = 0; i < 4; ++i)
847 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
850 // Add optional chain and glue
851 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
852 Ops.push_back(Node->getOperand(i));
854 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
855 // this case a brand new node is always be created, even if the operands
856 // are the same as before. So, manually check if anything has been changed.
857 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
861 // Create a complete new instruction
862 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
865 /// \brief Helper function for adjustWritemask
866 static unsigned SubIdx2Lane(unsigned Idx) {
869 case AMDGPU::sub0: return 0;
870 case AMDGPU::sub1: return 1;
871 case AMDGPU::sub2: return 2;
872 case AMDGPU::sub3: return 3;
876 /// \brief Adjust the writemask of MIMG instructions
877 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
878 SelectionDAG &DAG) const {
879 SDNode *Users[4] = { };
880 unsigned Writemask = 0, Lane = 0;
882 // Try to figure out the used register components
883 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
886 // Abort if we can't understand the usage
887 if (!I->isMachineOpcode() ||
888 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
891 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
893 // Abort if we have more than one user per component
898 Writemask |= 1 << Lane;
901 // Abort if all components are used
902 if (Writemask == 0xf)
905 // Adjust the writemask in the node
906 std::vector<SDValue> Ops;
907 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
908 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
909 Ops.push_back(Node->getOperand(i));
910 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
912 // If we only got one lane, replace it with a copy
913 if (Writemask == (1U << Lane)) {
914 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
915 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
916 SDLoc(), Users[Lane]->getValueType(0),
917 SDValue(Node, 0), RC);
918 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
922 // Update the users of the node with the new indices
923 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
925 SDNode *User = Users[i];
929 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
930 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
934 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
935 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
936 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
941 /// \brief Fold the instructions after slecting them
942 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
943 SelectionDAG &DAG) const {
944 Node = AdjustRegClass(Node, DAG);
946 if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
947 adjustWritemask(Node, DAG);
949 return foldOperands(Node, DAG);
952 /// \brief Assign the register class depending on the number of
953 /// bits set in the writemask
954 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
955 SDNode *Node) const {
956 if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
959 unsigned VReg = MI->getOperand(0).getReg();
960 unsigned Writemask = MI->getOperand(1).getImm();
961 unsigned BitsSet = 0;
962 for (unsigned i = 0; i < 4; ++i)
963 BitsSet += Writemask & (1 << i) ? 1 : 0;
965 const TargetRegisterClass *RC;
968 case 1: RC = &AMDGPU::VReg_32RegClass; break;
969 case 2: RC = &AMDGPU::VReg_64RegClass; break;
970 case 3: RC = &AMDGPU::VReg_96RegClass; break;
973 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
974 MRI.setRegClass(VReg, RC);
977 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
978 SelectionDAG &DAG) const {
981 unsigned NewOpcode = N->getMachineOpcode();
983 switch (N->getMachineOpcode()) {
985 case AMDGPU::REG_SEQUENCE: {
986 // MVT::i128 only use SGPRs, so i128 REG_SEQUENCEs don't need to be
988 if (N->getValueType(0) == MVT::i128) {
991 const SDValue Ops[] = {
992 DAG.getTargetConstant(AMDGPU::VReg_64RegClassID, MVT::i32),
993 N->getOperand(1) , N->getOperand(2),
994 N->getOperand(3), N->getOperand(4)
996 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::i64, Ops);
999 case AMDGPU::S_LOAD_DWORD_IMM:
1000 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1002 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1003 if (NewOpcode == N->getMachineOpcode()) {
1004 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1007 case AMDGPU::S_LOAD_DWORDX4_IMM:
1008 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1009 if (NewOpcode == N->getMachineOpcode()) {
1010 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1012 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1015 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1017 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1018 DAG.getConstant(0, MVT::i64)), 0),
1020 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1022 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1027 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1028 const TargetRegisterClass *RC,
1029 unsigned Reg, EVT VT) const {
1030 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1032 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1033 cast<RegisterSDNode>(VReg)->getReg(), VT);