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