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::v32i8, &AMDGPU::SReg_256RegClass);
38 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
40 addRegisterClass(MVT::i32, &AMDGPU::VSrc_32RegClass);
41 addRegisterClass(MVT::f32, &AMDGPU::VSrc_32RegClass);
43 addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
44 addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
45 addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
47 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
48 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
49 addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
51 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
52 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
54 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
55 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
57 computeRegisterProperties();
59 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
60 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
61 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
62 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
64 setOperationAction(ISD::ADD, MVT::i64, Legal);
65 setOperationAction(ISD::ADD, MVT::i32, Legal);
67 setOperationAction(ISD::BITCAST, MVT::i128, Legal);
69 // We need to custom lower vector stores from local memory
70 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
71 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
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);
85 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
86 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
87 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
89 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
91 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
92 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
94 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
96 setTargetDAGCombine(ISD::SELECT_CC);
98 setTargetDAGCombine(ISD::SETCC);
100 setSchedulingPreference(Sched::RegPressure);
103 //===----------------------------------------------------------------------===//
104 // TargetLowering queries
105 //===----------------------------------------------------------------------===//
107 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
108 bool *IsFast) const {
109 // XXX: This depends on the address space and also we may want to revist
110 // the alignment values we specify in the DataLayout.
111 return VT.bitsGT(MVT::i32);
114 bool SITargetLowering::shouldSplitVectorElementType(EVT VT) const {
115 return VT.bitsLE(MVT::i8);
118 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
119 SDLoc DL, SDValue Chain,
120 unsigned Offset) const {
121 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
122 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
123 AMDGPUAS::CONSTANT_ADDRESS);
124 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
125 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
126 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
127 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
128 DAG.getConstant(Offset, MVT::i64));
129 return DAG.getLoad(VT, DL, Chain, Ptr,
130 MachinePointerInfo(UndefValue::get(PtrTy)),
131 false, false, false, ArgVT.getSizeInBits() >> 3);
135 SDValue SITargetLowering::LowerFormalArguments(
137 CallingConv::ID CallConv,
139 const SmallVectorImpl<ISD::InputArg> &Ins,
140 SDLoc DL, SelectionDAG &DAG,
141 SmallVectorImpl<SDValue> &InVals) const {
143 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
145 MachineFunction &MF = DAG.getMachineFunction();
146 FunctionType *FType = MF.getFunction()->getFunctionType();
147 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
149 assert(CallConv == CallingConv::C);
151 SmallVector<ISD::InputArg, 16> Splits;
152 uint32_t Skipped = 0;
154 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
155 const ISD::InputArg &Arg = Ins[i];
157 // First check if it's a PS input addr
158 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
160 assert((PSInputNum <= 15) && "Too many PS inputs!");
163 // We can savely skip PS inputs
169 Info->PSInputAddr |= 1 << PSInputNum++;
172 // Second split vertices into their elements
173 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
174 ISD::InputArg NewArg = Arg;
175 NewArg.Flags.setSplit();
176 NewArg.VT = Arg.VT.getVectorElementType();
178 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
179 // three or five element vertex only needs three or five registers,
180 // NOT four or eigth.
181 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
182 unsigned NumElements = ParamType->getVectorNumElements();
184 for (unsigned j = 0; j != NumElements; ++j) {
185 Splits.push_back(NewArg);
186 NewArg.PartOffset += NewArg.VT.getStoreSize();
190 Splits.push_back(Arg);
194 SmallVector<CCValAssign, 16> ArgLocs;
195 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
196 getTargetMachine(), ArgLocs, *DAG.getContext());
198 // At least one interpolation mode must be enabled or else the GPU will hang.
199 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
200 Info->PSInputAddr |= 1;
201 CCInfo.AllocateReg(AMDGPU::VGPR0);
202 CCInfo.AllocateReg(AMDGPU::VGPR1);
205 // The pointer to the list of arguments is stored in SGPR0, SGPR1
206 if (Info->ShaderType == ShaderType::COMPUTE) {
207 CCInfo.AllocateReg(AMDGPU::SGPR0);
208 CCInfo.AllocateReg(AMDGPU::SGPR1);
209 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
212 AnalyzeFormalArguments(CCInfo, Splits);
214 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
216 const ISD::InputArg &Arg = Ins[i];
217 if (Skipped & (1 << i)) {
218 InVals.push_back(DAG.getUNDEF(Arg.VT));
222 CCValAssign &VA = ArgLocs[ArgIdx++];
223 EVT VT = VA.getLocVT();
226 // The first 36 bytes of the input buffer contains information about
227 // thread group and global sizes.
228 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
229 36 + VA.getLocMemOffset());
230 InVals.push_back(Arg);
233 assert(VA.isRegLoc() && "Parameter must be in a register!");
235 unsigned Reg = VA.getLocReg();
237 if (VT == MVT::i64) {
238 // For now assume it is a pointer
239 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
240 &AMDGPU::SReg_64RegClass);
241 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
242 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
246 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
248 Reg = MF.addLiveIn(Reg, RC);
249 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
251 if (Arg.VT.isVector()) {
253 // Build a vector from the registers
254 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
255 unsigned NumElements = ParamType->getVectorNumElements();
257 SmallVector<SDValue, 4> Regs;
259 for (unsigned j = 1; j != NumElements; ++j) {
260 Reg = ArgLocs[ArgIdx++].getLocReg();
261 Reg = MF.addLiveIn(Reg, RC);
262 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
265 // Fill up the missing vector elements
266 NumElements = Arg.VT.getVectorNumElements() - NumElements;
267 for (unsigned j = 0; j != NumElements; ++j)
268 Regs.push_back(DAG.getUNDEF(VT));
270 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
271 Regs.data(), Regs.size()));
275 InVals.push_back(Val);
280 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
281 MachineInstr * MI, MachineBasicBlock * BB) const {
283 MachineBasicBlock::iterator I = *MI;
285 switch (MI->getOpcode()) {
287 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
288 case AMDGPU::BRANCH: return BB;
289 case AMDGPU::SI_ADDR64_RSRC: {
290 const SIInstrInfo *TII =
291 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
292 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
293 unsigned SuperReg = MI->getOperand(0).getReg();
294 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
295 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
296 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
297 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
298 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
299 .addOperand(MI->getOperand(1));
300 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
302 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
303 .addImm(RSRC_DATA_FORMAT >> 32);
304 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
306 .addImm(AMDGPU::sub0)
308 .addImm(AMDGPU::sub1);
309 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
311 .addImm(AMDGPU::sub0_sub1)
313 .addImm(AMDGPU::sub2_sub3);
314 MI->eraseFromParent();
317 case AMDGPU::V_SUB_F64: {
318 const SIInstrInfo *TII =
319 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
320 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
321 MI->getOperand(0).getReg())
322 .addReg(MI->getOperand(1).getReg())
323 .addReg(MI->getOperand(2).getReg())
324 .addImm(0) /* src2 */
326 .addImm(0) /* CLAMP */
327 .addImm(0) /* OMOD */
328 .addImm(2); /* NEG */
329 MI->eraseFromParent();
336 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
337 if (!VT.isVector()) {
340 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
343 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
347 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
348 VT = VT.getScalarType();
353 switch (VT.getSimpleVT().SimpleTy) {
355 return false; /* There is V_MAD_F32 for f32 */
365 //===----------------------------------------------------------------------===//
366 // Custom DAG Lowering Operations
367 //===----------------------------------------------------------------------===//
369 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
370 MachineFunction &MF = DAG.getMachineFunction();
371 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
372 switch (Op.getOpcode()) {
373 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
374 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
376 LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
377 if (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
378 Op.getValueType().isVector()) {
379 SDValue MergedValues[2] = {
380 SplitVectorLoad(Op, DAG),
383 return DAG.getMergeValues(MergedValues, 2, SDLoc(Op));
388 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
389 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
390 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
391 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
392 case ISD::INTRINSIC_WO_CHAIN: {
393 unsigned IntrinsicID =
394 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
395 EVT VT = Op.getValueType();
397 //XXX: Hardcoded we only use two to store the pointer to the parameters.
398 unsigned NumUserSGPRs = 2;
399 switch (IntrinsicID) {
400 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
401 case Intrinsic::r600_read_ngroups_x:
402 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
403 case Intrinsic::r600_read_ngroups_y:
404 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
405 case Intrinsic::r600_read_ngroups_z:
406 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
407 case Intrinsic::r600_read_global_size_x:
408 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
409 case Intrinsic::r600_read_global_size_y:
410 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
411 case Intrinsic::r600_read_global_size_z:
412 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
413 case Intrinsic::r600_read_local_size_x:
414 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
415 case Intrinsic::r600_read_local_size_y:
416 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
417 case Intrinsic::r600_read_local_size_z:
418 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
419 case Intrinsic::r600_read_tgid_x:
420 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
421 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
422 case Intrinsic::r600_read_tgid_y:
423 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
424 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
425 case Intrinsic::r600_read_tgid_z:
426 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
427 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
428 case Intrinsic::r600_read_tidig_x:
429 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
431 case Intrinsic::r600_read_tidig_y:
432 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
434 case Intrinsic::r600_read_tidig_z:
435 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
437 case AMDGPUIntrinsic::SI_load_const: {
439 ResourceDescriptorToi128(Op.getOperand(1), DAG),
443 MachineMemOperand *MMO = MF.getMachineMemOperand(
444 MachinePointerInfo(),
445 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
446 VT.getSizeInBits() / 8, 4);
447 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
448 Op->getVTList(), Ops, 2, VT, MMO);
450 case AMDGPUIntrinsic::SI_sample:
451 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
452 case AMDGPUIntrinsic::SI_sampleb:
453 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
454 case AMDGPUIntrinsic::SI_sampled:
455 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
456 case AMDGPUIntrinsic::SI_samplel:
457 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
458 case AMDGPUIntrinsic::SI_vs_load_input:
459 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
460 ResourceDescriptorToi128(Op.getOperand(1), DAG),
469 /// \brief Helper function for LowerBRCOND
470 static SDNode *findUser(SDValue Value, unsigned Opcode) {
472 SDNode *Parent = Value.getNode();
473 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
476 if (I.getUse().get() != Value)
479 if (I->getOpcode() == Opcode)
485 /// This transforms the control flow intrinsics to get the branch destination as
486 /// last parameter, also switches branch target with BR if the need arise
487 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
488 SelectionDAG &DAG) const {
492 SDNode *Intr = BRCOND.getOperand(1).getNode();
493 SDValue Target = BRCOND.getOperand(2);
496 if (Intr->getOpcode() == ISD::SETCC) {
497 // As long as we negate the condition everything is fine
498 SDNode *SetCC = Intr;
499 assert(SetCC->getConstantOperandVal(1) == 1);
500 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
502 Intr = SetCC->getOperand(0).getNode();
505 // Get the target from BR if we don't negate the condition
506 BR = findUser(BRCOND, ISD::BR);
507 Target = BR->getOperand(1);
510 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
512 // Build the result and
513 SmallVector<EVT, 4> Res;
514 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
515 Res.push_back(Intr->getValueType(i));
517 // operands of the new intrinsic call
518 SmallVector<SDValue, 4> Ops;
519 Ops.push_back(BRCOND.getOperand(0));
520 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
521 Ops.push_back(Intr->getOperand(i));
522 Ops.push_back(Target);
524 // build the new intrinsic call
525 SDNode *Result = DAG.getNode(
526 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
527 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
530 // Give the branch instruction our target
535 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
538 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
540 // Copy the intrinsic results to registers
541 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
542 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
546 Chain = DAG.getCopyToReg(
548 CopyToReg->getOperand(1),
549 SDValue(Result, i - 1),
552 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
555 // Remove the old intrinsic from the chain
556 DAG.ReplaceAllUsesOfValueWith(
557 SDValue(Intr, Intr->getNumValues() - 1),
558 Intr->getOperand(0));
563 SDValue SITargetLowering::ResourceDescriptorToi128(SDValue Op,
564 SelectionDAG &DAG) const {
566 if (Op.getValueType() == MVT::i128) {
570 assert(Op.getOpcode() == ISD::UNDEF);
572 return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), MVT::i128,
573 DAG.getConstant(0, MVT::i64),
574 DAG.getConstant(0, MVT::i64));
577 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
579 SelectionDAG &DAG) const {
580 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
582 ResourceDescriptorToi128(Op.getOperand(3), DAG),
586 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
587 SDValue LHS = Op.getOperand(0);
588 SDValue RHS = Op.getOperand(1);
589 SDValue True = Op.getOperand(2);
590 SDValue False = Op.getOperand(3);
591 SDValue CC = Op.getOperand(4);
592 EVT VT = Op.getValueType();
595 // Possible Min/Max pattern
596 SDValue MinMax = LowerMinMax(Op, DAG);
597 if (MinMax.getNode()) {
601 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
602 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
605 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
606 SelectionDAG &DAG) const {
607 EVT VT = Op.getValueType();
610 if (VT != MVT::i64) {
614 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
615 DAG.getConstant(31, MVT::i32));
617 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
620 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
621 SelectionDAG &DAG) const {
622 EVT VT = Op.getValueType();
625 if (VT != MVT::i64) {
629 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
630 DAG.getConstant(0, MVT::i32));
633 //===----------------------------------------------------------------------===//
634 // Custom DAG optimizations
635 //===----------------------------------------------------------------------===//
637 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
638 DAGCombinerInfo &DCI) const {
639 SelectionDAG &DAG = DCI.DAG;
641 EVT VT = N->getValueType(0);
643 switch (N->getOpcode()) {
645 case ISD::SELECT_CC: {
647 ConstantSDNode *True, *False;
648 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
649 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
650 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
651 && True->isAllOnesValue()
652 && False->isNullValue()
654 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
655 N->getOperand(1), N->getOperand(4));
661 SDValue Arg0 = N->getOperand(0);
662 SDValue Arg1 = N->getOperand(1);
663 SDValue CC = N->getOperand(2);
664 ConstantSDNode * C = NULL;
665 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
667 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
669 && Arg0.getOpcode() == ISD::SIGN_EXTEND
670 && Arg0.getOperand(0).getValueType() == MVT::i1
671 && (C = dyn_cast<ConstantSDNode>(Arg1))
673 && CCOp == ISD::SETNE) {
674 return SimplifySetCC(VT, Arg0.getOperand(0),
675 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
683 /// \brief Test if RegClass is one of the VSrc classes
684 static bool isVSrc(unsigned RegClass) {
685 return AMDGPU::VSrc_32RegClassID == RegClass ||
686 AMDGPU::VSrc_64RegClassID == RegClass;
689 /// \brief Test if RegClass is one of the SSrc classes
690 static bool isSSrc(unsigned RegClass) {
691 return AMDGPU::SSrc_32RegClassID == RegClass ||
692 AMDGPU::SSrc_64RegClassID == RegClass;
695 /// \brief Analyze the possible immediate value Op
697 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
698 /// and the immediate value if it's a literal immediate
699 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
706 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
707 if (Node->getZExtValue() >> 32) {
710 Imm.I = Node->getSExtValue();
711 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
712 Imm.F = Node->getValueAPF().convertToFloat();
714 return -1; // It isn't an immediate
716 if ((Imm.I >= -16 && Imm.I <= 64) ||
717 Imm.F == 0.5f || Imm.F == -0.5f ||
718 Imm.F == 1.0f || Imm.F == -1.0f ||
719 Imm.F == 2.0f || Imm.F == -2.0f ||
720 Imm.F == 4.0f || Imm.F == -4.0f)
721 return 0; // It's an inline immediate
723 return Imm.I; // It's a literal immediate
726 /// \brief Try to fold an immediate directly into an instruction
727 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
728 bool &ScalarSlotUsed) const {
730 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
731 const SIInstrInfo *TII =
732 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
733 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
736 const SDValue &Op = Mov->getOperand(0);
737 int32_t Value = analyzeImmediate(Op.getNode());
739 // Not an immediate at all
742 } else if (Value == 0) {
743 // Inline immediates can always be fold
747 } else if (Value == Immediate) {
748 // Already fold literal immediate
752 } else if (!ScalarSlotUsed && !Immediate) {
753 // Fold this literal immediate
754 ScalarSlotUsed = true;
764 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
765 SelectionDAG &DAG, const SDValue &Op) const {
766 const SIInstrInfo *TII =
767 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
768 const SIRegisterInfo &TRI = TII->getRegisterInfo();
770 if (!Op->isMachineOpcode()) {
771 switch(Op->getOpcode()) {
772 case ISD::CopyFromReg: {
773 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
774 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
775 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
776 return MRI.getRegClass(Reg);
778 return TRI.getPhysRegClass(Reg);
780 default: return NULL;
783 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
784 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
785 if (OpClassID != -1) {
786 return TRI.getRegClass(OpClassID);
788 switch(Op.getMachineOpcode()) {
789 case AMDGPU::COPY_TO_REGCLASS:
790 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
791 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
793 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
794 // class, then the register class for the value could be either a
795 // VReg or and SReg. In order to get a more accurate
796 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
797 OpClassID == AMDGPU::VSrc_64RegClassID) {
798 return getRegClassForNode(DAG, Op.getOperand(0));
800 return TRI.getRegClass(OpClassID);
801 case AMDGPU::EXTRACT_SUBREG: {
802 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
803 const TargetRegisterClass *SuperClass =
804 getRegClassForNode(DAG, Op.getOperand(0));
805 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
807 case AMDGPU::REG_SEQUENCE:
808 // Operand 0 is the register class id for REG_SEQUENCE instructions.
809 return TRI.getRegClass(
810 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
812 return getRegClassFor(Op.getSimpleValueType());
816 /// \brief Does "Op" fit into register class "RegClass" ?
817 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
818 unsigned RegClass) const {
819 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
820 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
824 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
827 /// \brief Make sure that we don't exeed the number of allowed scalars
828 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
830 bool &ScalarSlotUsed) const {
832 // First map the operands register class to a destination class
833 if (RegClass == AMDGPU::VSrc_32RegClassID)
834 RegClass = AMDGPU::VReg_32RegClassID;
835 else if (RegClass == AMDGPU::VSrc_64RegClassID)
836 RegClass = AMDGPU::VReg_64RegClassID;
840 // Nothing todo if they fit naturaly
841 if (fitsRegClass(DAG, Operand, RegClass))
844 // If the scalar slot isn't used yet use it now
845 if (!ScalarSlotUsed) {
846 ScalarSlotUsed = true;
850 // This is a conservative aproach, it is possible that we can't determine
851 // the correct register class and copy too often, but better save than sorry.
852 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
853 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
854 Operand.getValueType(), Operand, RC);
855 Operand = SDValue(Node, 0);
858 /// \returns true if \p Node's operands are different from the SDValue list
860 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
861 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
862 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
869 /// \brief Try to fold the Nodes operands into the Node
870 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
871 SelectionDAG &DAG) const {
873 // Original encoding (either e32 or e64)
874 int Opcode = Node->getMachineOpcode();
875 const SIInstrInfo *TII =
876 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
877 const MCInstrDesc *Desc = &TII->get(Opcode);
879 unsigned NumDefs = Desc->getNumDefs();
880 unsigned NumOps = Desc->getNumOperands();
882 // Commuted opcode if available
883 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
884 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
886 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
887 assert(!DescRev || DescRev->getNumOperands() == NumOps);
889 // e64 version if available, -1 otherwise
890 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
891 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
893 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
894 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
896 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
897 bool HaveVSrc = false, HaveSSrc = false;
899 // First figure out what we alread have in this instruction
900 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
901 i != e && Op < NumOps; ++i, ++Op) {
903 unsigned RegClass = Desc->OpInfo[Op].RegClass;
904 if (isVSrc(RegClass))
906 else if (isSSrc(RegClass))
911 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
912 if (Imm != -1 && Imm != 0) {
918 // If we neither have VSrc nor SSrc it makes no sense to continue
919 if (!HaveVSrc && !HaveSSrc)
922 // No scalar allowed when we have both VSrc and SSrc
923 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
925 // Second go over the operands and try to fold them
926 std::vector<SDValue> Ops;
927 bool Promote2e64 = false;
928 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
929 i != e && Op < NumOps; ++i, ++Op) {
931 const SDValue &Operand = Node->getOperand(i);
932 Ops.push_back(Operand);
934 // Already folded immediate ?
935 if (isa<ConstantSDNode>(Operand.getNode()) ||
936 isa<ConstantFPSDNode>(Operand.getNode()))
939 // Is this a VSrc or SSrc operand ?
940 unsigned RegClass = Desc->OpInfo[Op].RegClass;
941 if (isVSrc(RegClass) || isSSrc(RegClass)) {
942 // Try to fold the immediates
943 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
944 // Folding didn't worked, make sure we don't hit the SReg limit
945 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
950 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
952 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
953 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
955 // Test if it makes sense to swap operands
956 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
957 (!fitsRegClass(DAG, Ops[1], RegClass) &&
958 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
960 // Swap commutable operands
961 SDValue Tmp = Ops[1];
971 if (DescE64 && !Immediate) {
973 // Test if it makes sense to switch to e64 encoding
974 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
975 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
979 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
980 (!fitsRegClass(DAG, Ops[i], RegClass) &&
981 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
983 // Switch to e64 encoding
993 // Add the modifier flags while promoting
994 for (unsigned i = 0; i < 4; ++i)
995 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
998 // Add optional chain and glue
999 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1000 Ops.push_back(Node->getOperand(i));
1002 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1003 // this case a brand new node is always be created, even if the operands
1004 // are the same as before. So, manually check if anything has been changed.
1005 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1009 // Create a complete new instruction
1010 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1013 /// \brief Helper function for adjustWritemask
1014 static unsigned SubIdx2Lane(unsigned Idx) {
1017 case AMDGPU::sub0: return 0;
1018 case AMDGPU::sub1: return 1;
1019 case AMDGPU::sub2: return 2;
1020 case AMDGPU::sub3: return 3;
1024 /// \brief Adjust the writemask of MIMG instructions
1025 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1026 SelectionDAG &DAG) const {
1027 SDNode *Users[4] = { };
1028 unsigned Writemask = 0, Lane = 0;
1030 // Try to figure out the used register components
1031 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1034 // Abort if we can't understand the usage
1035 if (!I->isMachineOpcode() ||
1036 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1039 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1041 // Abort if we have more than one user per component
1046 Writemask |= 1 << Lane;
1049 // Abort if all components are used
1050 if (Writemask == 0xf)
1053 // Adjust the writemask in the node
1054 std::vector<SDValue> Ops;
1055 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
1056 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1057 Ops.push_back(Node->getOperand(i));
1058 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1060 // If we only got one lane, replace it with a copy
1061 if (Writemask == (1U << Lane)) {
1062 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1063 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1064 SDLoc(), Users[Lane]->getValueType(0),
1065 SDValue(Node, 0), RC);
1066 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1070 // Update the users of the node with the new indices
1071 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1073 SDNode *User = Users[i];
1077 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1078 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1082 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1083 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1084 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1089 /// \brief Fold the instructions after slecting them
1090 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1091 SelectionDAG &DAG) const {
1092 const SIInstrInfo *TII =
1093 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1094 Node = AdjustRegClass(Node, DAG);
1096 if (TII->isMIMG(Node->getMachineOpcode()))
1097 adjustWritemask(Node, DAG);
1099 return foldOperands(Node, DAG);
1102 /// \brief Assign the register class depending on the number of
1103 /// bits set in the writemask
1104 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1105 SDNode *Node) const {
1106 const SIInstrInfo *TII =
1107 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1108 if (!TII->isMIMG(MI->getOpcode()))
1111 unsigned VReg = MI->getOperand(0).getReg();
1112 unsigned Writemask = MI->getOperand(1).getImm();
1113 unsigned BitsSet = 0;
1114 for (unsigned i = 0; i < 4; ++i)
1115 BitsSet += Writemask & (1 << i) ? 1 : 0;
1117 const TargetRegisterClass *RC;
1120 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1121 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1122 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1125 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1126 MRI.setRegClass(VReg, RC);
1129 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1130 SelectionDAG &DAG) const {
1133 unsigned NewOpcode = N->getMachineOpcode();
1135 switch (N->getMachineOpcode()) {
1137 case AMDGPU::S_LOAD_DWORD_IMM:
1138 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1140 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1141 if (NewOpcode == N->getMachineOpcode()) {
1142 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1145 case AMDGPU::S_LOAD_DWORDX4_IMM:
1146 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1147 if (NewOpcode == N->getMachineOpcode()) {
1148 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1150 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1153 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1155 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1156 DAG.getConstant(0, MVT::i64)), 0),
1158 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1160 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1165 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1166 const TargetRegisterClass *RC,
1167 unsigned Reg, EVT VT) const {
1168 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1170 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1171 cast<RegisterSDNode>(VReg)->getReg(), VT);