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