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