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