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::SELECT_CC, MVT::f32, Custom);
91 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
93 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
95 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
97 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
99 setTargetDAGCombine(ISD::SELECT_CC);
101 setTargetDAGCombine(ISD::SETCC);
103 setSchedulingPreference(Sched::RegPressure);
106 //===----------------------------------------------------------------------===//
107 // TargetLowering queries
108 //===----------------------------------------------------------------------===//
110 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
111 bool *IsFast) const {
112 // XXX: This depends on the address space and also we may want to revist
113 // the alignment values we specify in the DataLayout.
114 return VT.bitsGT(MVT::i32);
118 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
119 SDLoc DL, SDValue Chain,
120 unsigned Offset) const {
121 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
122 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
123 AMDGPUAS::CONSTANT_ADDRESS);
124 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
125 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
126 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
127 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
128 DAG.getConstant(Offset, MVT::i64));
129 return DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
130 MachinePointerInfo(UndefValue::get(PtrTy)),
131 VT, false, false, ArgVT.getSizeInBits() >> 3);
135 SDValue SITargetLowering::LowerFormalArguments(
137 CallingConv::ID CallConv,
139 const SmallVectorImpl<ISD::InputArg> &Ins,
140 SDLoc DL, SelectionDAG &DAG,
141 SmallVectorImpl<SDValue> &InVals) const {
143 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
145 MachineFunction &MF = DAG.getMachineFunction();
146 FunctionType *FType = MF.getFunction()->getFunctionType();
147 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
149 assert(CallConv == CallingConv::C);
151 SmallVector<ISD::InputArg, 16> Splits;
152 uint32_t Skipped = 0;
154 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
155 const ISD::InputArg &Arg = Ins[i];
157 // First check if it's a PS input addr
158 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
160 assert((PSInputNum <= 15) && "Too many PS inputs!");
163 // We can savely skip PS inputs
169 Info->PSInputAddr |= 1 << PSInputNum++;
172 // Second split vertices into their elements
173 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
174 ISD::InputArg NewArg = Arg;
175 NewArg.Flags.setSplit();
176 NewArg.VT = Arg.VT.getVectorElementType();
178 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
179 // three or five element vertex only needs three or five registers,
180 // NOT four or eigth.
181 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
182 unsigned NumElements = ParamType->getVectorNumElements();
184 for (unsigned j = 0; j != NumElements; ++j) {
185 Splits.push_back(NewArg);
186 NewArg.PartOffset += NewArg.VT.getStoreSize();
190 Splits.push_back(Arg);
194 SmallVector<CCValAssign, 16> ArgLocs;
195 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
196 getTargetMachine(), ArgLocs, *DAG.getContext());
198 // At least one interpolation mode must be enabled or else the GPU will hang.
199 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
200 Info->PSInputAddr |= 1;
201 CCInfo.AllocateReg(AMDGPU::VGPR0);
202 CCInfo.AllocateReg(AMDGPU::VGPR1);
205 // The pointer to the list of arguments is stored in SGPR0, SGPR1
206 if (Info->ShaderType == ShaderType::COMPUTE) {
207 CCInfo.AllocateReg(AMDGPU::SGPR0);
208 CCInfo.AllocateReg(AMDGPU::SGPR1);
209 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
212 AnalyzeFormalArguments(CCInfo, Splits);
214 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
216 const ISD::InputArg &Arg = Ins[i];
217 if (Skipped & (1 << i)) {
218 InVals.push_back(DAG.getUNDEF(Arg.VT));
222 CCValAssign &VA = ArgLocs[ArgIdx++];
223 EVT VT = VA.getLocVT();
226 // The first 36 bytes of the input buffer contains information about
227 // thread group and global sizes.
228 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
229 36 + VA.getLocMemOffset());
230 InVals.push_back(Arg);
233 assert(VA.isRegLoc() && "Parameter must be in a register!");
235 unsigned Reg = VA.getLocReg();
237 if (VT == MVT::i64) {
238 // For now assume it is a pointer
239 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
240 &AMDGPU::SReg_64RegClass);
241 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
242 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
246 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
248 Reg = MF.addLiveIn(Reg, RC);
249 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
251 if (Arg.VT.isVector()) {
253 // Build a vector from the registers
254 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
255 unsigned NumElements = ParamType->getVectorNumElements();
257 SmallVector<SDValue, 4> Regs;
259 for (unsigned j = 1; j != NumElements; ++j) {
260 Reg = ArgLocs[ArgIdx++].getLocReg();
261 Reg = MF.addLiveIn(Reg, RC);
262 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
265 // Fill up the missing vector elements
266 NumElements = Arg.VT.getVectorNumElements() - NumElements;
267 for (unsigned j = 0; j != NumElements; ++j)
268 Regs.push_back(DAG.getUNDEF(VT));
270 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
271 Regs.data(), Regs.size()));
275 InVals.push_back(Val);
280 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
281 MachineInstr * MI, MachineBasicBlock * BB) const {
283 MachineBasicBlock::iterator I = *MI;
285 switch (MI->getOpcode()) {
287 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
288 case AMDGPU::BRANCH: return BB;
289 case AMDGPU::SI_ADDR64_RSRC: {
290 const SIInstrInfo *TII =
291 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
292 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
293 unsigned SuperReg = MI->getOperand(0).getReg();
294 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
295 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
296 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
297 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
298 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
299 .addOperand(MI->getOperand(1));
300 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
302 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
303 .addImm(RSRC_DATA_FORMAT >> 32);
304 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
306 .addImm(AMDGPU::sub0)
308 .addImm(AMDGPU::sub1);
309 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
311 .addImm(AMDGPU::sub0_sub1)
313 .addImm(AMDGPU::sub2_sub3);
314 MI->eraseFromParent();
321 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
325 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
329 //===----------------------------------------------------------------------===//
330 // Custom DAG Lowering Operations
331 //===----------------------------------------------------------------------===//
333 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
334 switch (Op.getOpcode()) {
335 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
336 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
337 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
338 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
339 case ISD::INTRINSIC_WO_CHAIN: {
340 unsigned IntrinsicID =
341 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
342 EVT VT = Op.getValueType();
344 //XXX: Hardcoded we only use two to store the pointer to the parameters.
345 unsigned NumUserSGPRs = 2;
346 switch (IntrinsicID) {
347 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
348 case Intrinsic::r600_read_ngroups_x:
349 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
350 case Intrinsic::r600_read_ngroups_y:
351 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
352 case Intrinsic::r600_read_ngroups_z:
353 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
354 case Intrinsic::r600_read_global_size_x:
355 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
356 case Intrinsic::r600_read_global_size_y:
357 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
358 case Intrinsic::r600_read_global_size_z:
359 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
360 case Intrinsic::r600_read_local_size_x:
361 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
362 case Intrinsic::r600_read_local_size_y:
363 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
364 case Intrinsic::r600_read_local_size_z:
365 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
366 case Intrinsic::r600_read_tgid_x:
367 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
368 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
369 case Intrinsic::r600_read_tgid_y:
370 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
371 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
372 case Intrinsic::r600_read_tgid_z:
373 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
374 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
375 case Intrinsic::r600_read_tidig_x:
376 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
378 case Intrinsic::r600_read_tidig_y:
379 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
381 case Intrinsic::r600_read_tidig_z:
382 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
391 /// \brief Helper function for LowerBRCOND
392 static SDNode *findUser(SDValue Value, unsigned Opcode) {
394 SDNode *Parent = Value.getNode();
395 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
398 if (I.getUse().get() != Value)
401 if (I->getOpcode() == Opcode)
407 /// This transforms the control flow intrinsics to get the branch destination as
408 /// last parameter, also switches branch target with BR if the need arise
409 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
410 SelectionDAG &DAG) const {
414 SDNode *Intr = BRCOND.getOperand(1).getNode();
415 SDValue Target = BRCOND.getOperand(2);
418 if (Intr->getOpcode() == ISD::SETCC) {
419 // As long as we negate the condition everything is fine
420 SDNode *SetCC = Intr;
421 assert(SetCC->getConstantOperandVal(1) == 1);
422 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
424 Intr = SetCC->getOperand(0).getNode();
427 // Get the target from BR if we don't negate the condition
428 BR = findUser(BRCOND, ISD::BR);
429 Target = BR->getOperand(1);
432 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
434 // Build the result and
435 SmallVector<EVT, 4> Res;
436 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
437 Res.push_back(Intr->getValueType(i));
439 // operands of the new intrinsic call
440 SmallVector<SDValue, 4> Ops;
441 Ops.push_back(BRCOND.getOperand(0));
442 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
443 Ops.push_back(Intr->getOperand(i));
444 Ops.push_back(Target);
446 // build the new intrinsic call
447 SDNode *Result = DAG.getNode(
448 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
449 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
452 // Give the branch instruction our target
457 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
460 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
462 // Copy the intrinsic results to registers
463 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
464 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
468 Chain = DAG.getCopyToReg(
470 CopyToReg->getOperand(1),
471 SDValue(Result, i - 1),
474 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
477 // Remove the old intrinsic from the chain
478 DAG.ReplaceAllUsesOfValueWith(
479 SDValue(Intr, Intr->getNumValues() - 1),
480 Intr->getOperand(0));
485 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
486 SDValue LHS = Op.getOperand(0);
487 SDValue RHS = Op.getOperand(1);
488 SDValue True = Op.getOperand(2);
489 SDValue False = Op.getOperand(3);
490 SDValue CC = Op.getOperand(4);
491 EVT VT = Op.getValueType();
494 // Possible Min/Max pattern
495 SDValue MinMax = LowerMinMax(Op, DAG);
496 if (MinMax.getNode()) {
500 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
501 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
504 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
505 SelectionDAG &DAG) const {
506 EVT VT = Op.getValueType();
509 if (VT != MVT::i64) {
513 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
514 DAG.getConstant(31, MVT::i32));
516 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
519 //===----------------------------------------------------------------------===//
520 // Custom DAG optimizations
521 //===----------------------------------------------------------------------===//
523 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
524 DAGCombinerInfo &DCI) const {
525 SelectionDAG &DAG = DCI.DAG;
527 EVT VT = N->getValueType(0);
529 switch (N->getOpcode()) {
531 case ISD::SELECT_CC: {
533 ConstantSDNode *True, *False;
534 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
535 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
536 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
537 && True->isAllOnesValue()
538 && False->isNullValue()
540 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
541 N->getOperand(1), N->getOperand(4));
547 SDValue Arg0 = N->getOperand(0);
548 SDValue Arg1 = N->getOperand(1);
549 SDValue CC = N->getOperand(2);
550 ConstantSDNode * C = NULL;
551 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
553 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
555 && Arg0.getOpcode() == ISD::SIGN_EXTEND
556 && Arg0.getOperand(0).getValueType() == MVT::i1
557 && (C = dyn_cast<ConstantSDNode>(Arg1))
559 && CCOp == ISD::SETNE) {
560 return SimplifySetCC(VT, Arg0.getOperand(0),
561 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
569 /// \brief Test if RegClass is one of the VSrc classes
570 static bool isVSrc(unsigned RegClass) {
571 return AMDGPU::VSrc_32RegClassID == RegClass ||
572 AMDGPU::VSrc_64RegClassID == RegClass;
575 /// \brief Test if RegClass is one of the SSrc classes
576 static bool isSSrc(unsigned RegClass) {
577 return AMDGPU::SSrc_32RegClassID == RegClass ||
578 AMDGPU::SSrc_64RegClassID == RegClass;
581 /// \brief Analyze the possible immediate value Op
583 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
584 /// and the immediate value if it's a literal immediate
585 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
592 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
593 if (Node->getZExtValue() >> 32) {
596 Imm.I = Node->getSExtValue();
597 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
598 Imm.F = Node->getValueAPF().convertToFloat();
600 return -1; // It isn't an immediate
602 if ((Imm.I >= -16 && Imm.I <= 64) ||
603 Imm.F == 0.5f || Imm.F == -0.5f ||
604 Imm.F == 1.0f || Imm.F == -1.0f ||
605 Imm.F == 2.0f || Imm.F == -2.0f ||
606 Imm.F == 4.0f || Imm.F == -4.0f)
607 return 0; // It's an inline immediate
609 return Imm.I; // It's a literal immediate
612 /// \brief Try to fold an immediate directly into an instruction
613 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
614 bool &ScalarSlotUsed) const {
616 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
617 const SIInstrInfo *TII =
618 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
619 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
622 const SDValue &Op = Mov->getOperand(0);
623 int32_t Value = analyzeImmediate(Op.getNode());
625 // Not an immediate at all
628 } else if (Value == 0) {
629 // Inline immediates can always be fold
633 } else if (Value == Immediate) {
634 // Already fold literal immediate
638 } else if (!ScalarSlotUsed && !Immediate) {
639 // Fold this literal immediate
640 ScalarSlotUsed = true;
650 /// \brief Does "Op" fit into register class "RegClass" ?
651 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
652 unsigned RegClass) const {
654 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
655 SDNode *Node = Op.getNode();
657 const TargetRegisterClass *OpClass;
658 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
659 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
660 const SIInstrInfo *TII =
661 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
662 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
663 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
664 if (OpClassID == -1) {
665 switch (MN->getMachineOpcode()) {
666 case AMDGPU::REG_SEQUENCE:
667 // Operand 0 is the register class id for REG_SEQUENCE instructions.
668 OpClass = TRI->getRegClass(
669 cast<ConstantSDNode>(MN->getOperand(0))->getZExtValue());
672 OpClass = getRegClassFor(Op.getSimpleValueType());
676 OpClass = TRI->getRegClass(OpClassID);
679 } else if (Node->getOpcode() == ISD::CopyFromReg) {
680 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
681 OpClass = MRI.getRegClass(Reg->getReg());
686 return TRI->getRegClass(RegClass)->hasSubClassEq(OpClass);
689 /// \brief Make sure that we don't exeed the number of allowed scalars
690 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
692 bool &ScalarSlotUsed) const {
694 // First map the operands register class to a destination class
695 if (RegClass == AMDGPU::VSrc_32RegClassID)
696 RegClass = AMDGPU::VReg_32RegClassID;
697 else if (RegClass == AMDGPU::VSrc_64RegClassID)
698 RegClass = AMDGPU::VReg_64RegClassID;
702 // Nothing todo if they fit naturaly
703 if (fitsRegClass(DAG, Operand, RegClass))
706 // If the scalar slot isn't used yet use it now
707 if (!ScalarSlotUsed) {
708 ScalarSlotUsed = true;
712 // This is a conservative aproach, it is possible that we can't determine
713 // the correct register class and copy too often, but better save than sorry.
714 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
715 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
716 Operand.getValueType(), Operand, RC);
717 Operand = SDValue(Node, 0);
720 /// \returns true if \p Node's operands are different from the SDValue list
722 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
723 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
724 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
731 /// \brief Try to fold the Nodes operands into the Node
732 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
733 SelectionDAG &DAG) const {
735 // Original encoding (either e32 or e64)
736 int Opcode = Node->getMachineOpcode();
737 const SIInstrInfo *TII =
738 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
739 const MCInstrDesc *Desc = &TII->get(Opcode);
741 unsigned NumDefs = Desc->getNumDefs();
742 unsigned NumOps = Desc->getNumOperands();
744 // Commuted opcode if available
745 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
746 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
748 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
749 assert(!DescRev || DescRev->getNumOperands() == NumOps);
751 // e64 version if available, -1 otherwise
752 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
753 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
755 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
756 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
758 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
759 bool HaveVSrc = false, HaveSSrc = false;
761 // First figure out what we alread have in this instruction
762 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
763 i != e && Op < NumOps; ++i, ++Op) {
765 unsigned RegClass = Desc->OpInfo[Op].RegClass;
766 if (isVSrc(RegClass))
768 else if (isSSrc(RegClass))
773 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
774 if (Imm != -1 && Imm != 0) {
780 // If we neither have VSrc nor SSrc it makes no sense to continue
781 if (!HaveVSrc && !HaveSSrc)
784 // No scalar allowed when we have both VSrc and SSrc
785 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
787 // Second go over the operands and try to fold them
788 std::vector<SDValue> Ops;
789 bool Promote2e64 = false;
790 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
791 i != e && Op < NumOps; ++i, ++Op) {
793 const SDValue &Operand = Node->getOperand(i);
794 Ops.push_back(Operand);
796 // Already folded immediate ?
797 if (isa<ConstantSDNode>(Operand.getNode()) ||
798 isa<ConstantFPSDNode>(Operand.getNode()))
801 // Is this a VSrc or SSrc operand ?
802 unsigned RegClass = Desc->OpInfo[Op].RegClass;
803 if (isVSrc(RegClass) || isSSrc(RegClass)) {
804 // Try to fold the immediates
805 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
806 // Folding didn't worked, make sure we don't hit the SReg limit
807 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
812 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
814 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
815 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
817 // Test if it makes sense to swap operands
818 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
819 (!fitsRegClass(DAG, Ops[1], RegClass) &&
820 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
822 // Swap commutable operands
823 SDValue Tmp = Ops[1];
833 if (DescE64 && !Immediate) {
835 // Test if it makes sense to switch to e64 encoding
836 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
837 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
841 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
842 (!fitsRegClass(DAG, Ops[i], RegClass) &&
843 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
845 // Switch to e64 encoding
855 // Add the modifier flags while promoting
856 for (unsigned i = 0; i < 4; ++i)
857 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
860 // Add optional chain and glue
861 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
862 Ops.push_back(Node->getOperand(i));
864 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
865 // this case a brand new node is always be created, even if the operands
866 // are the same as before. So, manually check if anything has been changed.
867 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
871 // Create a complete new instruction
872 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
875 /// \brief Helper function for adjustWritemask
876 static unsigned SubIdx2Lane(unsigned Idx) {
879 case AMDGPU::sub0: return 0;
880 case AMDGPU::sub1: return 1;
881 case AMDGPU::sub2: return 2;
882 case AMDGPU::sub3: return 3;
886 /// \brief Adjust the writemask of MIMG instructions
887 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
888 SelectionDAG &DAG) const {
889 SDNode *Users[4] = { };
890 unsigned Writemask = 0, Lane = 0;
892 // Try to figure out the used register components
893 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
896 // Abort if we can't understand the usage
897 if (!I->isMachineOpcode() ||
898 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
901 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
903 // Abort if we have more than one user per component
908 Writemask |= 1 << Lane;
911 // Abort if all components are used
912 if (Writemask == 0xf)
915 // Adjust the writemask in the node
916 std::vector<SDValue> Ops;
917 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
918 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
919 Ops.push_back(Node->getOperand(i));
920 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
922 // If we only got one lane, replace it with a copy
923 if (Writemask == (1U << Lane)) {
924 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
925 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
926 SDLoc(), Users[Lane]->getValueType(0),
927 SDValue(Node, 0), RC);
928 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
932 // Update the users of the node with the new indices
933 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
935 SDNode *User = Users[i];
939 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
940 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
944 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
945 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
946 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
951 /// \brief Fold the instructions after slecting them
952 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
953 SelectionDAG &DAG) const {
954 Node = AdjustRegClass(Node, DAG);
956 if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
957 adjustWritemask(Node, DAG);
959 return foldOperands(Node, DAG);
962 /// \brief Assign the register class depending on the number of
963 /// bits set in the writemask
964 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
965 SDNode *Node) const {
966 if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
969 unsigned VReg = MI->getOperand(0).getReg();
970 unsigned Writemask = MI->getOperand(1).getImm();
971 unsigned BitsSet = 0;
972 for (unsigned i = 0; i < 4; ++i)
973 BitsSet += Writemask & (1 << i) ? 1 : 0;
975 const TargetRegisterClass *RC;
978 case 1: RC = &AMDGPU::VReg_32RegClass; break;
979 case 2: RC = &AMDGPU::VReg_64RegClass; break;
980 case 3: RC = &AMDGPU::VReg_96RegClass; break;
983 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
984 MRI.setRegClass(VReg, RC);
987 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
988 SelectionDAG &DAG) const {
991 unsigned NewOpcode = N->getMachineOpcode();
993 switch (N->getMachineOpcode()) {
995 case AMDGPU::REG_SEQUENCE: {
996 // MVT::i128 only use SGPRs, so i128 REG_SEQUENCEs don't need to be
998 if (N->getValueType(0) == MVT::i128) {
1001 const SDValue Ops[] = {
1002 DAG.getTargetConstant(AMDGPU::VReg_64RegClassID, MVT::i32),
1003 N->getOperand(1) , N->getOperand(2),
1004 N->getOperand(3), N->getOperand(4)
1006 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::i64, Ops);
1009 case AMDGPU::S_LOAD_DWORD_IMM:
1010 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1012 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1013 if (NewOpcode == N->getMachineOpcode()) {
1014 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1017 case AMDGPU::S_LOAD_DWORDX4_IMM:
1018 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1019 if (NewOpcode == N->getMachineOpcode()) {
1020 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1022 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1025 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1027 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1028 DAG.getConstant(0, MVT::i64)), 0),
1030 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1032 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1037 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1038 const TargetRegisterClass *RC,
1039 unsigned Reg, EVT VT) const {
1040 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1042 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1043 cast<RegisterSDNode>(VReg)->getReg(), VT);