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