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::VSrc_64RegClass);
37 addRegisterClass(MVT::v2i1, &AMDGPU::VReg_64RegClass);
38 addRegisterClass(MVT::v4i1, &AMDGPU::VReg_128RegClass);
40 addRegisterClass(MVT::v16i8, &AMDGPU::SReg_128RegClass);
41 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
42 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
44 addRegisterClass(MVT::i32, &AMDGPU::VSrc_32RegClass);
45 addRegisterClass(MVT::f32, &AMDGPU::VSrc_32RegClass);
47 addRegisterClass(MVT::v1i32, &AMDGPU::VSrc_32RegClass);
49 addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
50 addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
51 addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
53 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
54 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
55 addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
57 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
58 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
60 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
61 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
63 computeRegisterProperties();
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
68 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
70 setOperationAction(ISD::ADD, MVT::i64, Legal);
71 setOperationAction(ISD::ADD, MVT::i32, Legal);
73 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
74 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
76 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
78 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
79 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
81 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
82 setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
84 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
86 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
88 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
89 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
91 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
93 setTargetDAGCombine(ISD::SELECT_CC);
95 setTargetDAGCombine(ISD::SETCC);
97 setSchedulingPreference(Sched::RegPressure);
100 //===----------------------------------------------------------------------===//
101 // TargetLowering queries
102 //===----------------------------------------------------------------------===//
104 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
105 bool *IsFast) const {
106 // XXX: This depends on the address space and also we may want to revist
107 // the alignment values we specify in the DataLayout.
108 return VT.bitsGT(MVT::i32);
112 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
113 SDLoc DL, SDValue Chain,
114 unsigned Offset) const {
115 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
116 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
117 AMDGPUAS::CONSTANT_ADDRESS);
118 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
119 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
120 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
121 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
122 DAG.getConstant(Offset, MVT::i64));
123 return DAG.getLoad(VT, DL, Chain, Ptr,
124 MachinePointerInfo(UndefValue::get(PtrTy)),
125 false, false, false, ArgVT.getSizeInBits() >> 3);
129 SDValue SITargetLowering::LowerFormalArguments(
131 CallingConv::ID CallConv,
133 const SmallVectorImpl<ISD::InputArg> &Ins,
134 SDLoc DL, SelectionDAG &DAG,
135 SmallVectorImpl<SDValue> &InVals) const {
137 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
139 MachineFunction &MF = DAG.getMachineFunction();
140 FunctionType *FType = MF.getFunction()->getFunctionType();
141 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
143 assert(CallConv == CallingConv::C);
145 SmallVector<ISD::InputArg, 16> Splits;
146 uint32_t Skipped = 0;
148 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
149 const ISD::InputArg &Arg = Ins[i];
151 // First check if it's a PS input addr
152 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
154 assert((PSInputNum <= 15) && "Too many PS inputs!");
157 // We can savely skip PS inputs
163 Info->PSInputAddr |= 1 << PSInputNum++;
166 // Second split vertices into their elements
167 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
168 ISD::InputArg NewArg = Arg;
169 NewArg.Flags.setSplit();
170 NewArg.VT = Arg.VT.getVectorElementType();
172 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
173 // three or five element vertex only needs three or five registers,
174 // NOT four or eigth.
175 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
176 unsigned NumElements = ParamType->getVectorNumElements();
178 for (unsigned j = 0; j != NumElements; ++j) {
179 Splits.push_back(NewArg);
180 NewArg.PartOffset += NewArg.VT.getStoreSize();
184 Splits.push_back(Arg);
188 SmallVector<CCValAssign, 16> ArgLocs;
189 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
190 getTargetMachine(), ArgLocs, *DAG.getContext());
192 // At least one interpolation mode must be enabled or else the GPU will hang.
193 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
194 Info->PSInputAddr |= 1;
195 CCInfo.AllocateReg(AMDGPU::VGPR0);
196 CCInfo.AllocateReg(AMDGPU::VGPR1);
199 // The pointer to the list of arguments is stored in SGPR0, SGPR1
200 if (Info->ShaderType == ShaderType::COMPUTE) {
201 CCInfo.AllocateReg(AMDGPU::SGPR0);
202 CCInfo.AllocateReg(AMDGPU::SGPR1);
203 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
206 AnalyzeFormalArguments(CCInfo, Splits);
208 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
210 const ISD::InputArg &Arg = Ins[i];
211 if (Skipped & (1 << i)) {
212 InVals.push_back(DAG.getUNDEF(Arg.VT));
216 CCValAssign &VA = ArgLocs[ArgIdx++];
217 EVT VT = VA.getLocVT();
220 // The first 36 bytes of the input buffer contains information about
221 // thread group and global sizes.
222 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
223 36 + VA.getLocMemOffset());
224 InVals.push_back(Arg);
227 assert(VA.isRegLoc() && "Parameter must be in a register!");
229 unsigned Reg = VA.getLocReg();
231 if (VT == MVT::i64) {
232 // For now assume it is a pointer
233 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
234 &AMDGPU::SReg_64RegClass);
235 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
236 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
240 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
242 Reg = MF.addLiveIn(Reg, RC);
243 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
245 if (Arg.VT.isVector()) {
247 // Build a vector from the registers
248 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
249 unsigned NumElements = ParamType->getVectorNumElements();
251 SmallVector<SDValue, 4> Regs;
253 for (unsigned j = 1; j != NumElements; ++j) {
254 Reg = ArgLocs[ArgIdx++].getLocReg();
255 Reg = MF.addLiveIn(Reg, RC);
256 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
259 // Fill up the missing vector elements
260 NumElements = Arg.VT.getVectorNumElements() - NumElements;
261 for (unsigned j = 0; j != NumElements; ++j)
262 Regs.push_back(DAG.getUNDEF(VT));
264 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
265 Regs.data(), Regs.size()));
269 InVals.push_back(Val);
274 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
275 MachineInstr * MI, MachineBasicBlock * BB) const {
277 MachineBasicBlock::iterator I = *MI;
279 switch (MI->getOpcode()) {
281 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
282 case AMDGPU::BRANCH: return BB;
283 case AMDGPU::SI_ADDR64_RSRC: {
284 const SIInstrInfo *TII =
285 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
286 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
287 unsigned SuperReg = MI->getOperand(0).getReg();
288 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
289 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
290 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
291 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
292 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
293 .addOperand(MI->getOperand(1));
294 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
296 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
297 .addImm(RSRC_DATA_FORMAT >> 32);
298 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
300 .addImm(AMDGPU::sub0)
302 .addImm(AMDGPU::sub1);
303 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
305 .addImm(AMDGPU::sub0_sub1)
307 .addImm(AMDGPU::sub2_sub3);
308 MI->eraseFromParent();
311 case AMDGPU::V_SUB_F64: {
312 const SIInstrInfo *TII =
313 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
314 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
315 MI->getOperand(0).getReg())
316 .addReg(MI->getOperand(1).getReg())
317 .addReg(MI->getOperand(2).getReg())
318 .addImm(0) /* src2 */
320 .addImm(0) /* CLAMP */
321 .addImm(0) /* OMOD */
322 .addImm(2); /* NEG */
323 MI->eraseFromParent();
330 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
331 if (!VT.isVector()) {
334 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
337 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
341 //===----------------------------------------------------------------------===//
342 // Custom DAG Lowering Operations
343 //===----------------------------------------------------------------------===//
345 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
346 MachineFunction &MF = DAG.getMachineFunction();
347 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
348 switch (Op.getOpcode()) {
349 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
350 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
351 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
352 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
353 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
354 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
355 case ISD::INTRINSIC_WO_CHAIN: {
356 unsigned IntrinsicID =
357 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
358 EVT VT = Op.getValueType();
360 //XXX: Hardcoded we only use two to store the pointer to the parameters.
361 unsigned NumUserSGPRs = 2;
362 switch (IntrinsicID) {
363 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
364 case Intrinsic::r600_read_ngroups_x:
365 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
366 case Intrinsic::r600_read_ngroups_y:
367 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
368 case Intrinsic::r600_read_ngroups_z:
369 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
370 case Intrinsic::r600_read_global_size_x:
371 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
372 case Intrinsic::r600_read_global_size_y:
373 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
374 case Intrinsic::r600_read_global_size_z:
375 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
376 case Intrinsic::r600_read_local_size_x:
377 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
378 case Intrinsic::r600_read_local_size_y:
379 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
380 case Intrinsic::r600_read_local_size_z:
381 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
382 case Intrinsic::r600_read_tgid_x:
383 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
384 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
385 case Intrinsic::r600_read_tgid_y:
386 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
387 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
388 case Intrinsic::r600_read_tgid_z:
389 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
390 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
391 case Intrinsic::r600_read_tidig_x:
392 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
394 case Intrinsic::r600_read_tidig_y:
395 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
397 case Intrinsic::r600_read_tidig_z:
398 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
407 /// \brief Helper function for LowerBRCOND
408 static SDNode *findUser(SDValue Value, unsigned Opcode) {
410 SDNode *Parent = Value.getNode();
411 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
414 if (I.getUse().get() != Value)
417 if (I->getOpcode() == Opcode)
423 /// This transforms the control flow intrinsics to get the branch destination as
424 /// last parameter, also switches branch target with BR if the need arise
425 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
426 SelectionDAG &DAG) const {
430 SDNode *Intr = BRCOND.getOperand(1).getNode();
431 SDValue Target = BRCOND.getOperand(2);
434 if (Intr->getOpcode() == ISD::SETCC) {
435 // As long as we negate the condition everything is fine
436 SDNode *SetCC = Intr;
437 assert(SetCC->getConstantOperandVal(1) == 1);
438 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
440 Intr = SetCC->getOperand(0).getNode();
443 // Get the target from BR if we don't negate the condition
444 BR = findUser(BRCOND, ISD::BR);
445 Target = BR->getOperand(1);
448 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
450 // Build the result and
451 SmallVector<EVT, 4> Res;
452 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
453 Res.push_back(Intr->getValueType(i));
455 // operands of the new intrinsic call
456 SmallVector<SDValue, 4> Ops;
457 Ops.push_back(BRCOND.getOperand(0));
458 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
459 Ops.push_back(Intr->getOperand(i));
460 Ops.push_back(Target);
462 // build the new intrinsic call
463 SDNode *Result = DAG.getNode(
464 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
465 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
468 // Give the branch instruction our target
473 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
476 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
478 // Copy the intrinsic results to registers
479 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
480 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
484 Chain = DAG.getCopyToReg(
486 CopyToReg->getOperand(1),
487 SDValue(Result, i - 1),
490 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
493 // Remove the old intrinsic from the chain
494 DAG.ReplaceAllUsesOfValueWith(
495 SDValue(Intr, Intr->getNumValues() - 1),
496 Intr->getOperand(0));
501 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
502 SDValue LHS = Op.getOperand(0);
503 SDValue RHS = Op.getOperand(1);
504 SDValue True = Op.getOperand(2);
505 SDValue False = Op.getOperand(3);
506 SDValue CC = Op.getOperand(4);
507 EVT VT = Op.getValueType();
510 // Possible Min/Max pattern
511 SDValue MinMax = LowerMinMax(Op, DAG);
512 if (MinMax.getNode()) {
516 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
517 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
520 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
521 SelectionDAG &DAG) const {
522 EVT VT = Op.getValueType();
525 if (VT != MVT::i64) {
529 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
530 DAG.getConstant(31, MVT::i32));
532 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
535 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
536 SelectionDAG &DAG) const {
537 EVT VT = Op.getValueType();
540 if (VT != MVT::i64) {
544 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
545 DAG.getConstant(0, MVT::i32));
548 //===----------------------------------------------------------------------===//
549 // Custom DAG optimizations
550 //===----------------------------------------------------------------------===//
552 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
553 DAGCombinerInfo &DCI) const {
554 SelectionDAG &DAG = DCI.DAG;
556 EVT VT = N->getValueType(0);
558 switch (N->getOpcode()) {
560 case ISD::SELECT_CC: {
562 ConstantSDNode *True, *False;
563 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
564 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
565 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
566 && True->isAllOnesValue()
567 && False->isNullValue()
569 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
570 N->getOperand(1), N->getOperand(4));
576 SDValue Arg0 = N->getOperand(0);
577 SDValue Arg1 = N->getOperand(1);
578 SDValue CC = N->getOperand(2);
579 ConstantSDNode * C = NULL;
580 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
582 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
584 && Arg0.getOpcode() == ISD::SIGN_EXTEND
585 && Arg0.getOperand(0).getValueType() == MVT::i1
586 && (C = dyn_cast<ConstantSDNode>(Arg1))
588 && CCOp == ISD::SETNE) {
589 return SimplifySetCC(VT, Arg0.getOperand(0),
590 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
598 /// \brief Test if RegClass is one of the VSrc classes
599 static bool isVSrc(unsigned RegClass) {
600 return AMDGPU::VSrc_32RegClassID == RegClass ||
601 AMDGPU::VSrc_64RegClassID == RegClass;
604 /// \brief Test if RegClass is one of the SSrc classes
605 static bool isSSrc(unsigned RegClass) {
606 return AMDGPU::SSrc_32RegClassID == RegClass ||
607 AMDGPU::SSrc_64RegClassID == RegClass;
610 /// \brief Analyze the possible immediate value Op
612 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
613 /// and the immediate value if it's a literal immediate
614 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
621 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
622 if (Node->getZExtValue() >> 32) {
625 Imm.I = Node->getSExtValue();
626 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
627 Imm.F = Node->getValueAPF().convertToFloat();
629 return -1; // It isn't an immediate
631 if ((Imm.I >= -16 && Imm.I <= 64) ||
632 Imm.F == 0.5f || Imm.F == -0.5f ||
633 Imm.F == 1.0f || Imm.F == -1.0f ||
634 Imm.F == 2.0f || Imm.F == -2.0f ||
635 Imm.F == 4.0f || Imm.F == -4.0f)
636 return 0; // It's an inline immediate
638 return Imm.I; // It's a literal immediate
641 /// \brief Try to fold an immediate directly into an instruction
642 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
643 bool &ScalarSlotUsed) const {
645 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
646 const SIInstrInfo *TII =
647 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
648 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
651 const SDValue &Op = Mov->getOperand(0);
652 int32_t Value = analyzeImmediate(Op.getNode());
654 // Not an immediate at all
657 } else if (Value == 0) {
658 // Inline immediates can always be fold
662 } else if (Value == Immediate) {
663 // Already fold literal immediate
667 } else if (!ScalarSlotUsed && !Immediate) {
668 // Fold this literal immediate
669 ScalarSlotUsed = true;
679 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
680 SelectionDAG &DAG, const SDValue &Op) const {
681 const SIInstrInfo *TII =
682 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
683 const SIRegisterInfo &TRI = TII->getRegisterInfo();
685 if (!Op->isMachineOpcode()) {
686 switch(Op->getOpcode()) {
687 case ISD::CopyFromReg: {
688 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
689 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
690 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
691 return MRI.getRegClass(Reg);
693 return TRI.getPhysRegClass(Reg);
695 default: return NULL;
698 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
699 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
700 if (OpClassID != -1) {
701 return TRI.getRegClass(OpClassID);
703 switch(Op.getMachineOpcode()) {
704 case AMDGPU::COPY_TO_REGCLASS:
705 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
706 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
708 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
709 // class, then the register class for the value could be either a
710 // VReg or and SReg. In order to get a more accurate
711 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
712 OpClassID == AMDGPU::VSrc_64RegClassID) {
713 return getRegClassForNode(DAG, Op.getOperand(0));
715 return TRI.getRegClass(OpClassID);
716 case AMDGPU::EXTRACT_SUBREG: {
717 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
718 const TargetRegisterClass *SuperClass =
719 getRegClassForNode(DAG, Op.getOperand(0));
720 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
722 case AMDGPU::REG_SEQUENCE:
723 // Operand 0 is the register class id for REG_SEQUENCE instructions.
724 return TRI.getRegClass(
725 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
727 return getRegClassFor(Op.getSimpleValueType());
731 /// \brief Does "Op" fit into register class "RegClass" ?
732 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
733 unsigned RegClass) const {
734 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
735 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
739 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
742 /// \brief Make sure that we don't exeed the number of allowed scalars
743 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
745 bool &ScalarSlotUsed) const {
747 // First map the operands register class to a destination class
748 if (RegClass == AMDGPU::VSrc_32RegClassID)
749 RegClass = AMDGPU::VReg_32RegClassID;
750 else if (RegClass == AMDGPU::VSrc_64RegClassID)
751 RegClass = AMDGPU::VReg_64RegClassID;
755 // Nothing todo if they fit naturaly
756 if (fitsRegClass(DAG, Operand, RegClass))
759 // If the scalar slot isn't used yet use it now
760 if (!ScalarSlotUsed) {
761 ScalarSlotUsed = true;
765 // This is a conservative aproach, it is possible that we can't determine
766 // the correct register class and copy too often, but better save than sorry.
767 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
768 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
769 Operand.getValueType(), Operand, RC);
770 Operand = SDValue(Node, 0);
773 /// \returns true if \p Node's operands are different from the SDValue list
775 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
776 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
777 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
784 /// \brief Try to fold the Nodes operands into the Node
785 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
786 SelectionDAG &DAG) const {
788 // Original encoding (either e32 or e64)
789 int Opcode = Node->getMachineOpcode();
790 const SIInstrInfo *TII =
791 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
792 const MCInstrDesc *Desc = &TII->get(Opcode);
794 unsigned NumDefs = Desc->getNumDefs();
795 unsigned NumOps = Desc->getNumOperands();
797 // Commuted opcode if available
798 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
799 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
801 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
802 assert(!DescRev || DescRev->getNumOperands() == NumOps);
804 // e64 version if available, -1 otherwise
805 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
806 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
808 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
809 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
811 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
812 bool HaveVSrc = false, HaveSSrc = false;
814 // First figure out what we alread have in this instruction
815 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
816 i != e && Op < NumOps; ++i, ++Op) {
818 unsigned RegClass = Desc->OpInfo[Op].RegClass;
819 if (isVSrc(RegClass))
821 else if (isSSrc(RegClass))
826 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
827 if (Imm != -1 && Imm != 0) {
833 // If we neither have VSrc nor SSrc it makes no sense to continue
834 if (!HaveVSrc && !HaveSSrc)
837 // No scalar allowed when we have both VSrc and SSrc
838 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
840 // Second go over the operands and try to fold them
841 std::vector<SDValue> Ops;
842 bool Promote2e64 = false;
843 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
844 i != e && Op < NumOps; ++i, ++Op) {
846 const SDValue &Operand = Node->getOperand(i);
847 Ops.push_back(Operand);
849 // Already folded immediate ?
850 if (isa<ConstantSDNode>(Operand.getNode()) ||
851 isa<ConstantFPSDNode>(Operand.getNode()))
854 // Is this a VSrc or SSrc operand ?
855 unsigned RegClass = Desc->OpInfo[Op].RegClass;
856 if (isVSrc(RegClass) || isSSrc(RegClass)) {
857 // Try to fold the immediates
858 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
859 // Folding didn't worked, make sure we don't hit the SReg limit
860 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
865 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
867 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
868 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
870 // Test if it makes sense to swap operands
871 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
872 (!fitsRegClass(DAG, Ops[1], RegClass) &&
873 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
875 // Swap commutable operands
876 SDValue Tmp = Ops[1];
886 if (DescE64 && !Immediate) {
888 // Test if it makes sense to switch to e64 encoding
889 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
890 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
894 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
895 (!fitsRegClass(DAG, Ops[i], RegClass) &&
896 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
898 // Switch to e64 encoding
908 // Add the modifier flags while promoting
909 for (unsigned i = 0; i < 4; ++i)
910 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
913 // Add optional chain and glue
914 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
915 Ops.push_back(Node->getOperand(i));
917 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
918 // this case a brand new node is always be created, even if the operands
919 // are the same as before. So, manually check if anything has been changed.
920 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
924 // Create a complete new instruction
925 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
928 /// \brief Helper function for adjustWritemask
929 static unsigned SubIdx2Lane(unsigned Idx) {
932 case AMDGPU::sub0: return 0;
933 case AMDGPU::sub1: return 1;
934 case AMDGPU::sub2: return 2;
935 case AMDGPU::sub3: return 3;
939 /// \brief Adjust the writemask of MIMG instructions
940 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
941 SelectionDAG &DAG) const {
942 SDNode *Users[4] = { };
943 unsigned Writemask = 0, Lane = 0;
945 // Try to figure out the used register components
946 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
949 // Abort if we can't understand the usage
950 if (!I->isMachineOpcode() ||
951 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
954 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
956 // Abort if we have more than one user per component
961 Writemask |= 1 << Lane;
964 // Abort if all components are used
965 if (Writemask == 0xf)
968 // Adjust the writemask in the node
969 std::vector<SDValue> Ops;
970 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
971 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
972 Ops.push_back(Node->getOperand(i));
973 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
975 // If we only got one lane, replace it with a copy
976 if (Writemask == (1U << Lane)) {
977 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
978 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
979 SDLoc(), Users[Lane]->getValueType(0),
980 SDValue(Node, 0), RC);
981 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
985 // Update the users of the node with the new indices
986 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
988 SDNode *User = Users[i];
992 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
993 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
997 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
998 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
999 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1004 /// \brief Fold the instructions after slecting them
1005 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1006 SelectionDAG &DAG) const {
1007 Node = AdjustRegClass(Node, DAG);
1009 if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
1010 adjustWritemask(Node, DAG);
1012 return foldOperands(Node, DAG);
1015 /// \brief Assign the register class depending on the number of
1016 /// bits set in the writemask
1017 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1018 SDNode *Node) const {
1019 if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
1022 unsigned VReg = MI->getOperand(0).getReg();
1023 unsigned Writemask = MI->getOperand(1).getImm();
1024 unsigned BitsSet = 0;
1025 for (unsigned i = 0; i < 4; ++i)
1026 BitsSet += Writemask & (1 << i) ? 1 : 0;
1028 const TargetRegisterClass *RC;
1031 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1032 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1033 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1036 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1037 MRI.setRegClass(VReg, RC);
1040 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1041 SelectionDAG &DAG) const {
1044 unsigned NewOpcode = N->getMachineOpcode();
1046 switch (N->getMachineOpcode()) {
1048 case AMDGPU::S_LOAD_DWORD_IMM:
1049 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1051 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1052 if (NewOpcode == N->getMachineOpcode()) {
1053 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1056 case AMDGPU::S_LOAD_DWORDX4_IMM:
1057 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1058 if (NewOpcode == N->getMachineOpcode()) {
1059 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1061 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1064 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1066 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1067 DAG.getConstant(0, MVT::i64)), 0),
1069 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1071 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1076 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1077 const TargetRegisterClass *RC,
1078 unsigned Reg, EVT VT) const {
1079 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1081 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1082 cast<RegisterSDNode>(VReg)->getReg(), VT);