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