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