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