R600/SI: Add support for 64-bit loads
[oota-llvm.git] / lib / Target / R600 / SIISelLowering.cpp
1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SIISelLowering.h"
16 #include "AMDGPU.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"
26
27 const uint64_t RSRC_DATA_FORMAT = 0xf00000000000LL;
28
29 using namespace llvm;
30
31 SITargetLowering::SITargetLowering(TargetMachine &TM) :
32     AMDGPUTargetLowering(TM) {
33
34   addRegisterClass(MVT::i1, &AMDGPU::SReg_64RegClass);
35   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
36
37   addRegisterClass(MVT::v16i8, &AMDGPU::SReg_128RegClass);
38   addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
39   addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
40
41   addRegisterClass(MVT::i32, &AMDGPU::VReg_32RegClass);
42   addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
43
44   addRegisterClass(MVT::v1i32, &AMDGPU::VReg_32RegClass);
45
46   addRegisterClass(MVT::v2i32, &AMDGPU::VReg_64RegClass);
47   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
48   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
49
50   addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
51   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
52   addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
53
54   addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
55   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
56
57   addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
58   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
59
60   computeRegisterProperties();
61
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);
66
67   setOperationAction(ISD::ADD, MVT::i64, Legal);
68   setOperationAction(ISD::ADD, MVT::i32, Legal);
69
70   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
71   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
72
73   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
74
75   setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
76
77   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
78
79   setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
80
81   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
82
83   setTargetDAGCombine(ISD::SELECT_CC);
84
85   setTargetDAGCombine(ISD::SETCC);
86
87   setSchedulingPreference(Sched::RegPressure);
88 }
89
90 //===----------------------------------------------------------------------===//
91 // TargetLowering queries
92 //===----------------------------------------------------------------------===//
93
94 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT  VT,
95                                                      bool *IsFast) const {
96   // XXX: This depends on the address space and also we may want to revist
97   // the alignment values we specify in the DataLayout.
98   return VT.bitsGT(MVT::i32);
99 }
100
101
102 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
103                                          SDLoc DL, SDValue Chain,
104                                          unsigned Offset) const {
105   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
106   PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
107                                             AMDGPUAS::CONSTANT_ADDRESS);
108   EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
109   SDValue BasePtr =  DAG.getCopyFromReg(Chain, DL,
110                            MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
111   SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
112                                              DAG.getConstant(Offset, MVT::i64));
113   return DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
114                             MachinePointerInfo(UndefValue::get(PtrTy)),
115                             VT, false, false, ArgVT.getSizeInBits() >> 3);
116
117 }
118
119 SDValue SITargetLowering::LowerFormalArguments(
120                                       SDValue Chain,
121                                       CallingConv::ID CallConv,
122                                       bool isVarArg,
123                                       const SmallVectorImpl<ISD::InputArg> &Ins,
124                                       SDLoc DL, SelectionDAG &DAG,
125                                       SmallVectorImpl<SDValue> &InVals) const {
126
127   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
128
129   MachineFunction &MF = DAG.getMachineFunction();
130   FunctionType *FType = MF.getFunction()->getFunctionType();
131   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
132
133   assert(CallConv == CallingConv::C);
134
135   SmallVector<ISD::InputArg, 16> Splits;
136   uint32_t Skipped = 0;
137
138   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
139     const ISD::InputArg &Arg = Ins[i];
140
141     // First check if it's a PS input addr
142     if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
143
144       assert((PSInputNum <= 15) && "Too many PS inputs!");
145
146       if (!Arg.Used) {
147         // We can savely skip PS inputs
148         Skipped |= 1 << i;
149         ++PSInputNum;
150         continue;
151       }
152
153       Info->PSInputAddr |= 1 << PSInputNum++;
154     }
155
156     // Second split vertices into their elements
157     if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
158       ISD::InputArg NewArg = Arg;
159       NewArg.Flags.setSplit();
160       NewArg.VT = Arg.VT.getVectorElementType();
161
162       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
163       // three or five element vertex only needs three or five registers,
164       // NOT four or eigth.
165       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
166       unsigned NumElements = ParamType->getVectorNumElements();
167
168       for (unsigned j = 0; j != NumElements; ++j) {
169         Splits.push_back(NewArg);
170         NewArg.PartOffset += NewArg.VT.getStoreSize();
171       }
172
173     } else {
174       Splits.push_back(Arg);
175     }
176   }
177
178   SmallVector<CCValAssign, 16> ArgLocs;
179   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
180                  getTargetMachine(), ArgLocs, *DAG.getContext());
181
182   // At least one interpolation mode must be enabled or else the GPU will hang.
183   if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
184     Info->PSInputAddr |= 1;
185     CCInfo.AllocateReg(AMDGPU::VGPR0);
186     CCInfo.AllocateReg(AMDGPU::VGPR1);
187   }
188
189   // The pointer to the list of arguments is stored in SGPR0, SGPR1
190   if (Info->ShaderType == ShaderType::COMPUTE) {
191     CCInfo.AllocateReg(AMDGPU::SGPR0);
192     CCInfo.AllocateReg(AMDGPU::SGPR1);
193     MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
194   }
195
196   AnalyzeFormalArguments(CCInfo, Splits);
197
198   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
199
200     const ISD::InputArg &Arg = Ins[i];
201     if (Skipped & (1 << i)) {
202       InVals.push_back(DAG.getUNDEF(Arg.VT));
203       continue;
204     }
205
206     CCValAssign &VA = ArgLocs[ArgIdx++];
207     EVT VT = VA.getLocVT();
208
209     if (VA.isMemLoc()) {
210       // The first 36 bytes of the input buffer contains information about
211       // thread group and global sizes.
212       SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
213                                    36 + VA.getLocMemOffset());
214       InVals.push_back(Arg);
215       continue;
216     }
217     assert(VA.isRegLoc() && "Parameter must be in a register!");
218
219     unsigned Reg = VA.getLocReg();
220
221     if (VT == MVT::i64) {
222       // For now assume it is a pointer
223       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
224                                      &AMDGPU::SReg_64RegClass);
225       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
226       InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
227       continue;
228     }
229
230     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
231
232     Reg = MF.addLiveIn(Reg, RC);
233     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
234
235     if (Arg.VT.isVector()) {
236
237       // Build a vector from the registers
238       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
239       unsigned NumElements = ParamType->getVectorNumElements();
240
241       SmallVector<SDValue, 4> Regs;
242       Regs.push_back(Val);
243       for (unsigned j = 1; j != NumElements; ++j) {
244         Reg = ArgLocs[ArgIdx++].getLocReg();
245         Reg = MF.addLiveIn(Reg, RC);
246         Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
247       }
248
249       // Fill up the missing vector elements
250       NumElements = Arg.VT.getVectorNumElements() - NumElements;
251       for (unsigned j = 0; j != NumElements; ++j)
252         Regs.push_back(DAG.getUNDEF(VT));
253
254       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
255                                    Regs.data(), Regs.size()));
256       continue;
257     }
258
259     InVals.push_back(Val);
260   }
261   return Chain;
262 }
263
264 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
265     MachineInstr * MI, MachineBasicBlock * BB) const {
266
267   MachineBasicBlock::iterator I = *MI;
268
269   switch (MI->getOpcode()) {
270   default:
271     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
272   case AMDGPU::BRANCH: return BB;
273   case AMDGPU::SI_ADDR64_RSRC: {
274     const SIInstrInfo *TII =
275       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
276     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
277     unsigned SuperReg = MI->getOperand(0).getReg();
278     unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
279     unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
280     unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
281     unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
282     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
283             .addOperand(MI->getOperand(1));
284     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
285             .addImm(0);
286     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
287             .addImm(RSRC_DATA_FORMAT >> 32);
288     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
289             .addReg(SubRegHiLo)
290             .addImm(AMDGPU::sub0)
291             .addReg(SubRegHiHi)
292             .addImm(AMDGPU::sub1);
293     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
294             .addReg(SubRegLo)
295             .addImm(AMDGPU::sub0_sub1)
296             .addReg(SubRegHi)
297             .addImm(AMDGPU::sub2_sub3);
298     MI->eraseFromParent();
299     break;
300   }
301   case AMDGPU::V_SUB_F64: {
302     const SIInstrInfo *TII =
303       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
304     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
305             MI->getOperand(0).getReg())
306             .addReg(MI->getOperand(1).getReg())
307             .addReg(MI->getOperand(2).getReg())
308             .addImm(0)  /* src2 */
309             .addImm(0)  /* ABS */
310             .addImm(0)  /* CLAMP */
311             .addImm(0)  /* OMOD */
312             .addImm(2); /* NEG */
313     MI->eraseFromParent();
314     break;
315   }
316   }
317   return BB;
318 }
319
320 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
321   return MVT::i1;
322 }
323
324 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
325   return MVT::i32;
326 }
327
328 //===----------------------------------------------------------------------===//
329 // Custom DAG Lowering Operations
330 //===----------------------------------------------------------------------===//
331
332 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
333   MachineFunction &MF = DAG.getMachineFunction();
334   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
335   switch (Op.getOpcode()) {
336   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
337   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
338   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
339   case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
340   case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
341   case ISD::INTRINSIC_WO_CHAIN: {
342     unsigned IntrinsicID =
343                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
344     EVT VT = Op.getValueType();
345     SDLoc DL(Op);
346     //XXX: Hardcoded we only use two to store the pointer to the parameters.
347     unsigned NumUserSGPRs = 2;
348     switch (IntrinsicID) {
349     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
350     case Intrinsic::r600_read_ngroups_x:
351       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
352     case Intrinsic::r600_read_ngroups_y:
353       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
354     case Intrinsic::r600_read_ngroups_z:
355       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
356     case Intrinsic::r600_read_global_size_x:
357       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
358     case Intrinsic::r600_read_global_size_y:
359       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
360     case Intrinsic::r600_read_global_size_z:
361       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
362     case Intrinsic::r600_read_local_size_x:
363       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
364     case Intrinsic::r600_read_local_size_y:
365       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
366     case Intrinsic::r600_read_local_size_z:
367       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
368     case Intrinsic::r600_read_tgid_x:
369       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
370                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
371     case Intrinsic::r600_read_tgid_y:
372       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
373                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
374     case Intrinsic::r600_read_tgid_z:
375       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
376                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
377     case Intrinsic::r600_read_tidig_x:
378       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
379                                   AMDGPU::VGPR0, VT);
380     case Intrinsic::r600_read_tidig_y:
381       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
382                                   AMDGPU::VGPR1, VT);
383     case Intrinsic::r600_read_tidig_z:
384       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
385                                   AMDGPU::VGPR2, VT);
386
387     }
388   }
389   }
390   return SDValue();
391 }
392
393 /// \brief Helper function for LowerBRCOND
394 static SDNode *findUser(SDValue Value, unsigned Opcode) {
395
396   SDNode *Parent = Value.getNode();
397   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
398        I != E; ++I) {
399
400     if (I.getUse().get() != Value)
401       continue;
402
403     if (I->getOpcode() == Opcode)
404       return *I;
405   }
406   return 0;
407 }
408
409 /// This transforms the control flow intrinsics to get the branch destination as
410 /// last parameter, also switches branch target with BR if the need arise
411 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
412                                       SelectionDAG &DAG) const {
413
414   SDLoc DL(BRCOND);
415
416   SDNode *Intr = BRCOND.getOperand(1).getNode();
417   SDValue Target = BRCOND.getOperand(2);
418   SDNode *BR = 0;
419
420   if (Intr->getOpcode() == ISD::SETCC) {
421     // As long as we negate the condition everything is fine
422     SDNode *SetCC = Intr;
423     assert(SetCC->getConstantOperandVal(1) == 1);
424     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
425            ISD::SETNE);
426     Intr = SetCC->getOperand(0).getNode();
427
428   } else {
429     // Get the target from BR if we don't negate the condition
430     BR = findUser(BRCOND, ISD::BR);
431     Target = BR->getOperand(1);
432   }
433
434   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
435
436   // Build the result and
437   SmallVector<EVT, 4> Res;
438   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
439     Res.push_back(Intr->getValueType(i));
440
441   // operands of the new intrinsic call
442   SmallVector<SDValue, 4> Ops;
443   Ops.push_back(BRCOND.getOperand(0));
444   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
445     Ops.push_back(Intr->getOperand(i));
446   Ops.push_back(Target);
447
448   // build the new intrinsic call
449   SDNode *Result = DAG.getNode(
450     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
451     DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
452
453   if (BR) {
454     // Give the branch instruction our target
455     SDValue Ops[] = {
456       BR->getOperand(0),
457       BRCOND.getOperand(2)
458     };
459     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
460   }
461
462   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
463
464   // Copy the intrinsic results to registers
465   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
466     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
467     if (!CopyToReg)
468       continue;
469
470     Chain = DAG.getCopyToReg(
471       Chain, DL,
472       CopyToReg->getOperand(1),
473       SDValue(Result, i - 1),
474       SDValue());
475
476     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
477   }
478
479   // Remove the old intrinsic from the chain
480   DAG.ReplaceAllUsesOfValueWith(
481     SDValue(Intr, Intr->getNumValues() - 1),
482     Intr->getOperand(0));
483
484   return Chain;
485 }
486
487 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
488   SDValue LHS = Op.getOperand(0);
489   SDValue RHS = Op.getOperand(1);
490   SDValue True = Op.getOperand(2);
491   SDValue False = Op.getOperand(3);
492   SDValue CC = Op.getOperand(4);
493   EVT VT = Op.getValueType();
494   SDLoc DL(Op);
495
496   // Possible Min/Max pattern
497   SDValue MinMax = LowerMinMax(Op, DAG);
498   if (MinMax.getNode()) {
499     return MinMax;
500   }
501
502   SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
503   return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
504 }
505
506 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
507                                            SelectionDAG &DAG) const {
508   EVT VT = Op.getValueType();
509   SDLoc DL(Op);
510
511   if (VT != MVT::i64) {
512     return SDValue();
513   }
514
515   SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
516                                                  DAG.getConstant(31, MVT::i32));
517
518   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
519 }
520
521 //===----------------------------------------------------------------------===//
522 // Custom DAG optimizations
523 //===----------------------------------------------------------------------===//
524
525 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
526                                             DAGCombinerInfo &DCI) const {
527   SelectionDAG &DAG = DCI.DAG;
528   SDLoc DL(N);
529   EVT VT = N->getValueType(0);
530
531   switch (N->getOpcode()) {
532     default: break;
533     case ISD::SELECT_CC: {
534       N->dump();
535       ConstantSDNode *True, *False;
536       // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
537       if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
538           && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
539           && True->isAllOnesValue()
540           && False->isNullValue()
541           && VT == MVT::i1) {
542         return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
543                            N->getOperand(1), N->getOperand(4));
544
545       }
546       break;
547     }
548     case ISD::SETCC: {
549       SDValue Arg0 = N->getOperand(0);
550       SDValue Arg1 = N->getOperand(1);
551       SDValue CC = N->getOperand(2);
552       ConstantSDNode * C = NULL;
553       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
554
555       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
556       if (VT == MVT::i1
557           && Arg0.getOpcode() == ISD::SIGN_EXTEND
558           && Arg0.getOperand(0).getValueType() == MVT::i1
559           && (C = dyn_cast<ConstantSDNode>(Arg1))
560           && C->isNullValue()
561           && CCOp == ISD::SETNE) {
562         return SimplifySetCC(VT, Arg0.getOperand(0),
563                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
564       }
565       break;
566     }
567   }
568   return SDValue();
569 }
570
571 /// \brief Test if RegClass is one of the VSrc classes
572 static bool isVSrc(unsigned RegClass) {
573   return AMDGPU::VSrc_32RegClassID == RegClass ||
574          AMDGPU::VSrc_64RegClassID == RegClass;
575 }
576
577 /// \brief Test if RegClass is one of the SSrc classes
578 static bool isSSrc(unsigned RegClass) {
579   return AMDGPU::SSrc_32RegClassID == RegClass ||
580          AMDGPU::SSrc_64RegClassID == RegClass;
581 }
582
583 /// \brief Analyze the possible immediate value Op
584 ///
585 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
586 /// and the immediate value if it's a literal immediate
587 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
588
589   union {
590     int32_t I;
591     float F;
592   } Imm;
593
594   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
595     if (Node->getZExtValue() >> 32) {
596         return -1;
597     }
598     Imm.I = Node->getSExtValue();
599   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
600     Imm.F = Node->getValueAPF().convertToFloat();
601   else
602     return -1; // It isn't an immediate
603
604   if ((Imm.I >= -16 && Imm.I <= 64) ||
605       Imm.F == 0.5f || Imm.F == -0.5f ||
606       Imm.F == 1.0f || Imm.F == -1.0f ||
607       Imm.F == 2.0f || Imm.F == -2.0f ||
608       Imm.F == 4.0f || Imm.F == -4.0f)
609     return 0; // It's an inline immediate
610
611   return Imm.I; // It's a literal immediate
612 }
613
614 /// \brief Try to fold an immediate directly into an instruction
615 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
616                                bool &ScalarSlotUsed) const {
617
618   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
619   const SIInstrInfo *TII =
620     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
621   if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
622     return false;
623
624   const SDValue &Op = Mov->getOperand(0);
625   int32_t Value = analyzeImmediate(Op.getNode());
626   if (Value == -1) {
627     // Not an immediate at all
628     return false;
629
630   } else if (Value == 0) {
631     // Inline immediates can always be fold
632     Operand = Op;
633     return true;
634
635   } else if (Value == Immediate) {
636     // Already fold literal immediate
637     Operand = Op;
638     return true;
639
640   } else if (!ScalarSlotUsed && !Immediate) {
641     // Fold this literal immediate
642     ScalarSlotUsed = true;
643     Immediate = Value;
644     Operand = Op;
645     return true;
646
647   }
648
649   return false;
650 }
651
652 /// \brief Does "Op" fit into register class "RegClass" ?
653 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
654                                     unsigned RegClass) const {
655
656   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
657   SDNode *Node = Op.getNode();
658
659   const TargetRegisterClass *OpClass;
660   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
661   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
662     const SIInstrInfo *TII =
663       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
664     const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
665     int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
666     if (OpClassID == -1) {
667       switch (MN->getMachineOpcode()) {
668       case AMDGPU::REG_SEQUENCE:
669         // Operand 0 is the register class id for REG_SEQUENCE instructions.
670         OpClass = TRI->getRegClass(
671                        cast<ConstantSDNode>(MN->getOperand(0))->getZExtValue());
672         break;
673       default:
674         OpClass = getRegClassFor(Op.getSimpleValueType());
675         break;
676       }
677     } else {
678       OpClass = TRI->getRegClass(OpClassID);
679     }
680
681   } else if (Node->getOpcode() == ISD::CopyFromReg) {
682     RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
683     OpClass = MRI.getRegClass(Reg->getReg());
684
685   } else
686     return false;
687
688   return TRI->getRegClass(RegClass)->hasSubClassEq(OpClass);
689 }
690
691 /// \brief Make sure that we don't exeed the number of allowed scalars
692 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
693                                        unsigned RegClass,
694                                        bool &ScalarSlotUsed) const {
695
696   // First map the operands register class to a destination class
697   if (RegClass == AMDGPU::VSrc_32RegClassID)
698     RegClass = AMDGPU::VReg_32RegClassID;
699   else if (RegClass == AMDGPU::VSrc_64RegClassID)
700     RegClass = AMDGPU::VReg_64RegClassID;
701   else
702     return;
703
704   // Nothing todo if they fit naturaly
705   if (fitsRegClass(DAG, Operand, RegClass))
706     return;
707
708   // If the scalar slot isn't used yet use it now
709   if (!ScalarSlotUsed) {
710     ScalarSlotUsed = true;
711     return;
712   }
713
714   // This is a conservative aproach, it is possible that we can't determine
715   // the correct register class and copy too often, but better save than sorry.
716   SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
717   SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
718                                     Operand.getValueType(), Operand, RC);
719   Operand = SDValue(Node, 0);
720 }
721
722 /// \returns true if \p Node's operands are different from the SDValue list
723 /// \p Ops
724 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
725   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
726     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
727       return true;
728     }
729   }
730   return false;
731 }
732
733 /// \brief Try to fold the Nodes operands into the Node
734 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
735                                        SelectionDAG &DAG) const {
736
737   // Original encoding (either e32 or e64)
738   int Opcode = Node->getMachineOpcode();
739   const SIInstrInfo *TII =
740     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
741   const MCInstrDesc *Desc = &TII->get(Opcode);
742
743   unsigned NumDefs = Desc->getNumDefs();
744   unsigned NumOps = Desc->getNumOperands();
745
746   // Commuted opcode if available
747   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
748   const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
749
750   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
751   assert(!DescRev || DescRev->getNumOperands() == NumOps);
752
753   // e64 version if available, -1 otherwise
754   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
755   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
756
757   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
758   assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
759
760   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
761   bool HaveVSrc = false, HaveSSrc = false;
762
763   // First figure out what we alread have in this instruction
764   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
765        i != e && Op < NumOps; ++i, ++Op) {
766
767     unsigned RegClass = Desc->OpInfo[Op].RegClass;
768     if (isVSrc(RegClass))
769       HaveVSrc = true;
770     else if (isSSrc(RegClass))
771       HaveSSrc = true;
772     else
773       continue;
774
775     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
776     if (Imm != -1 && Imm != 0) {
777       // Literal immediate
778       Immediate = Imm;
779     }
780   }
781
782   // If we neither have VSrc nor SSrc it makes no sense to continue
783   if (!HaveVSrc && !HaveSSrc)
784     return Node;
785
786   // No scalar allowed when we have both VSrc and SSrc
787   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
788
789   // Second go over the operands and try to fold them
790   std::vector<SDValue> Ops;
791   bool Promote2e64 = false;
792   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
793        i != e && Op < NumOps; ++i, ++Op) {
794
795     const SDValue &Operand = Node->getOperand(i);
796     Ops.push_back(Operand);
797
798     // Already folded immediate ?
799     if (isa<ConstantSDNode>(Operand.getNode()) ||
800         isa<ConstantFPSDNode>(Operand.getNode()))
801       continue;
802
803     // Is this a VSrc or SSrc operand ?
804     unsigned RegClass = Desc->OpInfo[Op].RegClass;
805     if (isVSrc(RegClass) || isSSrc(RegClass)) {
806       // Try to fold the immediates
807       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
808         // Folding didn't worked, make sure we don't hit the SReg limit
809         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
810       }
811       continue;
812     }
813
814     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
815
816       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
817       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
818
819       // Test if it makes sense to swap operands
820       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
821           (!fitsRegClass(DAG, Ops[1], RegClass) &&
822            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
823
824         // Swap commutable operands
825         SDValue Tmp = Ops[1];
826         Ops[1] = Ops[0];
827         Ops[0] = Tmp;
828
829         Desc = DescRev;
830         DescRev = 0;
831         continue;
832       }
833     }
834
835     if (DescE64 && !Immediate) {
836
837       // Test if it makes sense to switch to e64 encoding
838       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
839       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
840         continue;
841
842       int32_t TmpImm = -1;
843       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
844           (!fitsRegClass(DAG, Ops[i], RegClass) &&
845            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
846
847         // Switch to e64 encoding
848         Immediate = -1;
849         Promote2e64 = true;
850         Desc = DescE64;
851         DescE64 = 0;
852       }
853     }
854   }
855
856   if (Promote2e64) {
857     // Add the modifier flags while promoting
858     for (unsigned i = 0; i < 4; ++i)
859       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
860   }
861
862   // Add optional chain and glue
863   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
864     Ops.push_back(Node->getOperand(i));
865
866   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
867   // this case a brand new node is always be created, even if the operands
868   // are the same as before.  So, manually check if anything has been changed.
869   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
870     return Node;
871   }
872
873   // Create a complete new instruction
874   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
875 }
876
877 /// \brief Helper function for adjustWritemask
878 static unsigned SubIdx2Lane(unsigned Idx) {
879   switch (Idx) {
880   default: return 0;
881   case AMDGPU::sub0: return 0;
882   case AMDGPU::sub1: return 1;
883   case AMDGPU::sub2: return 2;
884   case AMDGPU::sub3: return 3;
885   }
886 }
887
888 /// \brief Adjust the writemask of MIMG instructions
889 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
890                                        SelectionDAG &DAG) const {
891   SDNode *Users[4] = { };
892   unsigned Writemask = 0, Lane = 0;
893
894   // Try to figure out the used register components
895   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
896        I != E; ++I) {
897
898     // Abort if we can't understand the usage
899     if (!I->isMachineOpcode() ||
900         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
901       return;
902
903     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
904
905     // Abort if we have more than one user per component
906     if (Users[Lane])
907       return;
908
909     Users[Lane] = *I;
910     Writemask |= 1 << Lane;
911   }
912
913   // Abort if all components are used
914   if (Writemask == 0xf)
915     return;
916
917   // Adjust the writemask in the node
918   std::vector<SDValue> Ops;
919   Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
920   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
921     Ops.push_back(Node->getOperand(i));
922   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
923
924   // If we only got one lane, replace it with a copy
925   if (Writemask == (1U << Lane)) {
926     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
927     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
928                                       SDLoc(), Users[Lane]->getValueType(0),
929                                       SDValue(Node, 0), RC);
930     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
931     return;
932   }
933
934   // Update the users of the node with the new indices
935   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
936
937     SDNode *User = Users[i];
938     if (!User)
939       continue;
940
941     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
942     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
943
944     switch (Idx) {
945     default: break;
946     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
947     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
948     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
949     }
950   }
951 }
952
953 /// \brief Fold the instructions after slecting them
954 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
955                                           SelectionDAG &DAG) const {
956   Node = AdjustRegClass(Node, DAG);
957
958   if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
959     adjustWritemask(Node, DAG);
960
961   return foldOperands(Node, DAG);
962 }
963
964 /// \brief Assign the register class depending on the number of
965 /// bits set in the writemask
966 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
967                                                      SDNode *Node) const {
968   if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
969     return;
970
971   unsigned VReg = MI->getOperand(0).getReg();
972   unsigned Writemask = MI->getOperand(1).getImm();
973   unsigned BitsSet = 0;
974   for (unsigned i = 0; i < 4; ++i)
975     BitsSet += Writemask & (1 << i) ? 1 : 0;
976
977   const TargetRegisterClass *RC;
978   switch (BitsSet) {
979   default: return;
980   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
981   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
982   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
983   }
984
985   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
986   MRI.setRegClass(VReg, RC);
987 }
988
989 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
990                                                 SelectionDAG &DAG) const {
991
992   SDLoc DL(N);
993   unsigned NewOpcode = N->getMachineOpcode();
994
995   switch (N->getMachineOpcode()) {
996   default: return N;
997   case AMDGPU::REG_SEQUENCE: {
998     // MVT::i128 only use SGPRs, so i128 REG_SEQUENCEs don't need to be
999     // rewritten.
1000     if (N->getValueType(0) == MVT::i128) {
1001       return N;
1002     }
1003     const SDValue Ops[] = {
1004       DAG.getTargetConstant(AMDGPU::VReg_64RegClassID, MVT::i32),
1005       N->getOperand(1) , N->getOperand(2),
1006       N->getOperand(3), N->getOperand(4)
1007     };
1008     return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::i64, Ops);
1009   }
1010
1011   case AMDGPU::S_LOAD_DWORD_IMM:
1012     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1013     // Fall-through
1014   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1015     if (NewOpcode == N->getMachineOpcode()) {
1016       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1017     }
1018     // Fall-through
1019   case AMDGPU::S_LOAD_DWORDX4_IMM:
1020   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1021     if (NewOpcode == N->getMachineOpcode()) {
1022       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1023     }
1024     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1025       return N;
1026     }
1027     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1028     SDValue Ops[] = {
1029       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1030                                  DAG.getConstant(0, MVT::i64)), 0),
1031       N->getOperand(0),
1032       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1033     };
1034     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1035   }
1036   }
1037 }
1038
1039 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1040                                                const TargetRegisterClass *RC,
1041                                                unsigned Reg, EVT VT) const {
1042   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1043
1044   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1045                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1046 }