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