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