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