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