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