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