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