c3405e104532bdf72ad8cb2865b4e0bbc4868179
[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)  // SRC2 modifiers
570       .addImm(0)  // src2
571       .addImm(0)  // CLAMP
572       .addImm(0); // OMOD
573     MI->eraseFromParent();
574     break;
575   }
576   case AMDGPU::SI_RegisterStorePseudo: {
577     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
578     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
579     MachineInstrBuilder MIB =
580         BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
581                 Reg);
582     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
583       MIB.addOperand(MI->getOperand(i));
584
585     MI->eraseFromParent();
586     break;
587   }
588   case AMDGPU::FABS_SI: {
589     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
590     const SIInstrInfo *TII =
591       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
592     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
593     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_MOV_B32_e32),
594             Reg)
595             .addImm(0x7fffffff);
596     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_AND_B32_e32),
597             MI->getOperand(0).getReg())
598             .addReg(MI->getOperand(1).getReg())
599             .addReg(Reg);
600     MI->eraseFromParent();
601     break;
602   }
603   case AMDGPU::FNEG_SI: {
604     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
605     const SIInstrInfo *TII =
606       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
607     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
608     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_MOV_B32_e32),
609             Reg)
610             .addImm(0x80000000);
611     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_XOR_B32_e32),
612             MI->getOperand(0).getReg())
613             .addReg(MI->getOperand(1).getReg())
614             .addReg(Reg);
615     MI->eraseFromParent();
616     break;
617   }
618   case AMDGPU::FCLAMP_SI: {
619     const SIInstrInfo *TII =
620       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
621     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F32_e64),
622             MI->getOperand(0).getReg())
623             .addImm(0) // SRC0 modifiers
624             .addOperand(MI->getOperand(1))
625             .addImm(0) // SRC1 modifiers
626             .addImm(0) // SRC1
627             .addImm(1) // CLAMP
628             .addImm(0); // OMOD
629     MI->eraseFromParent();
630   }
631   }
632   return BB;
633 }
634
635 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
636   if (!VT.isVector()) {
637     return MVT::i1;
638   }
639   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
640 }
641
642 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
643   return MVT::i32;
644 }
645
646 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
647   VT = VT.getScalarType();
648
649   if (!VT.isSimple())
650     return false;
651
652   switch (VT.getSimpleVT().SimpleTy) {
653   case MVT::f32:
654     return false; /* There is V_MAD_F32 for f32 */
655   case MVT::f64:
656     return true;
657   default:
658     break;
659   }
660
661   return false;
662 }
663
664 //===----------------------------------------------------------------------===//
665 // Custom DAG Lowering Operations
666 //===----------------------------------------------------------------------===//
667
668 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
669   switch (Op.getOpcode()) {
670   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
671   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
672   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
673   case ISD::LOAD: {
674     SDValue Result = LowerLOAD(Op, DAG);
675     assert((!Result.getNode() ||
676             Result.getNode()->getNumValues() == 2) &&
677            "Load should return a value and a chain");
678     return Result;
679   }
680
681   case ISD::FSIN:
682   case ISD::FCOS:
683     return LowerTrig(Op, DAG);
684   case ISD::SELECT: return LowerSELECT(Op, DAG);
685   case ISD::FDIV: return LowerFDIV(Op, DAG);
686   case ISD::STORE: return LowerSTORE(Op, DAG);
687   case ISD::GlobalAddress: {
688     MachineFunction &MF = DAG.getMachineFunction();
689     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
690     return LowerGlobalAddress(MFI, Op, DAG);
691   }
692   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
693   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
694   }
695   return SDValue();
696 }
697
698 /// \brief Helper function for LowerBRCOND
699 static SDNode *findUser(SDValue Value, unsigned Opcode) {
700
701   SDNode *Parent = Value.getNode();
702   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
703        I != E; ++I) {
704
705     if (I.getUse().get() != Value)
706       continue;
707
708     if (I->getOpcode() == Opcode)
709       return *I;
710   }
711   return nullptr;
712 }
713
714 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
715
716   MachineFunction &MF = DAG.getMachineFunction();
717   const SIInstrInfo *TII =
718     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
719   const SIRegisterInfo &TRI = TII->getRegisterInfo();
720   FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
721   unsigned FrameIndex = FINode->getIndex();
722
723   CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
724     TRI.getPreloadedValue(MF, SIRegisterInfo::SCRATCH_WAVE_OFFSET), MVT::i32);
725
726   return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
727 }
728
729 /// This transforms the control flow intrinsics to get the branch destination as
730 /// last parameter, also switches branch target with BR if the need arise
731 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
732                                       SelectionDAG &DAG) const {
733
734   SDLoc DL(BRCOND);
735
736   SDNode *Intr = BRCOND.getOperand(1).getNode();
737   SDValue Target = BRCOND.getOperand(2);
738   SDNode *BR = nullptr;
739
740   if (Intr->getOpcode() == ISD::SETCC) {
741     // As long as we negate the condition everything is fine
742     SDNode *SetCC = Intr;
743     assert(SetCC->getConstantOperandVal(1) == 1);
744     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
745            ISD::SETNE);
746     Intr = SetCC->getOperand(0).getNode();
747
748   } else {
749     // Get the target from BR if we don't negate the condition
750     BR = findUser(BRCOND, ISD::BR);
751     Target = BR->getOperand(1);
752   }
753
754   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
755
756   // Build the result and
757   SmallVector<EVT, 4> Res;
758   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
759     Res.push_back(Intr->getValueType(i));
760
761   // operands of the new intrinsic call
762   SmallVector<SDValue, 4> Ops;
763   Ops.push_back(BRCOND.getOperand(0));
764   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
765     Ops.push_back(Intr->getOperand(i));
766   Ops.push_back(Target);
767
768   // build the new intrinsic call
769   SDNode *Result = DAG.getNode(
770     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
771     DAG.getVTList(Res), Ops).getNode();
772
773   if (BR) {
774     // Give the branch instruction our target
775     SDValue Ops[] = {
776       BR->getOperand(0),
777       BRCOND.getOperand(2)
778     };
779     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops);
780   }
781
782   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
783
784   // Copy the intrinsic results to registers
785   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
786     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
787     if (!CopyToReg)
788       continue;
789
790     Chain = DAG.getCopyToReg(
791       Chain, DL,
792       CopyToReg->getOperand(1),
793       SDValue(Result, i - 1),
794       SDValue());
795
796     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
797   }
798
799   // Remove the old intrinsic from the chain
800   DAG.ReplaceAllUsesOfValueWith(
801     SDValue(Intr, Intr->getNumValues() - 1),
802     Intr->getOperand(0));
803
804   return Chain;
805 }
806
807 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
808                                              SDValue Op,
809                                              SelectionDAG &DAG) const {
810   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
811
812   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
813     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
814
815   SDLoc DL(GSD);
816   const GlobalValue *GV = GSD->getGlobal();
817   MVT PtrVT = getPointerTy(GSD->getAddressSpace());
818
819   SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
820   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
821
822   SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
823                               DAG.getConstant(0, MVT::i32));
824   SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
825                               DAG.getConstant(1, MVT::i32));
826
827   SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
828                            PtrLo, GA);
829   SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
830                            PtrHi, DAG.getConstant(0, MVT::i32),
831                            SDValue(Lo.getNode(), 1));
832   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
833 }
834
835 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
836                                                   SelectionDAG &DAG) const {
837   MachineFunction &MF = DAG.getMachineFunction();
838   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
839
840   EVT VT = Op.getValueType();
841   SDLoc DL(Op);
842   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
843
844   switch (IntrinsicID) {
845   case Intrinsic::r600_read_ngroups_x:
846     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
847   case Intrinsic::r600_read_ngroups_y:
848     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
849   case Intrinsic::r600_read_ngroups_z:
850     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
851   case Intrinsic::r600_read_global_size_x:
852     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
853   case Intrinsic::r600_read_global_size_y:
854     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
855   case Intrinsic::r600_read_global_size_z:
856     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
857   case Intrinsic::r600_read_local_size_x:
858     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
859   case Intrinsic::r600_read_local_size_y:
860     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
861   case Intrinsic::r600_read_local_size_z:
862     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
863   case Intrinsic::r600_read_tgid_x:
864     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
865       AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 0), VT);
866   case Intrinsic::r600_read_tgid_y:
867     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
868       AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 1), VT);
869   case Intrinsic::r600_read_tgid_z:
870     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
871       AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 2), VT);
872   case Intrinsic::r600_read_tidig_x:
873     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
874                                 AMDGPU::VGPR0, VT);
875   case Intrinsic::r600_read_tidig_y:
876     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
877                                 AMDGPU::VGPR1, VT);
878   case Intrinsic::r600_read_tidig_z:
879     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
880                                 AMDGPU::VGPR2, VT);
881   case AMDGPUIntrinsic::SI_load_const: {
882     SDValue Ops[] = {
883       Op.getOperand(1),
884       Op.getOperand(2)
885     };
886
887     MachineMemOperand *MMO = MF.getMachineMemOperand(
888       MachinePointerInfo(),
889       MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
890       VT.getStoreSize(), 4);
891     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
892                                    Op->getVTList(), Ops, VT, MMO);
893   }
894   case AMDGPUIntrinsic::SI_sample:
895     return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
896   case AMDGPUIntrinsic::SI_sampleb:
897     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
898   case AMDGPUIntrinsic::SI_sampled:
899     return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
900   case AMDGPUIntrinsic::SI_samplel:
901     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
902   case AMDGPUIntrinsic::SI_vs_load_input:
903     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
904                        Op.getOperand(1),
905                        Op.getOperand(2),
906                        Op.getOperand(3));
907   default:
908     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
909   }
910 }
911
912 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
913                                               SelectionDAG &DAG) const {
914   MachineFunction &MF = DAG.getMachineFunction();
915   SDValue Chain = Op.getOperand(0);
916   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
917
918   switch (IntrinsicID) {
919   case AMDGPUIntrinsic::SI_tbuffer_store: {
920     SDLoc DL(Op);
921     SDValue Ops[] = {
922       Chain,
923       Op.getOperand(2),
924       Op.getOperand(3),
925       Op.getOperand(4),
926       Op.getOperand(5),
927       Op.getOperand(6),
928       Op.getOperand(7),
929       Op.getOperand(8),
930       Op.getOperand(9),
931       Op.getOperand(10),
932       Op.getOperand(11),
933       Op.getOperand(12),
934       Op.getOperand(13),
935       Op.getOperand(14)
936     };
937
938     EVT VT = Op.getOperand(3).getValueType();
939
940     MachineMemOperand *MMO = MF.getMachineMemOperand(
941       MachinePointerInfo(),
942       MachineMemOperand::MOStore,
943       VT.getStoreSize(), 4);
944     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
945                                    Op->getVTList(), Ops, VT, MMO);
946   }
947   default:
948     return SDValue();
949   }
950 }
951
952 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
953   SDLoc DL(Op);
954   LoadSDNode *Load = cast<LoadSDNode>(Op);
955
956   if (Op.getValueType().isVector()) {
957     assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
958            "Custom lowering for non-i32 vectors hasn't been implemented.");
959     unsigned NumElements = Op.getValueType().getVectorNumElements();
960     assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
961     switch (Load->getAddressSpace()) {
962       default: break;
963       case AMDGPUAS::GLOBAL_ADDRESS:
964       case AMDGPUAS::PRIVATE_ADDRESS:
965         // v4 loads are supported for private and global memory.
966         if (NumElements <= 4)
967           break;
968         // fall-through
969       case AMDGPUAS::LOCAL_ADDRESS:
970         return ScalarizeVectorLoad(Op, DAG);
971     }
972   }
973
974   return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
975 }
976
977 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
978                                                const SDValue &Op,
979                                                SelectionDAG &DAG) const {
980   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
981                      Op.getOperand(2),
982                      Op.getOperand(3),
983                      Op.getOperand(4));
984 }
985
986 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
987   if (Op.getValueType() != MVT::i64)
988     return SDValue();
989
990   SDLoc DL(Op);
991   SDValue Cond = Op.getOperand(0);
992
993   SDValue Zero = DAG.getConstant(0, MVT::i32);
994   SDValue One = DAG.getConstant(1, MVT::i32);
995
996   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
997   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
998
999   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1000   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1001
1002   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1003
1004   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1005   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1006
1007   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1008
1009   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1010   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1011 }
1012
1013 // Catch division cases where we can use shortcuts with rcp and rsq
1014 // instructions.
1015 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1016   SDLoc SL(Op);
1017   SDValue LHS = Op.getOperand(0);
1018   SDValue RHS = Op.getOperand(1);
1019   EVT VT = Op.getValueType();
1020   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1021
1022   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1023     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1024         CLHS->isExactlyValue(1.0)) {
1025       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1026       // the CI documentation has a worst case error of 1 ulp.
1027       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1028       // use it as long as we aren't trying to use denormals.
1029
1030       // 1.0 / sqrt(x) -> rsq(x)
1031       //
1032       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1033       // error seems really high at 2^29 ULP.
1034       if (RHS.getOpcode() == ISD::FSQRT)
1035         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1036
1037       // 1.0 / x -> rcp(x)
1038       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1039     }
1040   }
1041
1042   if (Unsafe) {
1043     // Turn into multiply by the reciprocal.
1044     // x / y -> x * (1.0 / y)
1045     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1046     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1047   }
1048
1049   return SDValue();
1050 }
1051
1052 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1053   SDValue FastLowered = LowerFastFDIV(Op, DAG);
1054   if (FastLowered.getNode())
1055     return FastLowered;
1056
1057   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1058   // selection error for now rather than do something incorrect.
1059   if (Subtarget->hasFP32Denormals())
1060     return SDValue();
1061
1062   SDLoc SL(Op);
1063   SDValue LHS = Op.getOperand(0);
1064   SDValue RHS = Op.getOperand(1);
1065
1066   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1067
1068   const APFloat K0Val(BitsToFloat(0x6f800000));
1069   const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1070
1071   const APFloat K1Val(BitsToFloat(0x2f800000));
1072   const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1073
1074   const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1075
1076   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1077
1078   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1079
1080   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1081
1082   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1083
1084   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1085
1086   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1087
1088   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1089 }
1090
1091 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1092   return SDValue();
1093 }
1094
1095 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1096   EVT VT = Op.getValueType();
1097
1098   if (VT == MVT::f32)
1099     return LowerFDIV32(Op, DAG);
1100
1101   if (VT == MVT::f64)
1102     return LowerFDIV64(Op, DAG);
1103
1104   llvm_unreachable("Unexpected type for fdiv");
1105 }
1106
1107 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1108   SDLoc DL(Op);
1109   StoreSDNode *Store = cast<StoreSDNode>(Op);
1110   EVT VT = Store->getMemoryVT();
1111
1112   // These stores are legal.
1113   if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1114       VT.isVector() && VT.getVectorNumElements() == 2 &&
1115       VT.getVectorElementType() == MVT::i32)
1116     return SDValue();
1117
1118   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1119     if (VT.isVector() && VT.getVectorNumElements() > 4)
1120       return ScalarizeVectorStore(Op, DAG);
1121     return SDValue();
1122   }
1123
1124   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1125   if (Ret.getNode())
1126     return Ret;
1127
1128   if (VT.isVector() && VT.getVectorNumElements() >= 8)
1129       return ScalarizeVectorStore(Op, DAG);
1130
1131   if (VT == MVT::i1)
1132     return DAG.getTruncStore(Store->getChain(), DL,
1133                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1134                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1135
1136   return SDValue();
1137 }
1138
1139 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1140   EVT VT = Op.getValueType();
1141   SDValue Arg = Op.getOperand(0);
1142   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1143         DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1144           DAG.getConstantFP(0.5 / M_PI, VT)));
1145
1146   switch (Op.getOpcode()) {
1147   case ISD::FCOS:
1148     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1149   case ISD::FSIN:
1150     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1151   default:
1152     llvm_unreachable("Wrong trig opcode");
1153   }
1154 }
1155
1156 //===----------------------------------------------------------------------===//
1157 // Custom DAG optimizations
1158 //===----------------------------------------------------------------------===//
1159
1160 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1161                                                      DAGCombinerInfo &DCI) {
1162   EVT VT = N->getValueType(0);
1163   EVT ScalarVT = VT.getScalarType();
1164   if (ScalarVT != MVT::f32)
1165     return SDValue();
1166
1167   SelectionDAG &DAG = DCI.DAG;
1168   SDLoc DL(N);
1169
1170   SDValue Src = N->getOperand(0);
1171   EVT SrcVT = Src.getValueType();
1172
1173   // TODO: We could try to match extracting the higher bytes, which would be
1174   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1175   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1176   // about in practice.
1177   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1178     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1179       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1180       DCI.AddToWorklist(Cvt.getNode());
1181       return Cvt;
1182     }
1183   }
1184
1185   // We are primarily trying to catch operations on illegal vector types
1186   // before they are expanded.
1187   // For scalars, we can use the more flexible method of checking masked bits
1188   // after legalization.
1189   if (!DCI.isBeforeLegalize() ||
1190       !SrcVT.isVector() ||
1191       SrcVT.getVectorElementType() != MVT::i8) {
1192     return SDValue();
1193   }
1194
1195   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1196
1197   // Weird sized vectors are a pain to handle, but we know 3 is really the same
1198   // size as 4.
1199   unsigned NElts = SrcVT.getVectorNumElements();
1200   if (!SrcVT.isSimple() && NElts != 3)
1201     return SDValue();
1202
1203   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1204   // prevent a mess from expanding to v4i32 and repacking.
1205   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1206     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1207     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1208     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1209
1210     LoadSDNode *Load = cast<LoadSDNode>(Src);
1211     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1212                                      Load->getChain(),
1213                                      Load->getBasePtr(),
1214                                      LoadVT,
1215                                      Load->getMemOperand());
1216
1217     // Make sure successors of the original load stay after it by updating
1218     // them to use the new Chain.
1219     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1220
1221     SmallVector<SDValue, 4> Elts;
1222     if (RegVT.isVector())
1223       DAG.ExtractVectorElements(NewLoad, Elts);
1224     else
1225       Elts.push_back(NewLoad);
1226
1227     SmallVector<SDValue, 4> Ops;
1228
1229     unsigned EltIdx = 0;
1230     for (SDValue Elt : Elts) {
1231       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1232       for (unsigned I = 0; I < ComponentsInElt; ++I) {
1233         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1234         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1235         DCI.AddToWorklist(Cvt.getNode());
1236         Ops.push_back(Cvt);
1237       }
1238
1239       ++EltIdx;
1240     }
1241
1242     assert(Ops.size() == NElts);
1243
1244     return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1245   }
1246
1247   return SDValue();
1248 }
1249
1250 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1251                                             DAGCombinerInfo &DCI) const {
1252   SelectionDAG &DAG = DCI.DAG;
1253   SDLoc DL(N);
1254   EVT VT = N->getValueType(0);
1255
1256   switch (N->getOpcode()) {
1257     default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1258     case ISD::SETCC: {
1259       SDValue Arg0 = N->getOperand(0);
1260       SDValue Arg1 = N->getOperand(1);
1261       SDValue CC = N->getOperand(2);
1262       ConstantSDNode * C = nullptr;
1263       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1264
1265       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1266       if (VT == MVT::i1
1267           && Arg0.getOpcode() == ISD::SIGN_EXTEND
1268           && Arg0.getOperand(0).getValueType() == MVT::i1
1269           && (C = dyn_cast<ConstantSDNode>(Arg1))
1270           && C->isNullValue()
1271           && CCOp == ISD::SETNE) {
1272         return SimplifySetCC(VT, Arg0.getOperand(0),
1273                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1274       }
1275       break;
1276     }
1277
1278   case AMDGPUISD::CVT_F32_UBYTE0:
1279   case AMDGPUISD::CVT_F32_UBYTE1:
1280   case AMDGPUISD::CVT_F32_UBYTE2:
1281   case AMDGPUISD::CVT_F32_UBYTE3: {
1282     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1283
1284     SDValue Src = N->getOperand(0);
1285     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1286
1287     APInt KnownZero, KnownOne;
1288     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1289                                           !DCI.isBeforeLegalizeOps());
1290     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1291     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1292         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1293       DCI.CommitTargetLoweringOpt(TLO);
1294     }
1295
1296     break;
1297   }
1298
1299   case ISD::UINT_TO_FP: {
1300     return performUCharToFloatCombine(N, DCI);
1301   }
1302   }
1303
1304   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1305 }
1306
1307 /// \brief Test if RegClass is one of the VSrc classes
1308 static bool isVSrc(unsigned RegClass) {
1309   return AMDGPU::VSrc_32RegClassID == RegClass ||
1310          AMDGPU::VSrc_64RegClassID == RegClass;
1311 }
1312
1313 /// \brief Test if RegClass is one of the SSrc classes
1314 static bool isSSrc(unsigned RegClass) {
1315   return AMDGPU::SSrc_32RegClassID == RegClass ||
1316          AMDGPU::SSrc_64RegClassID == RegClass;
1317 }
1318
1319 /// \brief Analyze the possible immediate value Op
1320 ///
1321 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1322 /// and the immediate value if it's a literal immediate
1323 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1324
1325   union {
1326     int32_t I;
1327     float F;
1328   } Imm;
1329
1330   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1331     if (Node->getZExtValue() >> 32) {
1332         return -1;
1333     }
1334     Imm.I = Node->getSExtValue();
1335   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1336     if (N->getValueType(0) != MVT::f32)
1337       return -1;
1338     Imm.F = Node->getValueAPF().convertToFloat();
1339   } else
1340     return -1; // It isn't an immediate
1341
1342   if ((Imm.I >= -16 && Imm.I <= 64) ||
1343       Imm.F == 0.5f || Imm.F == -0.5f ||
1344       Imm.F == 1.0f || Imm.F == -1.0f ||
1345       Imm.F == 2.0f || Imm.F == -2.0f ||
1346       Imm.F == 4.0f || Imm.F == -4.0f)
1347     return 0; // It's an inline immediate
1348
1349   return Imm.I; // It's a literal immediate
1350 }
1351
1352 /// \brief Try to fold an immediate directly into an instruction
1353 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1354                                bool &ScalarSlotUsed) const {
1355
1356   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1357   const SIInstrInfo *TII =
1358     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1359   if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1360     return false;
1361
1362   const SDValue &Op = Mov->getOperand(0);
1363   int32_t Value = analyzeImmediate(Op.getNode());
1364   if (Value == -1) {
1365     // Not an immediate at all
1366     return false;
1367
1368   } else if (Value == 0) {
1369     // Inline immediates can always be fold
1370     Operand = Op;
1371     return true;
1372
1373   } else if (Value == Immediate) {
1374     // Already fold literal immediate
1375     Operand = Op;
1376     return true;
1377
1378   } else if (!ScalarSlotUsed && !Immediate) {
1379     // Fold this literal immediate
1380     ScalarSlotUsed = true;
1381     Immediate = Value;
1382     Operand = Op;
1383     return true;
1384
1385   }
1386
1387   return false;
1388 }
1389
1390 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1391                                    SelectionDAG &DAG, const SDValue &Op) const {
1392   const SIInstrInfo *TII =
1393     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1394   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1395
1396   if (!Op->isMachineOpcode()) {
1397     switch(Op->getOpcode()) {
1398     case ISD::CopyFromReg: {
1399       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1400       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1401       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1402         return MRI.getRegClass(Reg);
1403       }
1404       return TRI.getPhysRegClass(Reg);
1405     }
1406     default:  return nullptr;
1407     }
1408   }
1409   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1410   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1411   if (OpClassID != -1) {
1412     return TRI.getRegClass(OpClassID);
1413   }
1414   switch(Op.getMachineOpcode()) {
1415   case AMDGPU::COPY_TO_REGCLASS:
1416     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1417     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1418
1419     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1420     // class, then the register class for the value could be either a
1421     // VReg or and SReg.  In order to get a more accurate
1422     if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1423         OpClassID == AMDGPU::VSrc_64RegClassID) {
1424       return getRegClassForNode(DAG, Op.getOperand(0));
1425     }
1426     return TRI.getRegClass(OpClassID);
1427   case AMDGPU::EXTRACT_SUBREG: {
1428     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1429     const TargetRegisterClass *SuperClass =
1430       getRegClassForNode(DAG, Op.getOperand(0));
1431     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1432   }
1433   case AMDGPU::REG_SEQUENCE:
1434     // Operand 0 is the register class id for REG_SEQUENCE instructions.
1435     return TRI.getRegClass(
1436       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1437   default:
1438     return getRegClassFor(Op.getSimpleValueType());
1439   }
1440 }
1441
1442 /// \brief Does "Op" fit into register class "RegClass" ?
1443 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1444                                     unsigned RegClass) const {
1445   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1446   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1447   if (!RC) {
1448     return false;
1449   }
1450   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1451 }
1452
1453 /// \brief Make sure that we don't exeed the number of allowed scalars
1454 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1455                                        unsigned RegClass,
1456                                        bool &ScalarSlotUsed) const {
1457
1458   // First map the operands register class to a destination class
1459   if (RegClass == AMDGPU::VSrc_32RegClassID)
1460     RegClass = AMDGPU::VReg_32RegClassID;
1461   else if (RegClass == AMDGPU::VSrc_64RegClassID)
1462     RegClass = AMDGPU::VReg_64RegClassID;
1463   else
1464     return;
1465
1466   // Nothing to do if they fit naturally
1467   if (fitsRegClass(DAG, Operand, RegClass))
1468     return;
1469
1470   // If the scalar slot isn't used yet use it now
1471   if (!ScalarSlotUsed) {
1472     ScalarSlotUsed = true;
1473     return;
1474   }
1475
1476   // This is a conservative aproach. It is possible that we can't determine the
1477   // correct register class and copy too often, but better safe than sorry.
1478
1479   SDNode *Node;
1480   // We can't use COPY_TO_REGCLASS with FrameIndex arguments.
1481   if (isa<FrameIndexSDNode>(Operand)) {
1482     unsigned Opcode = Operand.getValueType() == MVT::i32 ?
1483                       AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
1484     Node = DAG.getMachineNode(Opcode, SDLoc(), Operand.getValueType(),
1485                               Operand);
1486   } else {
1487     SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1488     Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1489                               Operand.getValueType(), Operand, RC);
1490   }
1491   Operand = SDValue(Node, 0);
1492 }
1493
1494 /// \returns true if \p Node's operands are different from the SDValue list
1495 /// \p Ops
1496 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1497   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1498     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1499       return true;
1500     }
1501   }
1502   return false;
1503 }
1504
1505 /// \brief Try to fold the Nodes operands into the Node
1506 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1507                                        SelectionDAG &DAG) const {
1508
1509   // Original encoding (either e32 or e64)
1510   int Opcode = Node->getMachineOpcode();
1511   const SIInstrInfo *TII =
1512     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1513   const MCInstrDesc *Desc = &TII->get(Opcode);
1514
1515   unsigned NumDefs = Desc->getNumDefs();
1516   unsigned NumOps = Desc->getNumOperands();
1517
1518   // Commuted opcode if available
1519   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1520   const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1521
1522   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1523   assert(!DescRev || DescRev->getNumOperands() == NumOps);
1524
1525   // e64 version if available, -1 otherwise
1526   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1527   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1528   int InputModifiers[3] = {0};
1529
1530   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1531
1532   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1533   bool HaveVSrc = false, HaveSSrc = false;
1534
1535   // First figure out what we already have in this instruction.
1536   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1537        i != e && Op < NumOps; ++i, ++Op) {
1538
1539     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1540     if (isVSrc(RegClass))
1541       HaveVSrc = true;
1542     else if (isSSrc(RegClass))
1543       HaveSSrc = true;
1544     else
1545       continue;
1546
1547     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1548     if (Imm != -1 && Imm != 0) {
1549       // Literal immediate
1550       Immediate = Imm;
1551     }
1552   }
1553
1554   // If we neither have VSrc nor SSrc, it makes no sense to continue.
1555   if (!HaveVSrc && !HaveSSrc)
1556     return Node;
1557
1558   // No scalar allowed when we have both VSrc and SSrc
1559   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1560
1561   // Second go over the operands and try to fold them
1562   std::vector<SDValue> Ops;
1563   bool Promote2e64 = false;
1564   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1565        i != e && Op < NumOps; ++i, ++Op) {
1566
1567     const SDValue &Operand = Node->getOperand(i);
1568     Ops.push_back(Operand);
1569
1570     // Already folded immediate?
1571     if (isa<ConstantSDNode>(Operand.getNode()) ||
1572         isa<ConstantFPSDNode>(Operand.getNode()))
1573       continue;
1574
1575     // Is this a VSrc or SSrc operand?
1576     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1577     if (isVSrc(RegClass) || isSSrc(RegClass)) {
1578       // Try to fold the immediates
1579       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1580         // Folding didn't work, make sure we don't hit the SReg limit.
1581         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1582       }
1583       continue;
1584     } else {
1585       // If it's not a VSrc or SSrc operand check if we have a GlobalAddress.
1586       // These will be lowered to immediates, so we will need to insert a MOV.
1587       if (isa<GlobalAddressSDNode>(Ops[i])) {
1588         SDNode *Node = DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, SDLoc(),
1589                                     Operand.getValueType(), Operand);
1590         Ops[i] = SDValue(Node, 0);
1591       }
1592     }
1593
1594     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1595
1596       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1597       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1598
1599       // Test if it makes sense to swap operands
1600       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1601           (!fitsRegClass(DAG, Ops[1], RegClass) &&
1602            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1603
1604         // Swap commutable operands
1605         std::swap(Ops[0], Ops[1]);
1606
1607         Desc = DescRev;
1608         DescRev = nullptr;
1609         continue;
1610       }
1611     }
1612
1613     if (Immediate)
1614       continue;
1615
1616     if (DescE64) {
1617       // Test if it makes sense to switch to e64 encoding
1618       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1619       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1620         continue;
1621
1622       int32_t TmpImm = -1;
1623       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1624           (!fitsRegClass(DAG, Ops[i], RegClass) &&
1625            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1626
1627         // Switch to e64 encoding
1628         Immediate = -1;
1629         Promote2e64 = true;
1630         Desc = DescE64;
1631         DescE64 = nullptr;
1632       }
1633     }
1634
1635     if (!DescE64 && !Promote2e64)
1636       continue;
1637     if (!Operand.isMachineOpcode())
1638       continue;
1639     if (Operand.getMachineOpcode() == AMDGPU::FNEG_SI) {
1640       Ops.pop_back();
1641       Ops.push_back(Operand.getOperand(0));
1642       InputModifiers[i] = 1;
1643       Promote2e64 = true;
1644       if (!DescE64)
1645         continue;
1646       Desc = DescE64;
1647       DescE64 = nullptr;
1648     }
1649     else if (Operand.getMachineOpcode() == AMDGPU::FABS_SI) {
1650       Ops.pop_back();
1651       Ops.push_back(Operand.getOperand(0));
1652       InputModifiers[i] = 2;
1653       Promote2e64 = true;
1654       if (!DescE64)
1655         continue;
1656       Desc = DescE64;
1657       DescE64 = nullptr;
1658     }
1659   }
1660
1661   if (Promote2e64) {
1662     std::vector<SDValue> OldOps(Ops);
1663     Ops.clear();
1664     for (unsigned i = 0; i < OldOps.size(); ++i) {
1665       // src_modifier
1666       Ops.push_back(DAG.getTargetConstant(InputModifiers[i], MVT::i32));
1667       Ops.push_back(OldOps[i]);
1668     }
1669     // Add the modifier flags while promoting
1670     for (unsigned i = 0; i < 2; ++i)
1671       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1672   }
1673
1674   // Add optional chain and glue
1675   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1676     Ops.push_back(Node->getOperand(i));
1677
1678   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1679   // this case a brand new node is always be created, even if the operands
1680   // are the same as before.  So, manually check if anything has been changed.
1681   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1682     return Node;
1683   }
1684
1685   // Create a complete new instruction
1686   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1687 }
1688
1689 /// \brief Helper function for adjustWritemask
1690 static unsigned SubIdx2Lane(unsigned Idx) {
1691   switch (Idx) {
1692   default: return 0;
1693   case AMDGPU::sub0: return 0;
1694   case AMDGPU::sub1: return 1;
1695   case AMDGPU::sub2: return 2;
1696   case AMDGPU::sub3: return 3;
1697   }
1698 }
1699
1700 /// \brief Adjust the writemask of MIMG instructions
1701 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1702                                        SelectionDAG &DAG) const {
1703   SDNode *Users[4] = { };
1704   unsigned Lane = 0;
1705   unsigned OldDmask = Node->getConstantOperandVal(0);
1706   unsigned NewDmask = 0;
1707
1708   // Try to figure out the used register components
1709   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1710        I != E; ++I) {
1711
1712     // Abort if we can't understand the usage
1713     if (!I->isMachineOpcode() ||
1714         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1715       return;
1716
1717     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1718     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1719     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1720     // set, etc.
1721     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1722
1723     // Set which texture component corresponds to the lane.
1724     unsigned Comp;
1725     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1726       assert(Dmask);
1727       Comp = countTrailingZeros(Dmask);
1728       Dmask &= ~(1 << Comp);
1729     }
1730
1731     // Abort if we have more than one user per component
1732     if (Users[Lane])
1733       return;
1734
1735     Users[Lane] = *I;
1736     NewDmask |= 1 << Comp;
1737   }
1738
1739   // Abort if there's no change
1740   if (NewDmask == OldDmask)
1741     return;
1742
1743   // Adjust the writemask in the node
1744   std::vector<SDValue> Ops;
1745   Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1746   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1747     Ops.push_back(Node->getOperand(i));
1748   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1749
1750   // If we only got one lane, replace it with a copy
1751   // (if NewDmask has only one bit set...)
1752   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1753     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1754     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1755                                       SDLoc(), Users[Lane]->getValueType(0),
1756                                       SDValue(Node, 0), RC);
1757     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1758     return;
1759   }
1760
1761   // Update the users of the node with the new indices
1762   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1763
1764     SDNode *User = Users[i];
1765     if (!User)
1766       continue;
1767
1768     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1769     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1770
1771     switch (Idx) {
1772     default: break;
1773     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1774     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1775     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1776     }
1777   }
1778 }
1779
1780 /// \brief Fold the instructions after selecting them.
1781 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1782                                           SelectionDAG &DAG) const {
1783   const SIInstrInfo *TII =
1784       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1785   Node = AdjustRegClass(Node, DAG);
1786
1787   if (TII->isMIMG(Node->getMachineOpcode()))
1788     adjustWritemask(Node, DAG);
1789
1790   return foldOperands(Node, DAG);
1791 }
1792
1793 /// \brief Assign the register class depending on the number of
1794 /// bits set in the writemask
1795 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1796                                                      SDNode *Node) const {
1797   const SIInstrInfo *TII =
1798       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1799   if (!TII->isMIMG(MI->getOpcode()))
1800     return;
1801
1802   unsigned VReg = MI->getOperand(0).getReg();
1803   unsigned Writemask = MI->getOperand(1).getImm();
1804   unsigned BitsSet = 0;
1805   for (unsigned i = 0; i < 4; ++i)
1806     BitsSet += Writemask & (1 << i) ? 1 : 0;
1807
1808   const TargetRegisterClass *RC;
1809   switch (BitsSet) {
1810   default: return;
1811   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1812   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1813   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1814   }
1815
1816   unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1817   MI->setDesc(TII->get(NewOpcode));
1818   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1819   MRI.setRegClass(VReg, RC);
1820 }
1821
1822 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1823                                                 SelectionDAG &DAG) const {
1824
1825   SDLoc DL(N);
1826   unsigned NewOpcode = N->getMachineOpcode();
1827
1828   switch (N->getMachineOpcode()) {
1829   default: return N;
1830   case AMDGPU::S_LOAD_DWORD_IMM:
1831     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1832     // Fall-through
1833   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1834     if (NewOpcode == N->getMachineOpcode()) {
1835       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1836     }
1837     // Fall-through
1838   case AMDGPU::S_LOAD_DWORDX4_IMM:
1839   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1840     if (NewOpcode == N->getMachineOpcode()) {
1841       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1842     }
1843     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1844       return N;
1845     }
1846     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1847     SDValue Ops[] = {
1848       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1849                                  DAG.getConstant(0, MVT::i64)), 0),
1850       N->getOperand(0),
1851       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1852     };
1853     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1854   }
1855   }
1856 }
1857
1858 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1859                                                const TargetRegisterClass *RC,
1860                                                unsigned Reg, EVT VT) const {
1861   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1862
1863   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1864                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1865 }