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"
18 #include "AMDILIntrinsicInfo.h"
19 #include "SIInstrInfo.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "SIRegisterInfo.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
30 SITargetLowering::SITargetLowering(TargetMachine &TM) :
31 AMDGPUTargetLowering(TM),
32 TII(static_cast<const SIInstrInfo*>(TM.getInstrInfo())),
33 TRI(TM.getRegisterInfo()) {
35 addRegisterClass(MVT::i1, &AMDGPU::SReg_64RegClass);
36 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
38 addRegisterClass(MVT::v16i8, &AMDGPU::SReg_128RegClass);
39 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
40 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
42 addRegisterClass(MVT::i32, &AMDGPU::VReg_32RegClass);
43 addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
45 addRegisterClass(MVT::v1i32, &AMDGPU::VReg_32RegClass);
47 addRegisterClass(MVT::v2i32, &AMDGPU::VReg_64RegClass);
48 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
50 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
51 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
53 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
54 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
56 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
57 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
59 computeRegisterProperties();
61 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
62 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
63 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
64 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
66 setOperationAction(ISD::ADD, MVT::i64, Legal);
67 setOperationAction(ISD::ADD, MVT::i32, Legal);
69 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
70 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
72 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
73 setTargetDAGCombine(ISD::SELECT_CC);
75 setTargetDAGCombine(ISD::SETCC);
77 setSchedulingPreference(Sched::RegPressure);
80 SDValue SITargetLowering::LowerFormalArguments(
82 CallingConv::ID CallConv,
84 const SmallVectorImpl<ISD::InputArg> &Ins,
85 DebugLoc DL, SelectionDAG &DAG,
86 SmallVectorImpl<SDValue> &InVals) const {
88 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
90 MachineFunction &MF = DAG.getMachineFunction();
91 FunctionType *FType = MF.getFunction()->getFunctionType();
92 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
94 assert(CallConv == CallingConv::C);
96 SmallVector<ISD::InputArg, 16> Splits;
99 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
100 const ISD::InputArg &Arg = Ins[i];
102 // First check if it's a PS input addr
103 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
105 assert((PSInputNum <= 15) && "Too many PS inputs!");
108 // We can savely skip PS inputs
114 Info->PSInputAddr |= 1 << PSInputNum++;
117 // Second split vertices into their elements
118 if (Arg.VT.isVector()) {
119 ISD::InputArg NewArg = Arg;
120 NewArg.Flags.setSplit();
121 NewArg.VT = Arg.VT.getVectorElementType();
123 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
124 // three or five element vertex only needs three or five registers,
125 // NOT four or eigth.
126 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
127 unsigned NumElements = ParamType->getVectorNumElements();
129 for (unsigned j = 0; j != NumElements; ++j) {
130 Splits.push_back(NewArg);
131 NewArg.PartOffset += NewArg.VT.getStoreSize();
135 Splits.push_back(Arg);
139 SmallVector<CCValAssign, 16> ArgLocs;
140 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
141 getTargetMachine(), ArgLocs, *DAG.getContext());
143 // At least one interpolation mode must be enabled or else the GPU will hang.
144 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
145 Info->PSInputAddr |= 1;
146 CCInfo.AllocateReg(AMDGPU::VGPR0);
147 CCInfo.AllocateReg(AMDGPU::VGPR1);
150 AnalyzeFormalArguments(CCInfo, Splits);
152 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
154 if (Skipped & (1 << i)) {
155 InVals.push_back(SDValue());
159 CCValAssign &VA = ArgLocs[ArgIdx++];
160 assert(VA.isRegLoc() && "Parameter must be in a register!");
162 unsigned Reg = VA.getLocReg();
163 MVT VT = VA.getLocVT();
165 if (VT == MVT::i64) {
166 // For now assume it is a pointer
167 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
168 &AMDGPU::SReg_64RegClass);
169 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
170 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
174 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
176 Reg = MF.addLiveIn(Reg, RC);
177 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
179 const ISD::InputArg &Arg = Ins[i];
180 if (Arg.VT.isVector()) {
182 // Build a vector from the registers
183 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
184 unsigned NumElements = ParamType->getVectorNumElements();
186 SmallVector<SDValue, 4> Regs;
188 for (unsigned j = 1; j != NumElements; ++j) {
189 Reg = ArgLocs[ArgIdx++].getLocReg();
190 Reg = MF.addLiveIn(Reg, RC);
191 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
194 // Fill up the missing vector elements
195 NumElements = Arg.VT.getVectorNumElements() - NumElements;
196 for (unsigned j = 0; j != NumElements; ++j)
197 Regs.push_back(DAG.getUNDEF(VT));
199 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
200 Regs.data(), Regs.size()));
204 InVals.push_back(Val);
209 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
210 MachineInstr * MI, MachineBasicBlock * BB) const {
212 switch (MI->getOpcode()) {
214 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
215 case AMDGPU::BRANCH: return BB;
220 EVT SITargetLowering::getSetCCResultType(EVT VT) const {
224 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
228 //===----------------------------------------------------------------------===//
229 // Custom DAG Lowering Operations
230 //===----------------------------------------------------------------------===//
232 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
233 switch (Op.getOpcode()) {
234 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
235 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
236 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
241 /// \brief Helper function for LowerBRCOND
242 static SDNode *findUser(SDValue Value, unsigned Opcode) {
244 SDNode *Parent = Value.getNode();
245 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
248 if (I.getUse().get() != Value)
251 if (I->getOpcode() == Opcode)
257 /// This transforms the control flow intrinsics to get the branch destination as
258 /// last parameter, also switches branch target with BR if the need arise
259 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
260 SelectionDAG &DAG) const {
262 DebugLoc DL = BRCOND.getDebugLoc();
264 SDNode *Intr = BRCOND.getOperand(1).getNode();
265 SDValue Target = BRCOND.getOperand(2);
268 if (Intr->getOpcode() == ISD::SETCC) {
269 // As long as we negate the condition everything is fine
270 SDNode *SetCC = Intr;
271 assert(SetCC->getConstantOperandVal(1) == 1);
272 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
274 Intr = SetCC->getOperand(0).getNode();
277 // Get the target from BR if we don't negate the condition
278 BR = findUser(BRCOND, ISD::BR);
279 Target = BR->getOperand(1);
282 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
284 // Build the result and
285 SmallVector<EVT, 4> Res;
286 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
287 Res.push_back(Intr->getValueType(i));
289 // operands of the new intrinsic call
290 SmallVector<SDValue, 4> Ops;
291 Ops.push_back(BRCOND.getOperand(0));
292 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
293 Ops.push_back(Intr->getOperand(i));
294 Ops.push_back(Target);
296 // build the new intrinsic call
297 SDNode *Result = DAG.getNode(
298 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
299 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
302 // Give the branch instruction our target
307 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
310 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
312 // Copy the intrinsic results to registers
313 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
314 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
318 Chain = DAG.getCopyToReg(
320 CopyToReg->getOperand(1),
321 SDValue(Result, i - 1),
324 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
327 // Remove the old intrinsic from the chain
328 DAG.ReplaceAllUsesOfValueWith(
329 SDValue(Intr, Intr->getNumValues() - 1),
330 Intr->getOperand(0));
335 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
336 SDValue LHS = Op.getOperand(0);
337 SDValue RHS = Op.getOperand(1);
338 SDValue True = Op.getOperand(2);
339 SDValue False = Op.getOperand(3);
340 SDValue CC = Op.getOperand(4);
341 EVT VT = Op.getValueType();
342 DebugLoc DL = Op.getDebugLoc();
344 // Possible Min/Max pattern
345 SDValue MinMax = LowerMinMax(Op, DAG);
346 if (MinMax.getNode()) {
350 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
351 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
354 //===----------------------------------------------------------------------===//
355 // Custom DAG optimizations
356 //===----------------------------------------------------------------------===//
358 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
359 DAGCombinerInfo &DCI) const {
360 SelectionDAG &DAG = DCI.DAG;
361 DebugLoc DL = N->getDebugLoc();
362 EVT VT = N->getValueType(0);
364 switch (N->getOpcode()) {
366 case ISD::SELECT_CC: {
368 ConstantSDNode *True, *False;
369 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
370 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
371 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
372 && True->isAllOnesValue()
373 && False->isNullValue()
375 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
376 N->getOperand(1), N->getOperand(4));
382 SDValue Arg0 = N->getOperand(0);
383 SDValue Arg1 = N->getOperand(1);
384 SDValue CC = N->getOperand(2);
385 ConstantSDNode * C = NULL;
386 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
388 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
390 && Arg0.getOpcode() == ISD::SIGN_EXTEND
391 && Arg0.getOperand(0).getValueType() == MVT::i1
392 && (C = dyn_cast<ConstantSDNode>(Arg1))
394 && CCOp == ISD::SETNE) {
395 return SimplifySetCC(VT, Arg0.getOperand(0),
396 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
404 /// \brief Test if RegClass is one of the VSrc classes
405 static bool isVSrc(unsigned RegClass) {
406 return AMDGPU::VSrc_32RegClassID == RegClass ||
407 AMDGPU::VSrc_64RegClassID == RegClass;
410 /// \brief Test if RegClass is one of the SSrc classes
411 static bool isSSrc(unsigned RegClass) {
412 return AMDGPU::SSrc_32RegClassID == RegClass ||
413 AMDGPU::SSrc_64RegClassID == RegClass;
416 /// \brief Analyze the possible immediate value Op
418 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
419 /// and the immediate value if it's a literal immediate
420 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
427 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N))
428 Imm.I = Node->getSExtValue();
429 else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
430 Imm.F = Node->getValueAPF().convertToFloat();
432 return -1; // It isn't an immediate
434 if ((Imm.I >= -16 && Imm.I <= 64) ||
435 Imm.F == 0.5f || Imm.F == -0.5f ||
436 Imm.F == 1.0f || Imm.F == -1.0f ||
437 Imm.F == 2.0f || Imm.F == -2.0f ||
438 Imm.F == 4.0f || Imm.F == -4.0f)
439 return 0; // It's an inline immediate
441 return Imm.I; // It's a literal immediate
444 /// \brief Try to fold an immediate directly into an instruction
445 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
446 bool &ScalarSlotUsed) const {
448 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
449 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
452 const SDValue &Op = Mov->getOperand(0);
453 int32_t Value = analyzeImmediate(Op.getNode());
455 // Not an immediate at all
458 } else if (Value == 0) {
459 // Inline immediates can always be fold
463 } else if (Value == Immediate) {
464 // Already fold literal immediate
468 } else if (!ScalarSlotUsed && !Immediate) {
469 // Fold this literal immediate
470 ScalarSlotUsed = true;
480 /// \brief Does "Op" fit into register class "RegClass" ?
481 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, SDValue &Op,
482 unsigned RegClass) const {
484 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
485 SDNode *Node = Op.getNode();
488 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
489 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
490 OpClass = Desc.OpInfo[Op.getResNo()].RegClass;
492 } else if (Node->getOpcode() == ISD::CopyFromReg) {
493 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
494 OpClass = MRI.getRegClass(Reg->getReg())->getID();
502 return TRI->getRegClass(RegClass)->hasSubClassEq(TRI->getRegClass(OpClass));
505 /// \brief Make sure that we don't exeed the number of allowed scalars
506 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
508 bool &ScalarSlotUsed) const {
510 // First map the operands register class to a destination class
511 if (RegClass == AMDGPU::VSrc_32RegClassID)
512 RegClass = AMDGPU::VReg_32RegClassID;
513 else if (RegClass == AMDGPU::VSrc_64RegClassID)
514 RegClass = AMDGPU::VReg_64RegClassID;
518 // Nothing todo if they fit naturaly
519 if (fitsRegClass(DAG, Operand, RegClass))
522 // If the scalar slot isn't used yet use it now
523 if (!ScalarSlotUsed) {
524 ScalarSlotUsed = true;
528 // This is a conservative aproach, it is possible that we can't determine
529 // the correct register class and copy too often, but better save than sorry.
530 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
531 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, DebugLoc(),
532 Operand.getValueType(), Operand, RC);
533 Operand = SDValue(Node, 0);
536 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
537 SelectionDAG &DAG) const {
539 // Original encoding (either e32 or e64)
540 int Opcode = Node->getMachineOpcode();
541 const MCInstrDesc *Desc = &TII->get(Opcode);
543 unsigned NumDefs = Desc->getNumDefs();
544 unsigned NumOps = Desc->getNumOperands();
546 // e64 version if available, -1 otherwise
547 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
548 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
550 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
551 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
553 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
554 bool HaveVSrc = false, HaveSSrc = false;
556 // First figure out what we alread have in this instruction
557 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
558 i != e && Op < NumOps; ++i, ++Op) {
560 unsigned RegClass = Desc->OpInfo[Op].RegClass;
561 if (isVSrc(RegClass))
563 else if (isSSrc(RegClass))
568 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
569 if (Imm != -1 && Imm != 0) {
575 // If we neither have VSrc nor SSrc it makes no sense to continue
576 if (!HaveVSrc && !HaveSSrc)
579 // No scalar allowed when we have both VSrc and SSrc
580 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
582 // Second go over the operands and try to fold them
583 std::vector<SDValue> Ops;
584 bool Promote2e64 = false;
585 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
586 i != e && Op < NumOps; ++i, ++Op) {
588 const SDValue &Operand = Node->getOperand(i);
589 Ops.push_back(Operand);
591 // Already folded immediate ?
592 if (isa<ConstantSDNode>(Operand.getNode()) ||
593 isa<ConstantFPSDNode>(Operand.getNode()))
596 // Is this a VSrc or SSrc operand ?
597 unsigned RegClass = Desc->OpInfo[Op].RegClass;
598 if (!isVSrc(RegClass) && !isSSrc(RegClass)) {
600 if (i == 1 && Desc->isCommutable() &&
601 fitsRegClass(DAG, Ops[0], RegClass) &&
602 foldImm(Ops[1], Immediate, ScalarSlotUsed)) {
604 assert(isVSrc(Desc->OpInfo[NumDefs].RegClass) ||
605 isSSrc(Desc->OpInfo[NumDefs].RegClass));
607 // Swap commutable operands
608 SDValue Tmp = Ops[1];
612 } else if (DescE64 && !Immediate) {
613 // Test if it makes sense to switch to e64 encoding
615 RegClass = DescE64->OpInfo[Op].RegClass;
617 if ((isVSrc(RegClass) || isSSrc(RegClass)) &&
618 foldImm(Ops[i], TmpImm, ScalarSlotUsed)) {
629 // Try to fold the immediates
630 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
631 // Folding didn't worked, make sure we don't hit the SReg limit
632 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
637 // Add the modifier flags while promoting
638 for (unsigned i = 0; i < 4; ++i)
639 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
642 // Add optional chain and glue
643 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
644 Ops.push_back(Node->getOperand(i));
646 // Either create a complete new or update the current instruction
648 return DAG.getMachineNode(OpcodeE64, Node->getDebugLoc(),
649 Node->getVTList(), Ops.data(), Ops.size());
651 return DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());