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::OR, MVT::v2i32, Expand);
78 setOperationAction(ISD::OR, MVT::v4i32, Expand);
80 setOperationAction(ISD::SHL, MVT::v2i32, Expand);
81 setOperationAction(ISD::SHL, MVT::v4i32, Expand);
82 setOperationAction(ISD::SRL, MVT::v4i32, Expand);
83 setOperationAction(ISD::SRL, MVT::v2i32, Expand);
84 setOperationAction(ISD::SRA, MVT::v4i32, Expand);
85 setOperationAction(ISD::SRA, MVT::v2i32, Expand);
87 setOperationAction(ISD::SUB, MVT::v2i32, Expand);
88 setOperationAction(ISD::SUB, MVT::v4i32, Expand);
90 setOperationAction(ISD::UDIV, MVT::v2i32, Expand);
91 setOperationAction(ISD::UDIV, MVT::v4i32, Expand);
93 setOperationAction(ISD::UREM, MVT::v2i32, Expand);
94 setOperationAction(ISD::UREM, MVT::v4i32, Expand);
96 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
97 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
99 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
101 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
103 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
105 setTargetDAGCombine(ISD::SELECT_CC);
107 setTargetDAGCombine(ISD::SETCC);
109 setSchedulingPreference(Sched::RegPressure);
112 //===----------------------------------------------------------------------===//
113 // TargetLowering queries
114 //===----------------------------------------------------------------------===//
116 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
117 bool *IsFast) const {
118 // XXX: This depends on the address space and also we may want to revist
119 // the alignment values we specify in the DataLayout.
120 return VT.bitsGT(MVT::i32);
124 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
125 SDLoc DL, SDValue Chain,
126 unsigned Offset) const {
127 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
128 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
129 AMDGPUAS::CONSTANT_ADDRESS);
130 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
131 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
132 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
133 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
134 DAG.getConstant(Offset, MVT::i64));
135 return DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
136 MachinePointerInfo(UndefValue::get(PtrTy)),
137 VT, false, false, ArgVT.getSizeInBits() >> 3);
141 SDValue SITargetLowering::LowerFormalArguments(
143 CallingConv::ID CallConv,
145 const SmallVectorImpl<ISD::InputArg> &Ins,
146 SDLoc DL, SelectionDAG &DAG,
147 SmallVectorImpl<SDValue> &InVals) const {
149 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
151 MachineFunction &MF = DAG.getMachineFunction();
152 FunctionType *FType = MF.getFunction()->getFunctionType();
153 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
155 assert(CallConv == CallingConv::C);
157 SmallVector<ISD::InputArg, 16> Splits;
158 uint32_t Skipped = 0;
160 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
161 const ISD::InputArg &Arg = Ins[i];
163 // First check if it's a PS input addr
164 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
166 assert((PSInputNum <= 15) && "Too many PS inputs!");
169 // We can savely skip PS inputs
175 Info->PSInputAddr |= 1 << PSInputNum++;
178 // Second split vertices into their elements
179 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
180 ISD::InputArg NewArg = Arg;
181 NewArg.Flags.setSplit();
182 NewArg.VT = Arg.VT.getVectorElementType();
184 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
185 // three or five element vertex only needs three or five registers,
186 // NOT four or eigth.
187 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
188 unsigned NumElements = ParamType->getVectorNumElements();
190 for (unsigned j = 0; j != NumElements; ++j) {
191 Splits.push_back(NewArg);
192 NewArg.PartOffset += NewArg.VT.getStoreSize();
196 Splits.push_back(Arg);
200 SmallVector<CCValAssign, 16> ArgLocs;
201 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
202 getTargetMachine(), ArgLocs, *DAG.getContext());
204 // At least one interpolation mode must be enabled or else the GPU will hang.
205 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
206 Info->PSInputAddr |= 1;
207 CCInfo.AllocateReg(AMDGPU::VGPR0);
208 CCInfo.AllocateReg(AMDGPU::VGPR1);
211 // The pointer to the list of arguments is stored in SGPR0, SGPR1
212 if (Info->ShaderType == ShaderType::COMPUTE) {
213 CCInfo.AllocateReg(AMDGPU::SGPR0);
214 CCInfo.AllocateReg(AMDGPU::SGPR1);
215 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
218 AnalyzeFormalArguments(CCInfo, Splits);
220 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
222 const ISD::InputArg &Arg = Ins[i];
223 if (Skipped & (1 << i)) {
224 InVals.push_back(DAG.getUNDEF(Arg.VT));
228 CCValAssign &VA = ArgLocs[ArgIdx++];
229 EVT VT = VA.getLocVT();
232 // The first 36 bytes of the input buffer contains information about
233 // thread group and global sizes.
234 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
235 36 + VA.getLocMemOffset());
236 InVals.push_back(Arg);
239 assert(VA.isRegLoc() && "Parameter must be in a register!");
241 unsigned Reg = VA.getLocReg();
243 if (VT == MVT::i64) {
244 // For now assume it is a pointer
245 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
246 &AMDGPU::SReg_64RegClass);
247 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
248 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
252 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
254 Reg = MF.addLiveIn(Reg, RC);
255 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
257 if (Arg.VT.isVector()) {
259 // Build a vector from the registers
260 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
261 unsigned NumElements = ParamType->getVectorNumElements();
263 SmallVector<SDValue, 4> Regs;
265 for (unsigned j = 1; j != NumElements; ++j) {
266 Reg = ArgLocs[ArgIdx++].getLocReg();
267 Reg = MF.addLiveIn(Reg, RC);
268 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
271 // Fill up the missing vector elements
272 NumElements = Arg.VT.getVectorNumElements() - NumElements;
273 for (unsigned j = 0; j != NumElements; ++j)
274 Regs.push_back(DAG.getUNDEF(VT));
276 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
277 Regs.data(), Regs.size()));
281 InVals.push_back(Val);
286 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
287 MachineInstr * MI, MachineBasicBlock * BB) const {
289 MachineBasicBlock::iterator I = *MI;
291 switch (MI->getOpcode()) {
293 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
294 case AMDGPU::BRANCH: return BB;
295 case AMDGPU::SI_ADDR64_RSRC: {
296 const SIInstrInfo *TII =
297 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
298 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
299 unsigned SuperReg = MI->getOperand(0).getReg();
300 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
301 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
302 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
303 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
304 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
305 .addOperand(MI->getOperand(1));
306 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
308 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
309 .addImm(RSRC_DATA_FORMAT >> 32);
310 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
312 .addImm(AMDGPU::sub0)
314 .addImm(AMDGPU::sub1);
315 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
317 .addImm(AMDGPU::sub0_sub1)
319 .addImm(AMDGPU::sub2_sub3);
320 MI->eraseFromParent();
327 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
331 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
335 //===----------------------------------------------------------------------===//
336 // Custom DAG Lowering Operations
337 //===----------------------------------------------------------------------===//
339 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
340 switch (Op.getOpcode()) {
341 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
342 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
343 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
344 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
345 case ISD::INTRINSIC_WO_CHAIN: {
346 unsigned IntrinsicID =
347 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
348 EVT VT = Op.getValueType();
350 //XXX: Hardcoded we only use two to store the pointer to the parameters.
351 unsigned NumUserSGPRs = 2;
352 switch (IntrinsicID) {
353 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
354 case Intrinsic::r600_read_ngroups_x:
355 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
356 case Intrinsic::r600_read_ngroups_y:
357 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
358 case Intrinsic::r600_read_ngroups_z:
359 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
360 case Intrinsic::r600_read_global_size_x:
361 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
362 case Intrinsic::r600_read_global_size_y:
363 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
364 case Intrinsic::r600_read_global_size_z:
365 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
366 case Intrinsic::r600_read_local_size_x:
367 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
368 case Intrinsic::r600_read_local_size_y:
369 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
370 case Intrinsic::r600_read_local_size_z:
371 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
372 case Intrinsic::r600_read_tgid_x:
373 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
374 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
375 case Intrinsic::r600_read_tgid_y:
376 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
377 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
378 case Intrinsic::r600_read_tgid_z:
379 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
380 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
381 case Intrinsic::r600_read_tidig_x:
382 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
384 case Intrinsic::r600_read_tidig_y:
385 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
387 case Intrinsic::r600_read_tidig_z:
388 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
397 /// \brief Helper function for LowerBRCOND
398 static SDNode *findUser(SDValue Value, unsigned Opcode) {
400 SDNode *Parent = Value.getNode();
401 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
404 if (I.getUse().get() != Value)
407 if (I->getOpcode() == Opcode)
413 /// This transforms the control flow intrinsics to get the branch destination as
414 /// last parameter, also switches branch target with BR if the need arise
415 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
416 SelectionDAG &DAG) const {
420 SDNode *Intr = BRCOND.getOperand(1).getNode();
421 SDValue Target = BRCOND.getOperand(2);
424 if (Intr->getOpcode() == ISD::SETCC) {
425 // As long as we negate the condition everything is fine
426 SDNode *SetCC = Intr;
427 assert(SetCC->getConstantOperandVal(1) == 1);
428 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
430 Intr = SetCC->getOperand(0).getNode();
433 // Get the target from BR if we don't negate the condition
434 BR = findUser(BRCOND, ISD::BR);
435 Target = BR->getOperand(1);
438 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
440 // Build the result and
441 SmallVector<EVT, 4> Res;
442 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
443 Res.push_back(Intr->getValueType(i));
445 // operands of the new intrinsic call
446 SmallVector<SDValue, 4> Ops;
447 Ops.push_back(BRCOND.getOperand(0));
448 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
449 Ops.push_back(Intr->getOperand(i));
450 Ops.push_back(Target);
452 // build the new intrinsic call
453 SDNode *Result = DAG.getNode(
454 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
455 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
458 // Give the branch instruction our target
463 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
466 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
468 // Copy the intrinsic results to registers
469 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
470 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
474 Chain = DAG.getCopyToReg(
476 CopyToReg->getOperand(1),
477 SDValue(Result, i - 1),
480 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
483 // Remove the old intrinsic from the chain
484 DAG.ReplaceAllUsesOfValueWith(
485 SDValue(Intr, Intr->getNumValues() - 1),
486 Intr->getOperand(0));
491 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
492 SDValue LHS = Op.getOperand(0);
493 SDValue RHS = Op.getOperand(1);
494 SDValue True = Op.getOperand(2);
495 SDValue False = Op.getOperand(3);
496 SDValue CC = Op.getOperand(4);
497 EVT VT = Op.getValueType();
500 // Possible Min/Max pattern
501 SDValue MinMax = LowerMinMax(Op, DAG);
502 if (MinMax.getNode()) {
506 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
507 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
510 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
511 SelectionDAG &DAG) const {
512 EVT VT = Op.getValueType();
515 if (VT != MVT::i64) {
519 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
520 DAG.getConstant(31, MVT::i32));
522 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
525 //===----------------------------------------------------------------------===//
526 // Custom DAG optimizations
527 //===----------------------------------------------------------------------===//
529 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
530 DAGCombinerInfo &DCI) const {
531 SelectionDAG &DAG = DCI.DAG;
533 EVT VT = N->getValueType(0);
535 switch (N->getOpcode()) {
537 case ISD::SELECT_CC: {
539 ConstantSDNode *True, *False;
540 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
541 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
542 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
543 && True->isAllOnesValue()
544 && False->isNullValue()
546 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
547 N->getOperand(1), N->getOperand(4));
553 SDValue Arg0 = N->getOperand(0);
554 SDValue Arg1 = N->getOperand(1);
555 SDValue CC = N->getOperand(2);
556 ConstantSDNode * C = NULL;
557 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
559 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
561 && Arg0.getOpcode() == ISD::SIGN_EXTEND
562 && Arg0.getOperand(0).getValueType() == MVT::i1
563 && (C = dyn_cast<ConstantSDNode>(Arg1))
565 && CCOp == ISD::SETNE) {
566 return SimplifySetCC(VT, Arg0.getOperand(0),
567 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
575 /// \brief Test if RegClass is one of the VSrc classes
576 static bool isVSrc(unsigned RegClass) {
577 return AMDGPU::VSrc_32RegClassID == RegClass ||
578 AMDGPU::VSrc_64RegClassID == RegClass;
581 /// \brief Test if RegClass is one of the SSrc classes
582 static bool isSSrc(unsigned RegClass) {
583 return AMDGPU::SSrc_32RegClassID == RegClass ||
584 AMDGPU::SSrc_64RegClassID == RegClass;
587 /// \brief Analyze the possible immediate value Op
589 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
590 /// and the immediate value if it's a literal immediate
591 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
598 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
599 if (Node->getZExtValue() >> 32) {
602 Imm.I = Node->getSExtValue();
603 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
604 Imm.F = Node->getValueAPF().convertToFloat();
606 return -1; // It isn't an immediate
608 if ((Imm.I >= -16 && Imm.I <= 64) ||
609 Imm.F == 0.5f || Imm.F == -0.5f ||
610 Imm.F == 1.0f || Imm.F == -1.0f ||
611 Imm.F == 2.0f || Imm.F == -2.0f ||
612 Imm.F == 4.0f || Imm.F == -4.0f)
613 return 0; // It's an inline immediate
615 return Imm.I; // It's a literal immediate
618 /// \brief Try to fold an immediate directly into an instruction
619 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
620 bool &ScalarSlotUsed) const {
622 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
623 const SIInstrInfo *TII =
624 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
625 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
628 const SDValue &Op = Mov->getOperand(0);
629 int32_t Value = analyzeImmediate(Op.getNode());
631 // Not an immediate at all
634 } else if (Value == 0) {
635 // Inline immediates can always be fold
639 } else if (Value == Immediate) {
640 // Already fold literal immediate
644 } else if (!ScalarSlotUsed && !Immediate) {
645 // Fold this literal immediate
646 ScalarSlotUsed = true;
656 /// \brief Does "Op" fit into register class "RegClass" ?
657 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
658 unsigned RegClass) const {
660 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
661 SDNode *Node = Op.getNode();
663 const TargetRegisterClass *OpClass;
664 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
665 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
666 const SIInstrInfo *TII =
667 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
668 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
669 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
670 if (OpClassID == -1) {
671 switch (MN->getMachineOpcode()) {
672 case AMDGPU::REG_SEQUENCE:
673 // Operand 0 is the register class id for REG_SEQUENCE instructions.
674 OpClass = TRI->getRegClass(
675 cast<ConstantSDNode>(MN->getOperand(0))->getZExtValue());
678 OpClass = getRegClassFor(Op.getSimpleValueType());
682 OpClass = TRI->getRegClass(OpClassID);
685 } else if (Node->getOpcode() == ISD::CopyFromReg) {
686 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
687 OpClass = MRI.getRegClass(Reg->getReg());
692 return TRI->getRegClass(RegClass)->hasSubClassEq(OpClass);
695 /// \brief Make sure that we don't exeed the number of allowed scalars
696 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
698 bool &ScalarSlotUsed) const {
700 // First map the operands register class to a destination class
701 if (RegClass == AMDGPU::VSrc_32RegClassID)
702 RegClass = AMDGPU::VReg_32RegClassID;
703 else if (RegClass == AMDGPU::VSrc_64RegClassID)
704 RegClass = AMDGPU::VReg_64RegClassID;
708 // Nothing todo if they fit naturaly
709 if (fitsRegClass(DAG, Operand, RegClass))
712 // If the scalar slot isn't used yet use it now
713 if (!ScalarSlotUsed) {
714 ScalarSlotUsed = true;
718 // This is a conservative aproach, it is possible that we can't determine
719 // the correct register class and copy too often, but better save than sorry.
720 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
721 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
722 Operand.getValueType(), Operand, RC);
723 Operand = SDValue(Node, 0);
726 /// \returns true if \p Node's operands are different from the SDValue list
728 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
729 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
730 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
737 /// \brief Try to fold the Nodes operands into the Node
738 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
739 SelectionDAG &DAG) const {
741 // Original encoding (either e32 or e64)
742 int Opcode = Node->getMachineOpcode();
743 const SIInstrInfo *TII =
744 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
745 const MCInstrDesc *Desc = &TII->get(Opcode);
747 unsigned NumDefs = Desc->getNumDefs();
748 unsigned NumOps = Desc->getNumOperands();
750 // Commuted opcode if available
751 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
752 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
754 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
755 assert(!DescRev || DescRev->getNumOperands() == NumOps);
757 // e64 version if available, -1 otherwise
758 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
759 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
761 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
762 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
764 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
765 bool HaveVSrc = false, HaveSSrc = false;
767 // First figure out what we alread have in this instruction
768 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
769 i != e && Op < NumOps; ++i, ++Op) {
771 unsigned RegClass = Desc->OpInfo[Op].RegClass;
772 if (isVSrc(RegClass))
774 else if (isSSrc(RegClass))
779 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
780 if (Imm != -1 && Imm != 0) {
786 // If we neither have VSrc nor SSrc it makes no sense to continue
787 if (!HaveVSrc && !HaveSSrc)
790 // No scalar allowed when we have both VSrc and SSrc
791 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
793 // Second go over the operands and try to fold them
794 std::vector<SDValue> Ops;
795 bool Promote2e64 = false;
796 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
797 i != e && Op < NumOps; ++i, ++Op) {
799 const SDValue &Operand = Node->getOperand(i);
800 Ops.push_back(Operand);
802 // Already folded immediate ?
803 if (isa<ConstantSDNode>(Operand.getNode()) ||
804 isa<ConstantFPSDNode>(Operand.getNode()))
807 // Is this a VSrc or SSrc operand ?
808 unsigned RegClass = Desc->OpInfo[Op].RegClass;
809 if (isVSrc(RegClass) || isSSrc(RegClass)) {
810 // Try to fold the immediates
811 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
812 // Folding didn't worked, make sure we don't hit the SReg limit
813 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
818 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
820 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
821 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
823 // Test if it makes sense to swap operands
824 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
825 (!fitsRegClass(DAG, Ops[1], RegClass) &&
826 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
828 // Swap commutable operands
829 SDValue Tmp = Ops[1];
839 if (DescE64 && !Immediate) {
841 // Test if it makes sense to switch to e64 encoding
842 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
843 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
847 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
848 (!fitsRegClass(DAG, Ops[i], RegClass) &&
849 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
851 // Switch to e64 encoding
861 // Add the modifier flags while promoting
862 for (unsigned i = 0; i < 4; ++i)
863 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
866 // Add optional chain and glue
867 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
868 Ops.push_back(Node->getOperand(i));
870 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
871 // this case a brand new node is always be created, even if the operands
872 // are the same as before. So, manually check if anything has been changed.
873 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
877 // Create a complete new instruction
878 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
881 /// \brief Helper function for adjustWritemask
882 static unsigned SubIdx2Lane(unsigned Idx) {
885 case AMDGPU::sub0: return 0;
886 case AMDGPU::sub1: return 1;
887 case AMDGPU::sub2: return 2;
888 case AMDGPU::sub3: return 3;
892 /// \brief Adjust the writemask of MIMG instructions
893 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
894 SelectionDAG &DAG) const {
895 SDNode *Users[4] = { };
896 unsigned Writemask = 0, Lane = 0;
898 // Try to figure out the used register components
899 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
902 // Abort if we can't understand the usage
903 if (!I->isMachineOpcode() ||
904 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
907 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
909 // Abort if we have more than one user per component
914 Writemask |= 1 << Lane;
917 // Abort if all components are used
918 if (Writemask == 0xf)
921 // Adjust the writemask in the node
922 std::vector<SDValue> Ops;
923 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
924 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
925 Ops.push_back(Node->getOperand(i));
926 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
928 // If we only got one lane, replace it with a copy
929 if (Writemask == (1U << Lane)) {
930 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
931 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
932 SDLoc(), Users[Lane]->getValueType(0),
933 SDValue(Node, 0), RC);
934 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
938 // Update the users of the node with the new indices
939 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
941 SDNode *User = Users[i];
945 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
946 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
950 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
951 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
952 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
957 /// \brief Fold the instructions after slecting them
958 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
959 SelectionDAG &DAG) const {
960 Node = AdjustRegClass(Node, DAG);
962 if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
963 adjustWritemask(Node, DAG);
965 return foldOperands(Node, DAG);
968 /// \brief Assign the register class depending on the number of
969 /// bits set in the writemask
970 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
971 SDNode *Node) const {
972 if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
975 unsigned VReg = MI->getOperand(0).getReg();
976 unsigned Writemask = MI->getOperand(1).getImm();
977 unsigned BitsSet = 0;
978 for (unsigned i = 0; i < 4; ++i)
979 BitsSet += Writemask & (1 << i) ? 1 : 0;
981 const TargetRegisterClass *RC;
984 case 1: RC = &AMDGPU::VReg_32RegClass; break;
985 case 2: RC = &AMDGPU::VReg_64RegClass; break;
986 case 3: RC = &AMDGPU::VReg_96RegClass; break;
989 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
990 MRI.setRegClass(VReg, RC);
993 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
994 SelectionDAG &DAG) const {
997 unsigned NewOpcode = N->getMachineOpcode();
999 switch (N->getMachineOpcode()) {
1001 case AMDGPU::REG_SEQUENCE: {
1002 // MVT::i128 only use SGPRs, so i128 REG_SEQUENCEs don't need to be
1004 if (N->getValueType(0) == MVT::i128) {
1007 const SDValue Ops[] = {
1008 DAG.getTargetConstant(AMDGPU::VReg_64RegClassID, MVT::i32),
1009 N->getOperand(1) , N->getOperand(2),
1010 N->getOperand(3), N->getOperand(4)
1012 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::i64, Ops);
1015 case AMDGPU::S_LOAD_DWORD_IMM:
1016 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1018 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1019 if (NewOpcode == N->getMachineOpcode()) {
1020 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1023 case AMDGPU::S_LOAD_DWORDX4_IMM:
1024 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1025 if (NewOpcode == N->getMachineOpcode()) {
1026 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1028 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1031 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1033 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1034 DAG.getConstant(0, MVT::i64)), 0),
1036 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1038 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1043 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1044 const TargetRegisterClass *RC,
1045 unsigned Reg, EVT VT) const {
1046 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1048 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1049 cast<RegisterSDNode>(VReg)->getReg(), VT);