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::f64, &AMDGPU::VSrc_64RegClass);
47 addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
48 addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
50 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
51 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
52 addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
54 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
55 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
57 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
58 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
60 computeRegisterProperties();
62 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
63 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
64 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
67 setOperationAction(ISD::ADD, MVT::i64, Legal);
68 setOperationAction(ISD::ADD, MVT::i32, Legal);
70 setOperationAction(ISD::BITCAST, MVT::i128, Legal);
72 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
73 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
75 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
77 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
78 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
80 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
81 setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
83 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
84 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
85 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
86 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
88 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
90 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
91 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
93 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
95 setTargetDAGCombine(ISD::SELECT_CC);
97 setTargetDAGCombine(ISD::SETCC);
99 setSchedulingPreference(Sched::RegPressure);
102 //===----------------------------------------------------------------------===//
103 // TargetLowering queries
104 //===----------------------------------------------------------------------===//
106 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
107 bool *IsFast) const {
108 // XXX: This depends on the address space and also we may want to revist
109 // the alignment values we specify in the DataLayout.
110 return VT.bitsGT(MVT::i32);
114 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
115 SDLoc DL, SDValue Chain,
116 unsigned Offset) const {
117 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
118 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
119 AMDGPUAS::CONSTANT_ADDRESS);
120 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
121 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
122 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
123 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
124 DAG.getConstant(Offset, MVT::i64));
125 return DAG.getLoad(VT, DL, Chain, Ptr,
126 MachinePointerInfo(UndefValue::get(PtrTy)),
127 false, false, false, ArgVT.getSizeInBits() >> 3);
131 SDValue SITargetLowering::LowerFormalArguments(
133 CallingConv::ID CallConv,
135 const SmallVectorImpl<ISD::InputArg> &Ins,
136 SDLoc DL, SelectionDAG &DAG,
137 SmallVectorImpl<SDValue> &InVals) const {
139 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
141 MachineFunction &MF = DAG.getMachineFunction();
142 FunctionType *FType = MF.getFunction()->getFunctionType();
143 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
145 assert(CallConv == CallingConv::C);
147 SmallVector<ISD::InputArg, 16> Splits;
148 uint32_t Skipped = 0;
150 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
151 const ISD::InputArg &Arg = Ins[i];
153 // First check if it's a PS input addr
154 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
156 assert((PSInputNum <= 15) && "Too many PS inputs!");
159 // We can savely skip PS inputs
165 Info->PSInputAddr |= 1 << PSInputNum++;
168 // Second split vertices into their elements
169 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
170 ISD::InputArg NewArg = Arg;
171 NewArg.Flags.setSplit();
172 NewArg.VT = Arg.VT.getVectorElementType();
174 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
175 // three or five element vertex only needs three or five registers,
176 // NOT four or eigth.
177 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
178 unsigned NumElements = ParamType->getVectorNumElements();
180 for (unsigned j = 0; j != NumElements; ++j) {
181 Splits.push_back(NewArg);
182 NewArg.PartOffset += NewArg.VT.getStoreSize();
186 Splits.push_back(Arg);
190 SmallVector<CCValAssign, 16> ArgLocs;
191 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
192 getTargetMachine(), ArgLocs, *DAG.getContext());
194 // At least one interpolation mode must be enabled or else the GPU will hang.
195 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
196 Info->PSInputAddr |= 1;
197 CCInfo.AllocateReg(AMDGPU::VGPR0);
198 CCInfo.AllocateReg(AMDGPU::VGPR1);
201 // The pointer to the list of arguments is stored in SGPR0, SGPR1
202 if (Info->ShaderType == ShaderType::COMPUTE) {
203 CCInfo.AllocateReg(AMDGPU::SGPR0);
204 CCInfo.AllocateReg(AMDGPU::SGPR1);
205 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
208 AnalyzeFormalArguments(CCInfo, Splits);
210 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
212 const ISD::InputArg &Arg = Ins[i];
213 if (Skipped & (1 << i)) {
214 InVals.push_back(DAG.getUNDEF(Arg.VT));
218 CCValAssign &VA = ArgLocs[ArgIdx++];
219 EVT VT = VA.getLocVT();
222 // The first 36 bytes of the input buffer contains information about
223 // thread group and global sizes.
224 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
225 36 + VA.getLocMemOffset());
226 InVals.push_back(Arg);
229 assert(VA.isRegLoc() && "Parameter must be in a register!");
231 unsigned Reg = VA.getLocReg();
233 if (VT == MVT::i64) {
234 // For now assume it is a pointer
235 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
236 &AMDGPU::SReg_64RegClass);
237 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
238 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
242 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
244 Reg = MF.addLiveIn(Reg, RC);
245 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
247 if (Arg.VT.isVector()) {
249 // Build a vector from the registers
250 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
251 unsigned NumElements = ParamType->getVectorNumElements();
253 SmallVector<SDValue, 4> Regs;
255 for (unsigned j = 1; j != NumElements; ++j) {
256 Reg = ArgLocs[ArgIdx++].getLocReg();
257 Reg = MF.addLiveIn(Reg, RC);
258 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
261 // Fill up the missing vector elements
262 NumElements = Arg.VT.getVectorNumElements() - NumElements;
263 for (unsigned j = 0; j != NumElements; ++j)
264 Regs.push_back(DAG.getUNDEF(VT));
266 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
267 Regs.data(), Regs.size()));
271 InVals.push_back(Val);
276 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
277 MachineInstr * MI, MachineBasicBlock * BB) const {
279 MachineBasicBlock::iterator I = *MI;
281 switch (MI->getOpcode()) {
283 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
284 case AMDGPU::BRANCH: return BB;
285 case AMDGPU::SI_ADDR64_RSRC: {
286 const SIInstrInfo *TII =
287 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
288 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
289 unsigned SuperReg = MI->getOperand(0).getReg();
290 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
291 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
292 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
293 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
294 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
295 .addOperand(MI->getOperand(1));
296 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
298 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
299 .addImm(RSRC_DATA_FORMAT >> 32);
300 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
302 .addImm(AMDGPU::sub0)
304 .addImm(AMDGPU::sub1);
305 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
307 .addImm(AMDGPU::sub0_sub1)
309 .addImm(AMDGPU::sub2_sub3);
310 MI->eraseFromParent();
313 case AMDGPU::V_SUB_F64: {
314 const SIInstrInfo *TII =
315 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
316 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
317 MI->getOperand(0).getReg())
318 .addReg(MI->getOperand(1).getReg())
319 .addReg(MI->getOperand(2).getReg())
320 .addImm(0) /* src2 */
322 .addImm(0) /* CLAMP */
323 .addImm(0) /* OMOD */
324 .addImm(2); /* NEG */
325 MI->eraseFromParent();
332 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
333 if (!VT.isVector()) {
336 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
339 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
343 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
344 VT = VT.getScalarType();
349 switch (VT.getSimpleVT().SimpleTy) {
351 return false; /* There is V_MAD_F32 for f32 */
361 //===----------------------------------------------------------------------===//
362 // Custom DAG Lowering Operations
363 //===----------------------------------------------------------------------===//
365 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
366 MachineFunction &MF = DAG.getMachineFunction();
367 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
368 switch (Op.getOpcode()) {
369 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
370 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
371 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
372 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
373 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
374 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
375 case ISD::INTRINSIC_WO_CHAIN: {
376 unsigned IntrinsicID =
377 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
378 EVT VT = Op.getValueType();
380 //XXX: Hardcoded we only use two to store the pointer to the parameters.
381 unsigned NumUserSGPRs = 2;
382 switch (IntrinsicID) {
383 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
384 case Intrinsic::r600_read_ngroups_x:
385 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
386 case Intrinsic::r600_read_ngroups_y:
387 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
388 case Intrinsic::r600_read_ngroups_z:
389 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
390 case Intrinsic::r600_read_global_size_x:
391 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
392 case Intrinsic::r600_read_global_size_y:
393 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
394 case Intrinsic::r600_read_global_size_z:
395 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
396 case Intrinsic::r600_read_local_size_x:
397 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
398 case Intrinsic::r600_read_local_size_y:
399 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
400 case Intrinsic::r600_read_local_size_z:
401 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
402 case Intrinsic::r600_read_tgid_x:
403 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
404 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
405 case Intrinsic::r600_read_tgid_y:
406 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
407 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
408 case Intrinsic::r600_read_tgid_z:
409 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
410 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
411 case Intrinsic::r600_read_tidig_x:
412 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
414 case Intrinsic::r600_read_tidig_y:
415 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
417 case Intrinsic::r600_read_tidig_z:
418 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
420 case AMDGPUIntrinsic::SI_load_const: {
422 ResourceDescriptorToi128(Op.getOperand(1), DAG),
426 MachineMemOperand *MMO = new MachineMemOperand(MachinePointerInfo(),
427 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
428 VT.getSizeInBits() / 8, 4);
429 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
430 Op->getVTList(), Ops, 2, VT, MMO);
432 case AMDGPUIntrinsic::SI_sample:
433 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
434 case AMDGPUIntrinsic::SI_sampleb:
435 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
436 case AMDGPUIntrinsic::SI_sampled:
437 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
438 case AMDGPUIntrinsic::SI_samplel:
439 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
440 case AMDGPUIntrinsic::SI_vs_load_input:
441 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
442 ResourceDescriptorToi128(Op.getOperand(1), DAG),
451 /// \brief Helper function for LowerBRCOND
452 static SDNode *findUser(SDValue Value, unsigned Opcode) {
454 SDNode *Parent = Value.getNode();
455 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
458 if (I.getUse().get() != Value)
461 if (I->getOpcode() == Opcode)
467 /// This transforms the control flow intrinsics to get the branch destination as
468 /// last parameter, also switches branch target with BR if the need arise
469 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
470 SelectionDAG &DAG) const {
474 SDNode *Intr = BRCOND.getOperand(1).getNode();
475 SDValue Target = BRCOND.getOperand(2);
478 if (Intr->getOpcode() == ISD::SETCC) {
479 // As long as we negate the condition everything is fine
480 SDNode *SetCC = Intr;
481 assert(SetCC->getConstantOperandVal(1) == 1);
482 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
484 Intr = SetCC->getOperand(0).getNode();
487 // Get the target from BR if we don't negate the condition
488 BR = findUser(BRCOND, ISD::BR);
489 Target = BR->getOperand(1);
492 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
494 // Build the result and
495 SmallVector<EVT, 4> Res;
496 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
497 Res.push_back(Intr->getValueType(i));
499 // operands of the new intrinsic call
500 SmallVector<SDValue, 4> Ops;
501 Ops.push_back(BRCOND.getOperand(0));
502 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
503 Ops.push_back(Intr->getOperand(i));
504 Ops.push_back(Target);
506 // build the new intrinsic call
507 SDNode *Result = DAG.getNode(
508 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
509 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
512 // Give the branch instruction our target
517 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
520 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
522 // Copy the intrinsic results to registers
523 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
524 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
528 Chain = DAG.getCopyToReg(
530 CopyToReg->getOperand(1),
531 SDValue(Result, i - 1),
534 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
537 // Remove the old intrinsic from the chain
538 DAG.ReplaceAllUsesOfValueWith(
539 SDValue(Intr, Intr->getNumValues() - 1),
540 Intr->getOperand(0));
545 SDValue SITargetLowering::ResourceDescriptorToi128(SDValue Op,
546 SelectionDAG &DAG) const {
548 if (Op.getValueType() == MVT::i128) {
552 assert(Op.getOpcode() == ISD::UNDEF);
554 return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), MVT::i128,
555 DAG.getConstant(0, MVT::i64),
556 DAG.getConstant(0, MVT::i64));
559 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
561 SelectionDAG &DAG) const {
562 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
564 ResourceDescriptorToi128(Op.getOperand(3), DAG),
568 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
569 SDValue LHS = Op.getOperand(0);
570 SDValue RHS = Op.getOperand(1);
571 SDValue True = Op.getOperand(2);
572 SDValue False = Op.getOperand(3);
573 SDValue CC = Op.getOperand(4);
574 EVT VT = Op.getValueType();
577 // Possible Min/Max pattern
578 SDValue MinMax = LowerMinMax(Op, DAG);
579 if (MinMax.getNode()) {
583 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
584 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
587 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
588 SelectionDAG &DAG) const {
589 EVT VT = Op.getValueType();
592 if (VT != MVT::i64) {
596 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
597 DAG.getConstant(31, MVT::i32));
599 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
602 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
603 SelectionDAG &DAG) const {
604 EVT VT = Op.getValueType();
607 if (VT != MVT::i64) {
611 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
612 DAG.getConstant(0, MVT::i32));
615 //===----------------------------------------------------------------------===//
616 // Custom DAG optimizations
617 //===----------------------------------------------------------------------===//
619 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
620 DAGCombinerInfo &DCI) const {
621 SelectionDAG &DAG = DCI.DAG;
623 EVT VT = N->getValueType(0);
625 switch (N->getOpcode()) {
627 case ISD::SELECT_CC: {
629 ConstantSDNode *True, *False;
630 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
631 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
632 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
633 && True->isAllOnesValue()
634 && False->isNullValue()
636 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
637 N->getOperand(1), N->getOperand(4));
643 SDValue Arg0 = N->getOperand(0);
644 SDValue Arg1 = N->getOperand(1);
645 SDValue CC = N->getOperand(2);
646 ConstantSDNode * C = NULL;
647 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
649 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
651 && Arg0.getOpcode() == ISD::SIGN_EXTEND
652 && Arg0.getOperand(0).getValueType() == MVT::i1
653 && (C = dyn_cast<ConstantSDNode>(Arg1))
655 && CCOp == ISD::SETNE) {
656 return SimplifySetCC(VT, Arg0.getOperand(0),
657 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
665 /// \brief Test if RegClass is one of the VSrc classes
666 static bool isVSrc(unsigned RegClass) {
667 return AMDGPU::VSrc_32RegClassID == RegClass ||
668 AMDGPU::VSrc_64RegClassID == RegClass;
671 /// \brief Test if RegClass is one of the SSrc classes
672 static bool isSSrc(unsigned RegClass) {
673 return AMDGPU::SSrc_32RegClassID == RegClass ||
674 AMDGPU::SSrc_64RegClassID == RegClass;
677 /// \brief Analyze the possible immediate value Op
679 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
680 /// and the immediate value if it's a literal immediate
681 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
688 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
689 if (Node->getZExtValue() >> 32) {
692 Imm.I = Node->getSExtValue();
693 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
694 Imm.F = Node->getValueAPF().convertToFloat();
696 return -1; // It isn't an immediate
698 if ((Imm.I >= -16 && Imm.I <= 64) ||
699 Imm.F == 0.5f || Imm.F == -0.5f ||
700 Imm.F == 1.0f || Imm.F == -1.0f ||
701 Imm.F == 2.0f || Imm.F == -2.0f ||
702 Imm.F == 4.0f || Imm.F == -4.0f)
703 return 0; // It's an inline immediate
705 return Imm.I; // It's a literal immediate
708 /// \brief Try to fold an immediate directly into an instruction
709 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
710 bool &ScalarSlotUsed) const {
712 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
713 const SIInstrInfo *TII =
714 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
715 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
718 const SDValue &Op = Mov->getOperand(0);
719 int32_t Value = analyzeImmediate(Op.getNode());
721 // Not an immediate at all
724 } else if (Value == 0) {
725 // Inline immediates can always be fold
729 } else if (Value == Immediate) {
730 // Already fold literal immediate
734 } else if (!ScalarSlotUsed && !Immediate) {
735 // Fold this literal immediate
736 ScalarSlotUsed = true;
746 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
747 SelectionDAG &DAG, const SDValue &Op) const {
748 const SIInstrInfo *TII =
749 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
750 const SIRegisterInfo &TRI = TII->getRegisterInfo();
752 if (!Op->isMachineOpcode()) {
753 switch(Op->getOpcode()) {
754 case ISD::CopyFromReg: {
755 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
756 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
757 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
758 return MRI.getRegClass(Reg);
760 return TRI.getPhysRegClass(Reg);
762 default: return NULL;
765 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
766 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
767 if (OpClassID != -1) {
768 return TRI.getRegClass(OpClassID);
770 switch(Op.getMachineOpcode()) {
771 case AMDGPU::COPY_TO_REGCLASS:
772 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
773 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
775 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
776 // class, then the register class for the value could be either a
777 // VReg or and SReg. In order to get a more accurate
778 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
779 OpClassID == AMDGPU::VSrc_64RegClassID) {
780 return getRegClassForNode(DAG, Op.getOperand(0));
782 return TRI.getRegClass(OpClassID);
783 case AMDGPU::EXTRACT_SUBREG: {
784 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
785 const TargetRegisterClass *SuperClass =
786 getRegClassForNode(DAG, Op.getOperand(0));
787 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
789 case AMDGPU::REG_SEQUENCE:
790 // Operand 0 is the register class id for REG_SEQUENCE instructions.
791 return TRI.getRegClass(
792 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
794 return getRegClassFor(Op.getSimpleValueType());
798 /// \brief Does "Op" fit into register class "RegClass" ?
799 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
800 unsigned RegClass) const {
801 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
802 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
806 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
809 /// \brief Make sure that we don't exeed the number of allowed scalars
810 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
812 bool &ScalarSlotUsed) const {
814 // First map the operands register class to a destination class
815 if (RegClass == AMDGPU::VSrc_32RegClassID)
816 RegClass = AMDGPU::VReg_32RegClassID;
817 else if (RegClass == AMDGPU::VSrc_64RegClassID)
818 RegClass = AMDGPU::VReg_64RegClassID;
822 // Nothing todo if they fit naturaly
823 if (fitsRegClass(DAG, Operand, RegClass))
826 // If the scalar slot isn't used yet use it now
827 if (!ScalarSlotUsed) {
828 ScalarSlotUsed = true;
832 // This is a conservative aproach, it is possible that we can't determine
833 // the correct register class and copy too often, but better save than sorry.
834 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
835 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
836 Operand.getValueType(), Operand, RC);
837 Operand = SDValue(Node, 0);
840 /// \returns true if \p Node's operands are different from the SDValue list
842 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
843 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
844 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
851 /// \brief Try to fold the Nodes operands into the Node
852 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
853 SelectionDAG &DAG) const {
855 // Original encoding (either e32 or e64)
856 int Opcode = Node->getMachineOpcode();
857 const SIInstrInfo *TII =
858 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
859 const MCInstrDesc *Desc = &TII->get(Opcode);
861 unsigned NumDefs = Desc->getNumDefs();
862 unsigned NumOps = Desc->getNumOperands();
864 // Commuted opcode if available
865 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
866 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
868 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
869 assert(!DescRev || DescRev->getNumOperands() == NumOps);
871 // e64 version if available, -1 otherwise
872 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
873 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
875 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
876 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
878 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
879 bool HaveVSrc = false, HaveSSrc = false;
881 // First figure out what we alread have in this instruction
882 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
883 i != e && Op < NumOps; ++i, ++Op) {
885 unsigned RegClass = Desc->OpInfo[Op].RegClass;
886 if (isVSrc(RegClass))
888 else if (isSSrc(RegClass))
893 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
894 if (Imm != -1 && Imm != 0) {
900 // If we neither have VSrc nor SSrc it makes no sense to continue
901 if (!HaveVSrc && !HaveSSrc)
904 // No scalar allowed when we have both VSrc and SSrc
905 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
907 // Second go over the operands and try to fold them
908 std::vector<SDValue> Ops;
909 bool Promote2e64 = false;
910 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
911 i != e && Op < NumOps; ++i, ++Op) {
913 const SDValue &Operand = Node->getOperand(i);
914 Ops.push_back(Operand);
916 // Already folded immediate ?
917 if (isa<ConstantSDNode>(Operand.getNode()) ||
918 isa<ConstantFPSDNode>(Operand.getNode()))
921 // Is this a VSrc or SSrc operand ?
922 unsigned RegClass = Desc->OpInfo[Op].RegClass;
923 if (isVSrc(RegClass) || isSSrc(RegClass)) {
924 // Try to fold the immediates
925 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
926 // Folding didn't worked, make sure we don't hit the SReg limit
927 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
932 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
934 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
935 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
937 // Test if it makes sense to swap operands
938 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
939 (!fitsRegClass(DAG, Ops[1], RegClass) &&
940 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
942 // Swap commutable operands
943 SDValue Tmp = Ops[1];
953 if (DescE64 && !Immediate) {
955 // Test if it makes sense to switch to e64 encoding
956 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
957 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
961 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
962 (!fitsRegClass(DAG, Ops[i], RegClass) &&
963 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
965 // Switch to e64 encoding
975 // Add the modifier flags while promoting
976 for (unsigned i = 0; i < 4; ++i)
977 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
980 // Add optional chain and glue
981 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
982 Ops.push_back(Node->getOperand(i));
984 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
985 // this case a brand new node is always be created, even if the operands
986 // are the same as before. So, manually check if anything has been changed.
987 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
991 // Create a complete new instruction
992 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
995 /// \brief Helper function for adjustWritemask
996 static unsigned SubIdx2Lane(unsigned Idx) {
999 case AMDGPU::sub0: return 0;
1000 case AMDGPU::sub1: return 1;
1001 case AMDGPU::sub2: return 2;
1002 case AMDGPU::sub3: return 3;
1006 /// \brief Adjust the writemask of MIMG instructions
1007 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1008 SelectionDAG &DAG) const {
1009 SDNode *Users[4] = { };
1010 unsigned Writemask = 0, Lane = 0;
1012 // Try to figure out the used register components
1013 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1016 // Abort if we can't understand the usage
1017 if (!I->isMachineOpcode() ||
1018 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1021 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1023 // Abort if we have more than one user per component
1028 Writemask |= 1 << Lane;
1031 // Abort if all components are used
1032 if (Writemask == 0xf)
1035 // Adjust the writemask in the node
1036 std::vector<SDValue> Ops;
1037 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
1038 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1039 Ops.push_back(Node->getOperand(i));
1040 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1042 // If we only got one lane, replace it with a copy
1043 if (Writemask == (1U << Lane)) {
1044 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1045 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1046 SDLoc(), Users[Lane]->getValueType(0),
1047 SDValue(Node, 0), RC);
1048 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1052 // Update the users of the node with the new indices
1053 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1055 SDNode *User = Users[i];
1059 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1060 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1064 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1065 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1066 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1071 /// \brief Fold the instructions after slecting them
1072 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1073 SelectionDAG &DAG) const {
1074 const SIInstrInfo *TII =
1075 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1076 Node = AdjustRegClass(Node, DAG);
1078 if (TII->isMIMG(Node->getMachineOpcode()))
1079 adjustWritemask(Node, DAG);
1081 return foldOperands(Node, DAG);
1084 /// \brief Assign the register class depending on the number of
1085 /// bits set in the writemask
1086 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1087 SDNode *Node) const {
1088 const SIInstrInfo *TII =
1089 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1090 if (!TII->isMIMG(MI->getOpcode()))
1093 unsigned VReg = MI->getOperand(0).getReg();
1094 unsigned Writemask = MI->getOperand(1).getImm();
1095 unsigned BitsSet = 0;
1096 for (unsigned i = 0; i < 4; ++i)
1097 BitsSet += Writemask & (1 << i) ? 1 : 0;
1099 const TargetRegisterClass *RC;
1102 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1103 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1104 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1107 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1108 MRI.setRegClass(VReg, RC);
1111 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1112 SelectionDAG &DAG) const {
1115 unsigned NewOpcode = N->getMachineOpcode();
1117 switch (N->getMachineOpcode()) {
1119 case AMDGPU::S_LOAD_DWORD_IMM:
1120 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1122 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1123 if (NewOpcode == N->getMachineOpcode()) {
1124 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1127 case AMDGPU::S_LOAD_DWORDX4_IMM:
1128 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1129 if (NewOpcode == N->getMachineOpcode()) {
1130 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1132 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1135 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1137 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1138 DAG.getConstant(0, MVT::i64)), 0),
1140 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1142 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1147 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1148 const TargetRegisterClass *RC,
1149 unsigned Reg, EVT VT) const {
1150 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1152 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1153 cast<RegisterSDNode>(VReg)->getReg(), VT);