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