R600/SI: Split global vector loads with more than 4 elements
[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::VSrc_64RegClass);
36
37   addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
38   addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
39
40   addRegisterClass(MVT::i32, &AMDGPU::VSrc_32RegClass);
41   addRegisterClass(MVT::f32, &AMDGPU::VSrc_32RegClass);
42
43   addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
44   addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
45   addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
46
47   addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
48   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
49   addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
50
51   addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
52   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
53
54   addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
55   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
56
57   computeRegisterProperties();
58
59   // Condition Codes
60   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
61   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
62   setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
63   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
64   setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
65   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
66
67   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
68   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
69   setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
70   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
71   setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
72   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
73
74   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
75   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
76   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
77   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
78
79   setOperationAction(ISD::ADD, MVT::i64, Legal);
80   setOperationAction(ISD::ADD, MVT::i32, Legal);
81   setOperationAction(ISD::ADDC, MVT::i32, Legal);
82   setOperationAction(ISD::ADDE, MVT::i32, Legal);
83
84   setOperationAction(ISD::BITCAST, MVT::i128, Legal);
85
86   // We need to custom lower vector stores from local memory
87   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
88   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
89   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
90   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
91
92   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
93   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
94
95   // We need to custom lower loads/stores from private memory
96   setOperationAction(ISD::LOAD, MVT::i32, Custom);
97   setOperationAction(ISD::LOAD, MVT::i64, Custom);
98   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
99   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
100
101   setOperationAction(ISD::STORE, MVT::i32, Custom);
102   setOperationAction(ISD::STORE, MVT::i64, Custom);
103   setOperationAction(ISD::STORE, MVT::i128, Custom);
104   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
105   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
106
107   setOperationAction(ISD::SELECT, MVT::i64, Custom);
108
109   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
110   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
111
112   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
113
114   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
115   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
116
117   setOperationAction(ISD::ANY_EXTEND, MVT::i64, Custom);
118   setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
119   setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
120
121   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
122   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
123   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
124   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
125
126   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
127
128   setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
129   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
130   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
131   setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
132   setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
133
134   setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
135   setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
136   setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
137   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
138   setTruncStoreAction(MVT::i32, MVT::i8, Custom);
139   setTruncStoreAction(MVT::i32, MVT::i16, Custom);
140   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
141   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
142   setTruncStoreAction(MVT::i128, MVT::i64, Expand);
143   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
144   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
145
146   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
147   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
148   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
149
150   setTargetDAGCombine(ISD::SELECT_CC);
151
152   setTargetDAGCombine(ISD::SETCC);
153
154   setSchedulingPreference(Sched::RegPressure);
155 }
156
157 //===----------------------------------------------------------------------===//
158 // TargetLowering queries
159 //===----------------------------------------------------------------------===//
160
161 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT  VT,
162                                                      unsigned AddrSpace,
163                                                      bool *IsFast) const {
164   // XXX: This depends on the address space and also we may want to revist
165   // the alignment values we specify in the DataLayout.
166   if (!VT.isSimple() || VT == MVT::Other)
167     return false;
168   return VT.bitsGT(MVT::i32);
169 }
170
171 bool SITargetLowering::shouldSplitVectorElementType(EVT VT) const {
172   return VT.bitsLE(MVT::i16);
173 }
174
175 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
176                                          SDLoc DL, SDValue Chain,
177                                          unsigned Offset) const {
178   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
179   PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
180                                             AMDGPUAS::CONSTANT_ADDRESS);
181   SDValue BasePtr =  DAG.getCopyFromReg(Chain, DL,
182                            MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
183   SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
184                                              DAG.getConstant(Offset, MVT::i64));
185   return DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, Chain, Ptr,
186                             MachinePointerInfo(UndefValue::get(PtrTy)), MemVT,
187                             false, false, MemVT.getSizeInBits() >> 3);
188
189 }
190
191 SDValue SITargetLowering::LowerFormalArguments(
192                                       SDValue Chain,
193                                       CallingConv::ID CallConv,
194                                       bool isVarArg,
195                                       const SmallVectorImpl<ISD::InputArg> &Ins,
196                                       SDLoc DL, SelectionDAG &DAG,
197                                       SmallVectorImpl<SDValue> &InVals) const {
198
199   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
200
201   MachineFunction &MF = DAG.getMachineFunction();
202   FunctionType *FType = MF.getFunction()->getFunctionType();
203   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
204
205   assert(CallConv == CallingConv::C);
206
207   SmallVector<ISD::InputArg, 16> Splits;
208   uint32_t Skipped = 0;
209
210   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
211     const ISD::InputArg &Arg = Ins[i];
212
213     // First check if it's a PS input addr
214     if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
215         !Arg.Flags.isByVal()) {
216
217       assert((PSInputNum <= 15) && "Too many PS inputs!");
218
219       if (!Arg.Used) {
220         // We can savely skip PS inputs
221         Skipped |= 1 << i;
222         ++PSInputNum;
223         continue;
224       }
225
226       Info->PSInputAddr |= 1 << PSInputNum++;
227     }
228
229     // Second split vertices into their elements
230     if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
231       ISD::InputArg NewArg = Arg;
232       NewArg.Flags.setSplit();
233       NewArg.VT = Arg.VT.getVectorElementType();
234
235       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
236       // three or five element vertex only needs three or five registers,
237       // NOT four or eigth.
238       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
239       unsigned NumElements = ParamType->getVectorNumElements();
240
241       for (unsigned j = 0; j != NumElements; ++j) {
242         Splits.push_back(NewArg);
243         NewArg.PartOffset += NewArg.VT.getStoreSize();
244       }
245
246     } else if (Info->ShaderType != ShaderType::COMPUTE) {
247       Splits.push_back(Arg);
248     }
249   }
250
251   SmallVector<CCValAssign, 16> ArgLocs;
252   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
253                  getTargetMachine(), ArgLocs, *DAG.getContext());
254
255   // At least one interpolation mode must be enabled or else the GPU will hang.
256   if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
257     Info->PSInputAddr |= 1;
258     CCInfo.AllocateReg(AMDGPU::VGPR0);
259     CCInfo.AllocateReg(AMDGPU::VGPR1);
260   }
261
262   // The pointer to the list of arguments is stored in SGPR0, SGPR1
263   if (Info->ShaderType == ShaderType::COMPUTE) {
264     CCInfo.AllocateReg(AMDGPU::SGPR0);
265     CCInfo.AllocateReg(AMDGPU::SGPR1);
266     MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
267   }
268
269   if (Info->ShaderType == ShaderType::COMPUTE) {
270     getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
271                             Splits);
272   }
273
274   AnalyzeFormalArguments(CCInfo, Splits);
275
276   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
277
278     const ISD::InputArg &Arg = Ins[i];
279     if (Skipped & (1 << i)) {
280       InVals.push_back(DAG.getUNDEF(Arg.VT));
281       continue;
282     }
283
284     CCValAssign &VA = ArgLocs[ArgIdx++];
285     EVT VT = VA.getLocVT();
286
287     if (VA.isMemLoc()) {
288       VT = Ins[i].VT;
289       EVT MemVT = Splits[i].VT;
290       // The first 36 bytes of the input buffer contains information about
291       // thread group and global sizes.
292       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, DAG.getRoot(),
293                                    36 + VA.getLocMemOffset());
294       InVals.push_back(Arg);
295       continue;
296     }
297     assert(VA.isRegLoc() && "Parameter must be in a register!");
298
299     unsigned Reg = VA.getLocReg();
300
301     if (VT == MVT::i64) {
302       // For now assume it is a pointer
303       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
304                                      &AMDGPU::SReg_64RegClass);
305       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
306       InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
307       continue;
308     }
309
310     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
311
312     Reg = MF.addLiveIn(Reg, RC);
313     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
314
315     if (Arg.VT.isVector()) {
316
317       // Build a vector from the registers
318       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
319       unsigned NumElements = ParamType->getVectorNumElements();
320
321       SmallVector<SDValue, 4> Regs;
322       Regs.push_back(Val);
323       for (unsigned j = 1; j != NumElements; ++j) {
324         Reg = ArgLocs[ArgIdx++].getLocReg();
325         Reg = MF.addLiveIn(Reg, RC);
326         Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
327       }
328
329       // Fill up the missing vector elements
330       NumElements = Arg.VT.getVectorNumElements() - NumElements;
331       for (unsigned j = 0; j != NumElements; ++j)
332         Regs.push_back(DAG.getUNDEF(VT));
333
334       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
335                                    Regs.data(), Regs.size()));
336       continue;
337     }
338
339     InVals.push_back(Val);
340   }
341   return Chain;
342 }
343
344 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
345     MachineInstr * MI, MachineBasicBlock * BB) const {
346
347   MachineBasicBlock::iterator I = *MI;
348
349   switch (MI->getOpcode()) {
350   default:
351     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
352   case AMDGPU::BRANCH: return BB;
353   case AMDGPU::SI_ADDR64_RSRC: {
354     const SIInstrInfo *TII =
355       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
356     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
357     unsigned SuperReg = MI->getOperand(0).getReg();
358     unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
359     unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
360     unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
361     unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
362     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
363             .addOperand(MI->getOperand(1));
364     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
365             .addImm(0);
366     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
367             .addImm(RSRC_DATA_FORMAT >> 32);
368     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
369             .addReg(SubRegHiLo)
370             .addImm(AMDGPU::sub0)
371             .addReg(SubRegHiHi)
372             .addImm(AMDGPU::sub1);
373     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
374             .addReg(SubRegLo)
375             .addImm(AMDGPU::sub0_sub1)
376             .addReg(SubRegHi)
377             .addImm(AMDGPU::sub2_sub3);
378     MI->eraseFromParent();
379     break;
380   }
381   case AMDGPU::V_SUB_F64: {
382     const SIInstrInfo *TII =
383       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
384     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
385             MI->getOperand(0).getReg())
386             .addReg(MI->getOperand(1).getReg())
387             .addReg(MI->getOperand(2).getReg())
388             .addImm(0)  /* src2 */
389             .addImm(0)  /* ABS */
390             .addImm(0)  /* CLAMP */
391             .addImm(0)  /* OMOD */
392             .addImm(2); /* NEG */
393     MI->eraseFromParent();
394     break;
395   }
396   case AMDGPU::SI_RegisterStorePseudo: {
397     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
398     const SIInstrInfo *TII =
399       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
400     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
401     MachineInstrBuilder MIB =
402         BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
403                 Reg);
404     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
405       MIB.addOperand(MI->getOperand(i));
406
407     MI->eraseFromParent();
408   }
409   }
410   return BB;
411 }
412
413 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
414   if (!VT.isVector()) {
415     return MVT::i1;
416   }
417   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
418 }
419
420 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
421   return MVT::i32;
422 }
423
424 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
425   VT = VT.getScalarType();
426
427   if (!VT.isSimple())
428     return false;
429
430   switch (VT.getSimpleVT().SimpleTy) {
431   case MVT::f32:
432     return false; /* There is V_MAD_F32 for f32 */
433   case MVT::f64:
434     return true;
435   default:
436     break;
437   }
438
439   return false;
440 }
441
442 //===----------------------------------------------------------------------===//
443 // Custom DAG Lowering Operations
444 //===----------------------------------------------------------------------===//
445
446 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
447   MachineFunction &MF = DAG.getMachineFunction();
448   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
449   switch (Op.getOpcode()) {
450   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
451   case ISD::ADD: return LowerADD(Op, DAG);
452   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
453   case ISD::LOAD: {
454     LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
455     if (Op.getValueType().isVector() &&
456         (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
457          Load->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
458          (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
459           Op.getValueType().getVectorNumElements() > 4))) {
460       SDValue MergedValues[2] = {
461         SplitVectorLoad(Op, DAG),
462         Load->getChain()
463       };
464       return DAG.getMergeValues(MergedValues, 2, SDLoc(Op));
465     } else {
466       return LowerLOAD(Op, DAG);
467     }
468   }
469
470   case ISD::SELECT: return LowerSELECT(Op, DAG);
471   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
472   case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
473   case ISD::STORE: return LowerSTORE(Op, DAG);
474   case ISD::ANY_EXTEND: // Fall-through
475   case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
476   case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
477   case ISD::INTRINSIC_WO_CHAIN: {
478     unsigned IntrinsicID =
479                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
480     EVT VT = Op.getValueType();
481     SDLoc DL(Op);
482     //XXX: Hardcoded we only use two to store the pointer to the parameters.
483     unsigned NumUserSGPRs = 2;
484     switch (IntrinsicID) {
485     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
486     case Intrinsic::r600_read_ngroups_x:
487       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0);
488     case Intrinsic::r600_read_ngroups_y:
489       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4);
490     case Intrinsic::r600_read_ngroups_z:
491       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8);
492     case Intrinsic::r600_read_global_size_x:
493       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12);
494     case Intrinsic::r600_read_global_size_y:
495       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16);
496     case Intrinsic::r600_read_global_size_z:
497       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20);
498     case Intrinsic::r600_read_local_size_x:
499       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24);
500     case Intrinsic::r600_read_local_size_y:
501       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28);
502     case Intrinsic::r600_read_local_size_z:
503       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32);
504     case Intrinsic::r600_read_tgid_x:
505       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
506                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
507     case Intrinsic::r600_read_tgid_y:
508       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
509                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
510     case Intrinsic::r600_read_tgid_z:
511       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
512                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
513     case Intrinsic::r600_read_tidig_x:
514       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
515                                   AMDGPU::VGPR0, VT);
516     case Intrinsic::r600_read_tidig_y:
517       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
518                                   AMDGPU::VGPR1, VT);
519     case Intrinsic::r600_read_tidig_z:
520       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
521                                   AMDGPU::VGPR2, VT);
522     case AMDGPUIntrinsic::SI_load_const: {
523       SDValue Ops [] = {
524         ResourceDescriptorToi128(Op.getOperand(1), DAG),
525         Op.getOperand(2)
526       };
527
528       MachineMemOperand *MMO = MF.getMachineMemOperand(
529           MachinePointerInfo(),
530           MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
531           VT.getSizeInBits() / 8, 4);
532       return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
533                                      Op->getVTList(), Ops, 2, VT, MMO);
534     }
535     case AMDGPUIntrinsic::SI_sample:
536       return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
537     case AMDGPUIntrinsic::SI_sampleb:
538       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
539     case AMDGPUIntrinsic::SI_sampled:
540       return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
541     case AMDGPUIntrinsic::SI_samplel:
542       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
543     case AMDGPUIntrinsic::SI_vs_load_input:
544       return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
545                          ResourceDescriptorToi128(Op.getOperand(1), DAG),
546                          Op.getOperand(2),
547                          Op.getOperand(3));
548     }
549   }
550
551   case ISD::INTRINSIC_VOID:
552     SDValue Chain = Op.getOperand(0);
553     unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
554
555     switch (IntrinsicID) {
556       case AMDGPUIntrinsic::SI_tbuffer_store: {
557         SDLoc DL(Op);
558         SDValue Ops [] = {
559           Chain,
560           ResourceDescriptorToi128(Op.getOperand(2), DAG),
561           Op.getOperand(3),
562           Op.getOperand(4),
563           Op.getOperand(5),
564           Op.getOperand(6),
565           Op.getOperand(7),
566           Op.getOperand(8),
567           Op.getOperand(9),
568           Op.getOperand(10),
569           Op.getOperand(11),
570           Op.getOperand(12),
571           Op.getOperand(13),
572           Op.getOperand(14)
573         };
574         EVT VT = Op.getOperand(3).getValueType();
575
576         MachineMemOperand *MMO = MF.getMachineMemOperand(
577             MachinePointerInfo(),
578             MachineMemOperand::MOStore,
579             VT.getSizeInBits() / 8, 4);
580         return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
581                                        Op->getVTList(), Ops,
582                                        sizeof(Ops)/sizeof(Ops[0]), VT, MMO);
583       }
584       default:
585         break;
586     }
587   }
588   return SDValue();
589 }
590
591 SDValue SITargetLowering::LowerADD(SDValue Op,
592                                    SelectionDAG &DAG) const {
593   if (Op.getValueType() != MVT::i64)
594     return SDValue();
595
596   SDLoc DL(Op);
597   SDValue LHS = Op.getOperand(0);
598   SDValue RHS = Op.getOperand(1);
599
600   SDValue Zero = DAG.getConstant(0, MVT::i32);
601   SDValue One = DAG.getConstant(1, MVT::i32);
602
603   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS, Zero);
604   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS, One);
605
606   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS, Zero);
607   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS, One);
608
609   SDVTList VTList = DAG.getVTList(MVT::i32, MVT::Glue);
610
611   SDValue AddLo = DAG.getNode(ISD::ADDC, DL, VTList, Lo0, Lo1);
612   SDValue Carry = AddLo.getValue(1);
613   SDValue AddHi = DAG.getNode(ISD::ADDE, DL, VTList, Hi0, Hi1, Carry);
614
615   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, AddLo, AddHi.getValue(0));
616 }
617
618 /// \brief Helper function for LowerBRCOND
619 static SDNode *findUser(SDValue Value, unsigned Opcode) {
620
621   SDNode *Parent = Value.getNode();
622   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
623        I != E; ++I) {
624
625     if (I.getUse().get() != Value)
626       continue;
627
628     if (I->getOpcode() == Opcode)
629       return *I;
630   }
631   return 0;
632 }
633
634 /// This transforms the control flow intrinsics to get the branch destination as
635 /// last parameter, also switches branch target with BR if the need arise
636 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
637                                       SelectionDAG &DAG) const {
638
639   SDLoc DL(BRCOND);
640
641   SDNode *Intr = BRCOND.getOperand(1).getNode();
642   SDValue Target = BRCOND.getOperand(2);
643   SDNode *BR = 0;
644
645   if (Intr->getOpcode() == ISD::SETCC) {
646     // As long as we negate the condition everything is fine
647     SDNode *SetCC = Intr;
648     assert(SetCC->getConstantOperandVal(1) == 1);
649     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
650            ISD::SETNE);
651     Intr = SetCC->getOperand(0).getNode();
652
653   } else {
654     // Get the target from BR if we don't negate the condition
655     BR = findUser(BRCOND, ISD::BR);
656     Target = BR->getOperand(1);
657   }
658
659   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
660
661   // Build the result and
662   SmallVector<EVT, 4> Res;
663   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
664     Res.push_back(Intr->getValueType(i));
665
666   // operands of the new intrinsic call
667   SmallVector<SDValue, 4> Ops;
668   Ops.push_back(BRCOND.getOperand(0));
669   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
670     Ops.push_back(Intr->getOperand(i));
671   Ops.push_back(Target);
672
673   // build the new intrinsic call
674   SDNode *Result = DAG.getNode(
675     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
676     DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
677
678   if (BR) {
679     // Give the branch instruction our target
680     SDValue Ops[] = {
681       BR->getOperand(0),
682       BRCOND.getOperand(2)
683     };
684     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
685   }
686
687   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
688
689   // Copy the intrinsic results to registers
690   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
691     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
692     if (!CopyToReg)
693       continue;
694
695     Chain = DAG.getCopyToReg(
696       Chain, DL,
697       CopyToReg->getOperand(1),
698       SDValue(Result, i - 1),
699       SDValue());
700
701     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
702   }
703
704   // Remove the old intrinsic from the chain
705   DAG.ReplaceAllUsesOfValueWith(
706     SDValue(Intr, Intr->getNumValues() - 1),
707     Intr->getOperand(0));
708
709   return Chain;
710 }
711
712 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
713   SDLoc DL(Op);
714   LoadSDNode *Load = cast<LoadSDNode>(Op);
715   SDValue Ret = AMDGPUTargetLowering::LowerLOAD(Op, DAG);
716   SDValue MergedValues[2];
717   MergedValues[1] = Load->getChain();
718   if (Ret.getNode()) {
719     MergedValues[0] = Ret;
720     return DAG.getMergeValues(MergedValues, 2, DL);
721   }
722
723   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
724     return SDValue();
725   }
726
727   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
728                             DAG.getConstant(2, MVT::i32));
729   Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
730                     Load->getChain(), Ptr,
731                     DAG.getTargetConstant(0, MVT::i32),
732                     Op.getOperand(2));
733
734   MergedValues[0] = Ret;
735   return DAG.getMergeValues(MergedValues, 2, DL);
736
737 }
738
739 SDValue SITargetLowering::ResourceDescriptorToi128(SDValue Op,
740                                              SelectionDAG &DAG) const {
741
742   if (Op.getValueType() == MVT::i128) {
743     return Op;
744   }
745
746   assert(Op.getOpcode() == ISD::UNDEF);
747
748   return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), MVT::i128,
749                      DAG.getConstant(0, MVT::i64),
750                      DAG.getConstant(0, MVT::i64));
751 }
752
753 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
754                                                const SDValue &Op,
755                                                SelectionDAG &DAG) const {
756   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
757                      Op.getOperand(2),
758                      ResourceDescriptorToi128(Op.getOperand(3), DAG),
759                      Op.getOperand(4));
760 }
761
762 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
763   if (Op.getValueType() != MVT::i64)
764     return SDValue();
765
766   SDLoc DL(Op);
767   SDValue Cond = Op.getOperand(0);
768   SDValue LHS = Op.getOperand(1);
769   SDValue RHS = Op.getOperand(2);
770
771   SDValue Zero = DAG.getConstant(0, MVT::i32);
772   SDValue One = DAG.getConstant(1, MVT::i32);
773
774   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS, Zero);
775   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS, Zero);
776
777   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
778
779   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, LHS, One);
780   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, RHS, One);
781
782   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
783
784   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
785 }
786
787 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
788   SDValue LHS = Op.getOperand(0);
789   SDValue RHS = Op.getOperand(1);
790   SDValue True = Op.getOperand(2);
791   SDValue False = Op.getOperand(3);
792   SDValue CC = Op.getOperand(4);
793   EVT VT = Op.getValueType();
794   SDLoc DL(Op);
795
796   // Possible Min/Max pattern
797   SDValue MinMax = LowerMinMax(Op, DAG);
798   if (MinMax.getNode()) {
799     return MinMax;
800   }
801
802   SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
803   return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
804 }
805
806 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
807                                            SelectionDAG &DAG) const {
808   EVT VT = Op.getValueType();
809   SDLoc DL(Op);
810
811   if (VT != MVT::i64) {
812     return SDValue();
813   }
814
815   SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
816                                                  DAG.getConstant(31, MVT::i32));
817
818   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
819 }
820
821 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
822   SDLoc DL(Op);
823   StoreSDNode *Store = cast<StoreSDNode>(Op);
824   EVT VT = Store->getMemoryVT();
825
826   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
827   if (Ret.getNode())
828     return Ret;
829
830   if (VT.isVector() && VT.getVectorNumElements() >= 8)
831       return SplitVectorStore(Op, DAG);
832
833   if (Store->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
834     return SDValue();
835
836   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Store->getBasePtr(),
837                             DAG.getConstant(2, MVT::i32));
838   SDValue Chain = Store->getChain();
839   SmallVector<SDValue, 8> Values;
840
841   if (Store->isTruncatingStore()) {
842     unsigned Mask = 0;
843     if (Store->getMemoryVT() == MVT::i8) {
844       Mask = 0xff;
845     } else if (Store->getMemoryVT() == MVT::i16) {
846       Mask = 0xffff;
847     }
848     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
849                               Chain, Store->getBasePtr(),
850                               DAG.getConstant(0, MVT::i32));
851     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getBasePtr(),
852                                   DAG.getConstant(0x3, MVT::i32));
853     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
854                                    DAG.getConstant(3, MVT::i32));
855     SDValue MaskedValue = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getValue(),
856                                       DAG.getConstant(Mask, MVT::i32));
857     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
858                                        MaskedValue, ShiftAmt);
859     SDValue RotrAmt = DAG.getNode(ISD::SUB, DL, MVT::i32,
860                                   DAG.getConstant(32, MVT::i32), ShiftAmt);
861     SDValue DstMask = DAG.getNode(ISD::ROTR, DL, MVT::i32,
862                                   DAG.getConstant(Mask, MVT::i32),
863                                   RotrAmt);
864     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
865     Dst = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
866
867     Values.push_back(Dst);
868   } else if (VT == MVT::i64) {
869     for (unsigned i = 0; i < 2; ++i) {
870       Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
871                        Store->getValue(), DAG.getConstant(i, MVT::i32)));
872     }
873   } else if (VT == MVT::i128) {
874     for (unsigned i = 0; i < 2; ++i) {
875       for (unsigned j = 0; j < 2; ++j) {
876         Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
877                            DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
878                            Store->getValue(), DAG.getConstant(i, MVT::i32)),
879                          DAG.getConstant(j, MVT::i32)));
880       }
881     }
882   } else {
883     Values.push_back(Store->getValue());
884   }
885
886   for (unsigned i = 0; i < Values.size(); ++i) {
887     SDValue PartPtr = DAG.getNode(ISD::ADD, DL, MVT::i32,
888                                   Ptr, DAG.getConstant(i, MVT::i32));
889     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
890                         Chain, Values[i], PartPtr,
891                         DAG.getTargetConstant(0, MVT::i32));
892   }
893   return Chain;
894 }
895
896
897 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
898                                            SelectionDAG &DAG) const {
899   EVT VT = Op.getValueType();
900   SDLoc DL(Op);
901
902   if (VT != MVT::i64) {
903     return SDValue();
904   }
905
906   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
907                                               DAG.getConstant(0, MVT::i32));
908 }
909
910 //===----------------------------------------------------------------------===//
911 // Custom DAG optimizations
912 //===----------------------------------------------------------------------===//
913
914 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
915                                             DAGCombinerInfo &DCI) const {
916   SelectionDAG &DAG = DCI.DAG;
917   SDLoc DL(N);
918   EVT VT = N->getValueType(0);
919
920   switch (N->getOpcode()) {
921     default: break;
922     case ISD::SELECT_CC: {
923       ConstantSDNode *True, *False;
924       // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
925       if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
926           && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
927           && True->isAllOnesValue()
928           && False->isNullValue()
929           && VT == MVT::i1) {
930         return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
931                            N->getOperand(1), N->getOperand(4));
932
933       }
934       break;
935     }
936     case ISD::SETCC: {
937       SDValue Arg0 = N->getOperand(0);
938       SDValue Arg1 = N->getOperand(1);
939       SDValue CC = N->getOperand(2);
940       ConstantSDNode * C = NULL;
941       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
942
943       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
944       if (VT == MVT::i1
945           && Arg0.getOpcode() == ISD::SIGN_EXTEND
946           && Arg0.getOperand(0).getValueType() == MVT::i1
947           && (C = dyn_cast<ConstantSDNode>(Arg1))
948           && C->isNullValue()
949           && CCOp == ISD::SETNE) {
950         return SimplifySetCC(VT, Arg0.getOperand(0),
951                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
952       }
953       break;
954     }
955   }
956   return SDValue();
957 }
958
959 /// \brief Test if RegClass is one of the VSrc classes
960 static bool isVSrc(unsigned RegClass) {
961   return AMDGPU::VSrc_32RegClassID == RegClass ||
962          AMDGPU::VSrc_64RegClassID == RegClass;
963 }
964
965 /// \brief Test if RegClass is one of the SSrc classes
966 static bool isSSrc(unsigned RegClass) {
967   return AMDGPU::SSrc_32RegClassID == RegClass ||
968          AMDGPU::SSrc_64RegClassID == RegClass;
969 }
970
971 /// \brief Analyze the possible immediate value Op
972 ///
973 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
974 /// and the immediate value if it's a literal immediate
975 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
976
977   union {
978     int32_t I;
979     float F;
980   } Imm;
981
982   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
983     if (Node->getZExtValue() >> 32) {
984         return -1;
985     }
986     Imm.I = Node->getSExtValue();
987   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
988     Imm.F = Node->getValueAPF().convertToFloat();
989   else
990     return -1; // It isn't an immediate
991
992   if ((Imm.I >= -16 && Imm.I <= 64) ||
993       Imm.F == 0.5f || Imm.F == -0.5f ||
994       Imm.F == 1.0f || Imm.F == -1.0f ||
995       Imm.F == 2.0f || Imm.F == -2.0f ||
996       Imm.F == 4.0f || Imm.F == -4.0f)
997     return 0; // It's an inline immediate
998
999   return Imm.I; // It's a literal immediate
1000 }
1001
1002 /// \brief Try to fold an immediate directly into an instruction
1003 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1004                                bool &ScalarSlotUsed) const {
1005
1006   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1007   const SIInstrInfo *TII =
1008     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1009   if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
1010     return false;
1011
1012   const SDValue &Op = Mov->getOperand(0);
1013   int32_t Value = analyzeImmediate(Op.getNode());
1014   if (Value == -1) {
1015     // Not an immediate at all
1016     return false;
1017
1018   } else if (Value == 0) {
1019     // Inline immediates can always be fold
1020     Operand = Op;
1021     return true;
1022
1023   } else if (Value == Immediate) {
1024     // Already fold literal immediate
1025     Operand = Op;
1026     return true;
1027
1028   } else if (!ScalarSlotUsed && !Immediate) {
1029     // Fold this literal immediate
1030     ScalarSlotUsed = true;
1031     Immediate = Value;
1032     Operand = Op;
1033     return true;
1034
1035   }
1036
1037   return false;
1038 }
1039
1040 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1041                                    SelectionDAG &DAG, const SDValue &Op) const {
1042   const SIInstrInfo *TII =
1043     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1044   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1045
1046   if (!Op->isMachineOpcode()) {
1047     switch(Op->getOpcode()) {
1048     case ISD::CopyFromReg: {
1049       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1050       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1051       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1052         return MRI.getRegClass(Reg);
1053       }
1054       return TRI.getPhysRegClass(Reg);
1055     }
1056     default:  return NULL;
1057     }
1058   }
1059   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1060   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1061   if (OpClassID != -1) {
1062     return TRI.getRegClass(OpClassID);
1063   }
1064   switch(Op.getMachineOpcode()) {
1065   case AMDGPU::COPY_TO_REGCLASS:
1066     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1067     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1068
1069     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1070     // class, then the register class for the value could be either a
1071     // VReg or and SReg.  In order to get a more accurate
1072     if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1073         OpClassID == AMDGPU::VSrc_64RegClassID) {
1074       return getRegClassForNode(DAG, Op.getOperand(0));
1075     }
1076     return TRI.getRegClass(OpClassID);
1077   case AMDGPU::EXTRACT_SUBREG: {
1078     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1079     const TargetRegisterClass *SuperClass =
1080       getRegClassForNode(DAG, Op.getOperand(0));
1081     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1082   }
1083   case AMDGPU::REG_SEQUENCE:
1084     // Operand 0 is the register class id for REG_SEQUENCE instructions.
1085     return TRI.getRegClass(
1086       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1087   default:
1088     return getRegClassFor(Op.getSimpleValueType());
1089   }
1090 }
1091
1092 /// \brief Does "Op" fit into register class "RegClass" ?
1093 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1094                                     unsigned RegClass) const {
1095   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1096   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1097   if (!RC) {
1098     return false;
1099   }
1100   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1101 }
1102
1103 /// \brief Make sure that we don't exeed the number of allowed scalars
1104 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1105                                        unsigned RegClass,
1106                                        bool &ScalarSlotUsed) const {
1107
1108   // First map the operands register class to a destination class
1109   if (RegClass == AMDGPU::VSrc_32RegClassID)
1110     RegClass = AMDGPU::VReg_32RegClassID;
1111   else if (RegClass == AMDGPU::VSrc_64RegClassID)
1112     RegClass = AMDGPU::VReg_64RegClassID;
1113   else
1114     return;
1115
1116   // Nothing to do if they fit naturally
1117   if (fitsRegClass(DAG, Operand, RegClass))
1118     return;
1119
1120   // If the scalar slot isn't used yet use it now
1121   if (!ScalarSlotUsed) {
1122     ScalarSlotUsed = true;
1123     return;
1124   }
1125
1126   // This is a conservative aproach. It is possible that we can't determine the
1127   // correct register class and copy too often, but better safe than sorry.
1128   SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1129   SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1130                                     Operand.getValueType(), Operand, RC);
1131   Operand = SDValue(Node, 0);
1132 }
1133
1134 /// \returns true if \p Node's operands are different from the SDValue list
1135 /// \p Ops
1136 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1137   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1138     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1139       return true;
1140     }
1141   }
1142   return false;
1143 }
1144
1145 /// \brief Try to fold the Nodes operands into the Node
1146 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1147                                        SelectionDAG &DAG) const {
1148
1149   // Original encoding (either e32 or e64)
1150   int Opcode = Node->getMachineOpcode();
1151   const SIInstrInfo *TII =
1152     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1153   const MCInstrDesc *Desc = &TII->get(Opcode);
1154
1155   unsigned NumDefs = Desc->getNumDefs();
1156   unsigned NumOps = Desc->getNumOperands();
1157
1158   // Commuted opcode if available
1159   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1160   const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
1161
1162   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1163   assert(!DescRev || DescRev->getNumOperands() == NumOps);
1164
1165   // e64 version if available, -1 otherwise
1166   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1167   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
1168
1169   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1170   assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
1171
1172   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1173   bool HaveVSrc = false, HaveSSrc = false;
1174
1175   // First figure out what we alread have in this instruction
1176   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1177        i != e && Op < NumOps; ++i, ++Op) {
1178
1179     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1180     if (isVSrc(RegClass))
1181       HaveVSrc = true;
1182     else if (isSSrc(RegClass))
1183       HaveSSrc = true;
1184     else
1185       continue;
1186
1187     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1188     if (Imm != -1 && Imm != 0) {
1189       // Literal immediate
1190       Immediate = Imm;
1191     }
1192   }
1193
1194   // If we neither have VSrc nor SSrc it makes no sense to continue
1195   if (!HaveVSrc && !HaveSSrc)
1196     return Node;
1197
1198   // No scalar allowed when we have both VSrc and SSrc
1199   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1200
1201   // Second go over the operands and try to fold them
1202   std::vector<SDValue> Ops;
1203   bool Promote2e64 = false;
1204   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1205        i != e && Op < NumOps; ++i, ++Op) {
1206
1207     const SDValue &Operand = Node->getOperand(i);
1208     Ops.push_back(Operand);
1209
1210     // Already folded immediate ?
1211     if (isa<ConstantSDNode>(Operand.getNode()) ||
1212         isa<ConstantFPSDNode>(Operand.getNode()))
1213       continue;
1214
1215     // Is this a VSrc or SSrc operand ?
1216     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1217     if (isVSrc(RegClass) || isSSrc(RegClass)) {
1218       // Try to fold the immediates
1219       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1220         // Folding didn't worked, make sure we don't hit the SReg limit
1221         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1222       }
1223       continue;
1224     }
1225
1226     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1227
1228       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1229       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1230
1231       // Test if it makes sense to swap operands
1232       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1233           (!fitsRegClass(DAG, Ops[1], RegClass) &&
1234            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1235
1236         // Swap commutable operands
1237         SDValue Tmp = Ops[1];
1238         Ops[1] = Ops[0];
1239         Ops[0] = Tmp;
1240
1241         Desc = DescRev;
1242         DescRev = 0;
1243         continue;
1244       }
1245     }
1246
1247     if (DescE64 && !Immediate) {
1248
1249       // Test if it makes sense to switch to e64 encoding
1250       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1251       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1252         continue;
1253
1254       int32_t TmpImm = -1;
1255       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1256           (!fitsRegClass(DAG, Ops[i], RegClass) &&
1257            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1258
1259         // Switch to e64 encoding
1260         Immediate = -1;
1261         Promote2e64 = true;
1262         Desc = DescE64;
1263         DescE64 = 0;
1264       }
1265     }
1266   }
1267
1268   if (Promote2e64) {
1269     // Add the modifier flags while promoting
1270     for (unsigned i = 0; i < 4; ++i)
1271       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1272   }
1273
1274   // Add optional chain and glue
1275   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1276     Ops.push_back(Node->getOperand(i));
1277
1278   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1279   // this case a brand new node is always be created, even if the operands
1280   // are the same as before.  So, manually check if anything has been changed.
1281   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1282     return Node;
1283   }
1284
1285   // Create a complete new instruction
1286   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1287 }
1288
1289 /// \brief Helper function for adjustWritemask
1290 static unsigned SubIdx2Lane(unsigned Idx) {
1291   switch (Idx) {
1292   default: return 0;
1293   case AMDGPU::sub0: return 0;
1294   case AMDGPU::sub1: return 1;
1295   case AMDGPU::sub2: return 2;
1296   case AMDGPU::sub3: return 3;
1297   }
1298 }
1299
1300 /// \brief Adjust the writemask of MIMG instructions
1301 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1302                                        SelectionDAG &DAG) const {
1303   SDNode *Users[4] = { };
1304   unsigned Lane = 0;
1305   unsigned OldDmask = Node->getConstantOperandVal(0);
1306   unsigned NewDmask = 0;
1307
1308   // Try to figure out the used register components
1309   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1310        I != E; ++I) {
1311
1312     // Abort if we can't understand the usage
1313     if (!I->isMachineOpcode() ||
1314         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1315       return;
1316
1317     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1318     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1319     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1320     // set, etc.
1321     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1322
1323     // Set which texture component corresponds to the lane.
1324     unsigned Comp;
1325     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1326       assert(Dmask);
1327       Comp = countTrailingZeros(Dmask);
1328       Dmask &= ~(1 << Comp);
1329     }
1330
1331     // Abort if we have more than one user per component
1332     if (Users[Lane])
1333       return;
1334
1335     Users[Lane] = *I;
1336     NewDmask |= 1 << Comp;
1337   }
1338
1339   // Abort if there's no change
1340   if (NewDmask == OldDmask)
1341     return;
1342
1343   // Adjust the writemask in the node
1344   std::vector<SDValue> Ops;
1345   Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1346   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1347     Ops.push_back(Node->getOperand(i));
1348   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1349
1350   // If we only got one lane, replace it with a copy
1351   // (if NewDmask has only one bit set...)
1352   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1353     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1354     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1355                                       SDLoc(), Users[Lane]->getValueType(0),
1356                                       SDValue(Node, 0), RC);
1357     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1358     return;
1359   }
1360
1361   // Update the users of the node with the new indices
1362   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1363
1364     SDNode *User = Users[i];
1365     if (!User)
1366       continue;
1367
1368     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1369     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1370
1371     switch (Idx) {
1372     default: break;
1373     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1374     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1375     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1376     }
1377   }
1378 }
1379
1380 /// \brief Fold the instructions after slecting them
1381 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1382                                           SelectionDAG &DAG) const {
1383   const SIInstrInfo *TII =
1384       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1385   Node = AdjustRegClass(Node, DAG);
1386
1387   if (TII->isMIMG(Node->getMachineOpcode()))
1388     adjustWritemask(Node, DAG);
1389
1390   return foldOperands(Node, DAG);
1391 }
1392
1393 /// \brief Assign the register class depending on the number of
1394 /// bits set in the writemask
1395 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1396                                                      SDNode *Node) const {
1397   const SIInstrInfo *TII =
1398       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1399   if (!TII->isMIMG(MI->getOpcode()))
1400     return;
1401
1402   unsigned VReg = MI->getOperand(0).getReg();
1403   unsigned Writemask = MI->getOperand(1).getImm();
1404   unsigned BitsSet = 0;
1405   for (unsigned i = 0; i < 4; ++i)
1406     BitsSet += Writemask & (1 << i) ? 1 : 0;
1407
1408   const TargetRegisterClass *RC;
1409   switch (BitsSet) {
1410   default: return;
1411   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1412   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1413   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1414   }
1415
1416   unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1417   MI->setDesc(TII->get(NewOpcode));
1418   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1419   MRI.setRegClass(VReg, RC);
1420 }
1421
1422 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1423                                                 SelectionDAG &DAG) const {
1424
1425   SDLoc DL(N);
1426   unsigned NewOpcode = N->getMachineOpcode();
1427
1428   switch (N->getMachineOpcode()) {
1429   default: return N;
1430   case AMDGPU::S_LOAD_DWORD_IMM:
1431     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1432     // Fall-through
1433   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1434     if (NewOpcode == N->getMachineOpcode()) {
1435       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1436     }
1437     // Fall-through
1438   case AMDGPU::S_LOAD_DWORDX4_IMM:
1439   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1440     if (NewOpcode == N->getMachineOpcode()) {
1441       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1442     }
1443     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1444       return N;
1445     }
1446     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1447     SDValue Ops[] = {
1448       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1449                                  DAG.getConstant(0, MVT::i64)), 0),
1450       N->getOperand(0),
1451       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1452     };
1453     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1454   }
1455   }
1456 }
1457
1458 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1459                                                const TargetRegisterClass *RC,
1460                                                unsigned Reg, EVT VT) const {
1461   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1462
1463   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1464                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1465 }