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::v32i8, &AMDGPU::SReg_256RegClass);
41 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
43 addRegisterClass(MVT::i32, &AMDGPU::VSrc_32RegClass);
44 addRegisterClass(MVT::f32, &AMDGPU::VSrc_32RegClass);
46 addRegisterClass(MVT::v1i32, &AMDGPU::VSrc_32RegClass);
48 addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
49 addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
50 addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
52 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
53 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
54 addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
56 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
57 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
59 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
60 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
62 computeRegisterProperties();
64 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
69 setOperationAction(ISD::ADD, MVT::i64, Legal);
70 setOperationAction(ISD::ADD, MVT::i32, Legal);
72 setOperationAction(ISD::BITCAST, MVT::i128, Legal);
74 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
75 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
77 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
79 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
80 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
82 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
83 setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
85 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
86 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
87 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
88 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
90 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
92 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
93 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
95 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
97 setTargetDAGCombine(ISD::SELECT_CC);
99 setTargetDAGCombine(ISD::SETCC);
101 setSchedulingPreference(Sched::RegPressure);
104 //===----------------------------------------------------------------------===//
105 // TargetLowering queries
106 //===----------------------------------------------------------------------===//
108 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
109 bool *IsFast) const {
110 // XXX: This depends on the address space and also we may want to revist
111 // the alignment values we specify in the DataLayout.
112 return VT.bitsGT(MVT::i32);
116 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
117 SDLoc DL, SDValue Chain,
118 unsigned Offset) const {
119 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
120 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
121 AMDGPUAS::CONSTANT_ADDRESS);
122 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
123 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
124 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
125 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
126 DAG.getConstant(Offset, MVT::i64));
127 return DAG.getLoad(VT, DL, Chain, Ptr,
128 MachinePointerInfo(UndefValue::get(PtrTy)),
129 false, false, false, ArgVT.getSizeInBits() >> 3);
133 SDValue SITargetLowering::LowerFormalArguments(
135 CallingConv::ID CallConv,
137 const SmallVectorImpl<ISD::InputArg> &Ins,
138 SDLoc DL, SelectionDAG &DAG,
139 SmallVectorImpl<SDValue> &InVals) const {
141 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
143 MachineFunction &MF = DAG.getMachineFunction();
144 FunctionType *FType = MF.getFunction()->getFunctionType();
145 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
147 assert(CallConv == CallingConv::C);
149 SmallVector<ISD::InputArg, 16> Splits;
150 uint32_t Skipped = 0;
152 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
153 const ISD::InputArg &Arg = Ins[i];
155 // First check if it's a PS input addr
156 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
158 assert((PSInputNum <= 15) && "Too many PS inputs!");
161 // We can savely skip PS inputs
167 Info->PSInputAddr |= 1 << PSInputNum++;
170 // Second split vertices into their elements
171 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
172 ISD::InputArg NewArg = Arg;
173 NewArg.Flags.setSplit();
174 NewArg.VT = Arg.VT.getVectorElementType();
176 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
177 // three or five element vertex only needs three or five registers,
178 // NOT four or eigth.
179 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
180 unsigned NumElements = ParamType->getVectorNumElements();
182 for (unsigned j = 0; j != NumElements; ++j) {
183 Splits.push_back(NewArg);
184 NewArg.PartOffset += NewArg.VT.getStoreSize();
188 Splits.push_back(Arg);
192 SmallVector<CCValAssign, 16> ArgLocs;
193 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
194 getTargetMachine(), ArgLocs, *DAG.getContext());
196 // At least one interpolation mode must be enabled or else the GPU will hang.
197 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
198 Info->PSInputAddr |= 1;
199 CCInfo.AllocateReg(AMDGPU::VGPR0);
200 CCInfo.AllocateReg(AMDGPU::VGPR1);
203 // The pointer to the list of arguments is stored in SGPR0, SGPR1
204 if (Info->ShaderType == ShaderType::COMPUTE) {
205 CCInfo.AllocateReg(AMDGPU::SGPR0);
206 CCInfo.AllocateReg(AMDGPU::SGPR1);
207 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
210 AnalyzeFormalArguments(CCInfo, Splits);
212 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
214 const ISD::InputArg &Arg = Ins[i];
215 if (Skipped & (1 << i)) {
216 InVals.push_back(DAG.getUNDEF(Arg.VT));
220 CCValAssign &VA = ArgLocs[ArgIdx++];
221 EVT VT = VA.getLocVT();
224 // The first 36 bytes of the input buffer contains information about
225 // thread group and global sizes.
226 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
227 36 + VA.getLocMemOffset());
228 InVals.push_back(Arg);
231 assert(VA.isRegLoc() && "Parameter must be in a register!");
233 unsigned Reg = VA.getLocReg();
235 if (VT == MVT::i64) {
236 // For now assume it is a pointer
237 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
238 &AMDGPU::SReg_64RegClass);
239 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
240 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
244 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
246 Reg = MF.addLiveIn(Reg, RC);
247 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
249 if (Arg.VT.isVector()) {
251 // Build a vector from the registers
252 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
253 unsigned NumElements = ParamType->getVectorNumElements();
255 SmallVector<SDValue, 4> Regs;
257 for (unsigned j = 1; j != NumElements; ++j) {
258 Reg = ArgLocs[ArgIdx++].getLocReg();
259 Reg = MF.addLiveIn(Reg, RC);
260 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
263 // Fill up the missing vector elements
264 NumElements = Arg.VT.getVectorNumElements() - NumElements;
265 for (unsigned j = 0; j != NumElements; ++j)
266 Regs.push_back(DAG.getUNDEF(VT));
268 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
269 Regs.data(), Regs.size()));
273 InVals.push_back(Val);
278 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
279 MachineInstr * MI, MachineBasicBlock * BB) const {
281 MachineBasicBlock::iterator I = *MI;
283 switch (MI->getOpcode()) {
285 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
286 case AMDGPU::BRANCH: return BB;
287 case AMDGPU::SI_ADDR64_RSRC: {
288 const SIInstrInfo *TII =
289 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
290 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
291 unsigned SuperReg = MI->getOperand(0).getReg();
292 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
293 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
294 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
295 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
296 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
297 .addOperand(MI->getOperand(1));
298 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
300 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
301 .addImm(RSRC_DATA_FORMAT >> 32);
302 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
304 .addImm(AMDGPU::sub0)
306 .addImm(AMDGPU::sub1);
307 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
309 .addImm(AMDGPU::sub0_sub1)
311 .addImm(AMDGPU::sub2_sub3);
312 MI->eraseFromParent();
315 case AMDGPU::V_SUB_F64: {
316 const SIInstrInfo *TII =
317 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
318 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
319 MI->getOperand(0).getReg())
320 .addReg(MI->getOperand(1).getReg())
321 .addReg(MI->getOperand(2).getReg())
322 .addImm(0) /* src2 */
324 .addImm(0) /* CLAMP */
325 .addImm(0) /* OMOD */
326 .addImm(2); /* NEG */
327 MI->eraseFromParent();
334 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
335 if (!VT.isVector()) {
338 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
341 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
345 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
346 VT = VT.getScalarType();
351 switch (VT.getSimpleVT().SimpleTy) {
353 return false; /* There is V_MAD_F32 for f32 */
363 //===----------------------------------------------------------------------===//
364 // Custom DAG Lowering Operations
365 //===----------------------------------------------------------------------===//
367 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
368 MachineFunction &MF = DAG.getMachineFunction();
369 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
370 switch (Op.getOpcode()) {
371 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
372 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
373 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
374 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
375 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
376 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
377 case ISD::INTRINSIC_WO_CHAIN: {
378 unsigned IntrinsicID =
379 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
380 EVT VT = Op.getValueType();
382 //XXX: Hardcoded we only use two to store the pointer to the parameters.
383 unsigned NumUserSGPRs = 2;
384 switch (IntrinsicID) {
385 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
386 case Intrinsic::r600_read_ngroups_x:
387 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
388 case Intrinsic::r600_read_ngroups_y:
389 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
390 case Intrinsic::r600_read_ngroups_z:
391 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
392 case Intrinsic::r600_read_global_size_x:
393 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
394 case Intrinsic::r600_read_global_size_y:
395 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
396 case Intrinsic::r600_read_global_size_z:
397 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
398 case Intrinsic::r600_read_local_size_x:
399 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
400 case Intrinsic::r600_read_local_size_y:
401 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
402 case Intrinsic::r600_read_local_size_z:
403 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
404 case Intrinsic::r600_read_tgid_x:
405 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
406 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
407 case Intrinsic::r600_read_tgid_y:
408 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
409 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
410 case Intrinsic::r600_read_tgid_z:
411 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
412 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
413 case Intrinsic::r600_read_tidig_x:
414 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
416 case Intrinsic::r600_read_tidig_y:
417 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
419 case Intrinsic::r600_read_tidig_z:
420 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
422 case AMDGPUIntrinsic::SI_load_const: {
424 ResourceDescriptorToi128(Op.getOperand(1), DAG),
428 MachineMemOperand *MMO = new MachineMemOperand(MachinePointerInfo(),
429 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
430 VT.getSizeInBits() / 8, 4);
431 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
432 Op->getVTList(), Ops, 2, VT, MMO);
434 case AMDGPUIntrinsic::SI_sample:
435 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
436 case AMDGPUIntrinsic::SI_sampleb:
437 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
438 case AMDGPUIntrinsic::SI_sampled:
439 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
440 case AMDGPUIntrinsic::SI_samplel:
441 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
442 case AMDGPUIntrinsic::SI_vs_load_input:
443 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
444 ResourceDescriptorToi128(Op.getOperand(1), DAG),
453 /// \brief Helper function for LowerBRCOND
454 static SDNode *findUser(SDValue Value, unsigned Opcode) {
456 SDNode *Parent = Value.getNode();
457 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
460 if (I.getUse().get() != Value)
463 if (I->getOpcode() == Opcode)
469 /// This transforms the control flow intrinsics to get the branch destination as
470 /// last parameter, also switches branch target with BR if the need arise
471 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
472 SelectionDAG &DAG) const {
476 SDNode *Intr = BRCOND.getOperand(1).getNode();
477 SDValue Target = BRCOND.getOperand(2);
480 if (Intr->getOpcode() == ISD::SETCC) {
481 // As long as we negate the condition everything is fine
482 SDNode *SetCC = Intr;
483 assert(SetCC->getConstantOperandVal(1) == 1);
484 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
486 Intr = SetCC->getOperand(0).getNode();
489 // Get the target from BR if we don't negate the condition
490 BR = findUser(BRCOND, ISD::BR);
491 Target = BR->getOperand(1);
494 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
496 // Build the result and
497 SmallVector<EVT, 4> Res;
498 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
499 Res.push_back(Intr->getValueType(i));
501 // operands of the new intrinsic call
502 SmallVector<SDValue, 4> Ops;
503 Ops.push_back(BRCOND.getOperand(0));
504 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
505 Ops.push_back(Intr->getOperand(i));
506 Ops.push_back(Target);
508 // build the new intrinsic call
509 SDNode *Result = DAG.getNode(
510 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
511 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
514 // Give the branch instruction our target
519 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
522 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
524 // Copy the intrinsic results to registers
525 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
526 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
530 Chain = DAG.getCopyToReg(
532 CopyToReg->getOperand(1),
533 SDValue(Result, i - 1),
536 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
539 // Remove the old intrinsic from the chain
540 DAG.ReplaceAllUsesOfValueWith(
541 SDValue(Intr, Intr->getNumValues() - 1),
542 Intr->getOperand(0));
547 SDValue SITargetLowering::ResourceDescriptorToi128(SDValue Op,
548 SelectionDAG &DAG) const {
550 if (Op.getValueType() == MVT::i128) {
554 assert(Op.getOpcode() == ISD::UNDEF);
556 return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), MVT::i128,
557 DAG.getConstant(0, MVT::i64),
558 DAG.getConstant(0, MVT::i64));
561 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
563 SelectionDAG &DAG) const {
564 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
566 ResourceDescriptorToi128(Op.getOperand(3), DAG),
570 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
571 SDValue LHS = Op.getOperand(0);
572 SDValue RHS = Op.getOperand(1);
573 SDValue True = Op.getOperand(2);
574 SDValue False = Op.getOperand(3);
575 SDValue CC = Op.getOperand(4);
576 EVT VT = Op.getValueType();
579 // Possible Min/Max pattern
580 SDValue MinMax = LowerMinMax(Op, DAG);
581 if (MinMax.getNode()) {
585 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
586 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
589 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
590 SelectionDAG &DAG) const {
591 EVT VT = Op.getValueType();
594 if (VT != MVT::i64) {
598 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
599 DAG.getConstant(31, MVT::i32));
601 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
604 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
605 SelectionDAG &DAG) const {
606 EVT VT = Op.getValueType();
609 if (VT != MVT::i64) {
613 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
614 DAG.getConstant(0, MVT::i32));
617 //===----------------------------------------------------------------------===//
618 // Custom DAG optimizations
619 //===----------------------------------------------------------------------===//
621 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
622 DAGCombinerInfo &DCI) const {
623 SelectionDAG &DAG = DCI.DAG;
625 EVT VT = N->getValueType(0);
627 switch (N->getOpcode()) {
629 case ISD::SELECT_CC: {
631 ConstantSDNode *True, *False;
632 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
633 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
634 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
635 && True->isAllOnesValue()
636 && False->isNullValue()
638 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
639 N->getOperand(1), N->getOperand(4));
645 SDValue Arg0 = N->getOperand(0);
646 SDValue Arg1 = N->getOperand(1);
647 SDValue CC = N->getOperand(2);
648 ConstantSDNode * C = NULL;
649 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
651 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
653 && Arg0.getOpcode() == ISD::SIGN_EXTEND
654 && Arg0.getOperand(0).getValueType() == MVT::i1
655 && (C = dyn_cast<ConstantSDNode>(Arg1))
657 && CCOp == ISD::SETNE) {
658 return SimplifySetCC(VT, Arg0.getOperand(0),
659 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
667 /// \brief Test if RegClass is one of the VSrc classes
668 static bool isVSrc(unsigned RegClass) {
669 return AMDGPU::VSrc_32RegClassID == RegClass ||
670 AMDGPU::VSrc_64RegClassID == RegClass;
673 /// \brief Test if RegClass is one of the SSrc classes
674 static bool isSSrc(unsigned RegClass) {
675 return AMDGPU::SSrc_32RegClassID == RegClass ||
676 AMDGPU::SSrc_64RegClassID == RegClass;
679 /// \brief Analyze the possible immediate value Op
681 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
682 /// and the immediate value if it's a literal immediate
683 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
690 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
691 if (Node->getZExtValue() >> 32) {
694 Imm.I = Node->getSExtValue();
695 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
696 Imm.F = Node->getValueAPF().convertToFloat();
698 return -1; // It isn't an immediate
700 if ((Imm.I >= -16 && Imm.I <= 64) ||
701 Imm.F == 0.5f || Imm.F == -0.5f ||
702 Imm.F == 1.0f || Imm.F == -1.0f ||
703 Imm.F == 2.0f || Imm.F == -2.0f ||
704 Imm.F == 4.0f || Imm.F == -4.0f)
705 return 0; // It's an inline immediate
707 return Imm.I; // It's a literal immediate
710 /// \brief Try to fold an immediate directly into an instruction
711 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
712 bool &ScalarSlotUsed) const {
714 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
715 const SIInstrInfo *TII =
716 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
717 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
720 const SDValue &Op = Mov->getOperand(0);
721 int32_t Value = analyzeImmediate(Op.getNode());
723 // Not an immediate at all
726 } else if (Value == 0) {
727 // Inline immediates can always be fold
731 } else if (Value == Immediate) {
732 // Already fold literal immediate
736 } else if (!ScalarSlotUsed && !Immediate) {
737 // Fold this literal immediate
738 ScalarSlotUsed = true;
748 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
749 SelectionDAG &DAG, const SDValue &Op) const {
750 const SIInstrInfo *TII =
751 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
752 const SIRegisterInfo &TRI = TII->getRegisterInfo();
754 if (!Op->isMachineOpcode()) {
755 switch(Op->getOpcode()) {
756 case ISD::CopyFromReg: {
757 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
758 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
759 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
760 return MRI.getRegClass(Reg);
762 return TRI.getPhysRegClass(Reg);
764 default: return NULL;
767 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
768 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
769 if (OpClassID != -1) {
770 return TRI.getRegClass(OpClassID);
772 switch(Op.getMachineOpcode()) {
773 case AMDGPU::COPY_TO_REGCLASS:
774 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
775 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
777 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
778 // class, then the register class for the value could be either a
779 // VReg or and SReg. In order to get a more accurate
780 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
781 OpClassID == AMDGPU::VSrc_64RegClassID) {
782 return getRegClassForNode(DAG, Op.getOperand(0));
784 return TRI.getRegClass(OpClassID);
785 case AMDGPU::EXTRACT_SUBREG: {
786 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
787 const TargetRegisterClass *SuperClass =
788 getRegClassForNode(DAG, Op.getOperand(0));
789 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
791 case AMDGPU::REG_SEQUENCE:
792 // Operand 0 is the register class id for REG_SEQUENCE instructions.
793 return TRI.getRegClass(
794 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
796 return getRegClassFor(Op.getSimpleValueType());
800 /// \brief Does "Op" fit into register class "RegClass" ?
801 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
802 unsigned RegClass) const {
803 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
804 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
808 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
811 /// \brief Make sure that we don't exeed the number of allowed scalars
812 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
814 bool &ScalarSlotUsed) const {
816 // First map the operands register class to a destination class
817 if (RegClass == AMDGPU::VSrc_32RegClassID)
818 RegClass = AMDGPU::VReg_32RegClassID;
819 else if (RegClass == AMDGPU::VSrc_64RegClassID)
820 RegClass = AMDGPU::VReg_64RegClassID;
824 // Nothing todo if they fit naturaly
825 if (fitsRegClass(DAG, Operand, RegClass))
828 // If the scalar slot isn't used yet use it now
829 if (!ScalarSlotUsed) {
830 ScalarSlotUsed = true;
834 // This is a conservative aproach, it is possible that we can't determine
835 // the correct register class and copy too often, but better save than sorry.
836 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
837 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
838 Operand.getValueType(), Operand, RC);
839 Operand = SDValue(Node, 0);
842 /// \returns true if \p Node's operands are different from the SDValue list
844 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
845 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
846 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
853 /// \brief Try to fold the Nodes operands into the Node
854 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
855 SelectionDAG &DAG) const {
857 // Original encoding (either e32 or e64)
858 int Opcode = Node->getMachineOpcode();
859 const SIInstrInfo *TII =
860 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
861 const MCInstrDesc *Desc = &TII->get(Opcode);
863 unsigned NumDefs = Desc->getNumDefs();
864 unsigned NumOps = Desc->getNumOperands();
866 // Commuted opcode if available
867 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
868 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
870 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
871 assert(!DescRev || DescRev->getNumOperands() == NumOps);
873 // e64 version if available, -1 otherwise
874 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
875 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
877 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
878 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
880 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
881 bool HaveVSrc = false, HaveSSrc = false;
883 // First figure out what we alread have in this instruction
884 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
885 i != e && Op < NumOps; ++i, ++Op) {
887 unsigned RegClass = Desc->OpInfo[Op].RegClass;
888 if (isVSrc(RegClass))
890 else if (isSSrc(RegClass))
895 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
896 if (Imm != -1 && Imm != 0) {
902 // If we neither have VSrc nor SSrc it makes no sense to continue
903 if (!HaveVSrc && !HaveSSrc)
906 // No scalar allowed when we have both VSrc and SSrc
907 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
909 // Second go over the operands and try to fold them
910 std::vector<SDValue> Ops;
911 bool Promote2e64 = false;
912 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
913 i != e && Op < NumOps; ++i, ++Op) {
915 const SDValue &Operand = Node->getOperand(i);
916 Ops.push_back(Operand);
918 // Already folded immediate ?
919 if (isa<ConstantSDNode>(Operand.getNode()) ||
920 isa<ConstantFPSDNode>(Operand.getNode()))
923 // Is this a VSrc or SSrc operand ?
924 unsigned RegClass = Desc->OpInfo[Op].RegClass;
925 if (isVSrc(RegClass) || isSSrc(RegClass)) {
926 // Try to fold the immediates
927 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
928 // Folding didn't worked, make sure we don't hit the SReg limit
929 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
934 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
936 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
937 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
939 // Test if it makes sense to swap operands
940 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
941 (!fitsRegClass(DAG, Ops[1], RegClass) &&
942 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
944 // Swap commutable operands
945 SDValue Tmp = Ops[1];
955 if (DescE64 && !Immediate) {
957 // Test if it makes sense to switch to e64 encoding
958 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
959 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
963 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
964 (!fitsRegClass(DAG, Ops[i], RegClass) &&
965 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
967 // Switch to e64 encoding
977 // Add the modifier flags while promoting
978 for (unsigned i = 0; i < 4; ++i)
979 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
982 // Add optional chain and glue
983 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
984 Ops.push_back(Node->getOperand(i));
986 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
987 // this case a brand new node is always be created, even if the operands
988 // are the same as before. So, manually check if anything has been changed.
989 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
993 // Create a complete new instruction
994 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
997 /// \brief Helper function for adjustWritemask
998 static unsigned SubIdx2Lane(unsigned Idx) {
1001 case AMDGPU::sub0: return 0;
1002 case AMDGPU::sub1: return 1;
1003 case AMDGPU::sub2: return 2;
1004 case AMDGPU::sub3: return 3;
1008 /// \brief Adjust the writemask of MIMG instructions
1009 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1010 SelectionDAG &DAG) const {
1011 SDNode *Users[4] = { };
1012 unsigned Writemask = 0, Lane = 0;
1014 // Try to figure out the used register components
1015 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1018 // Abort if we can't understand the usage
1019 if (!I->isMachineOpcode() ||
1020 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1023 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1025 // Abort if we have more than one user per component
1030 Writemask |= 1 << Lane;
1033 // Abort if all components are used
1034 if (Writemask == 0xf)
1037 // Adjust the writemask in the node
1038 std::vector<SDValue> Ops;
1039 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
1040 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1041 Ops.push_back(Node->getOperand(i));
1042 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1044 // If we only got one lane, replace it with a copy
1045 if (Writemask == (1U << Lane)) {
1046 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1047 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1048 SDLoc(), Users[Lane]->getValueType(0),
1049 SDValue(Node, 0), RC);
1050 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1054 // Update the users of the node with the new indices
1055 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1057 SDNode *User = Users[i];
1061 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1062 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1066 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1067 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1068 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1073 /// \brief Fold the instructions after slecting them
1074 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1075 SelectionDAG &DAG) const {
1076 const SIInstrInfo *TII =
1077 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1078 Node = AdjustRegClass(Node, DAG);
1080 if (TII->isMIMG(Node->getMachineOpcode()))
1081 adjustWritemask(Node, DAG);
1083 return foldOperands(Node, DAG);
1086 /// \brief Assign the register class depending on the number of
1087 /// bits set in the writemask
1088 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1089 SDNode *Node) const {
1090 const SIInstrInfo *TII =
1091 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1092 if (!TII->isMIMG(MI->getOpcode()))
1095 unsigned VReg = MI->getOperand(0).getReg();
1096 unsigned Writemask = MI->getOperand(1).getImm();
1097 unsigned BitsSet = 0;
1098 for (unsigned i = 0; i < 4; ++i)
1099 BitsSet += Writemask & (1 << i) ? 1 : 0;
1101 const TargetRegisterClass *RC;
1104 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1105 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1106 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1109 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1110 MRI.setRegClass(VReg, RC);
1113 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1114 SelectionDAG &DAG) const {
1117 unsigned NewOpcode = N->getMachineOpcode();
1119 switch (N->getMachineOpcode()) {
1121 case AMDGPU::S_LOAD_DWORD_IMM:
1122 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1124 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1125 if (NewOpcode == N->getMachineOpcode()) {
1126 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1129 case AMDGPU::S_LOAD_DWORDX4_IMM:
1130 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1131 if (NewOpcode == N->getMachineOpcode()) {
1132 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1134 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1137 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1139 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1140 DAG.getConstant(0, MVT::i64)), 0),
1142 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1144 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1149 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1150 const TargetRegisterClass *RC,
1151 unsigned Reg, EVT VT) const {
1152 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1154 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1155 cast<RegisterSDNode>(VReg)->getReg(), VT);