d7ee8e64bffa2ada1db586156ddf81ec5005dc63
[oota-llvm.git] / lib / Target / R600 / AMDGPUISelLowering.cpp
1 //===-- AMDGPUISelLowering.cpp - AMDGPU Common DAG lowering functions -----===//
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 This is the parent TargetLowering class for hardware code gen
12 /// targets.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "AMDGPUISelLowering.h"
17 #include "AMDGPU.h"
18 #include "AMDGPUFrameLowering.h"
19 #include "AMDGPURegisterInfo.h"
20 #include "AMDGPUSubtarget.h"
21 #include "AMDILIntrinsicInfo.h"
22 #include "R600MachineFunctionInfo.h"
23 #include "SIMachineFunctionInfo.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/IR/DataLayout.h"
30
31 using namespace llvm;
32 static bool allocateStack(unsigned ValNo, MVT ValVT, MVT LocVT,
33                       CCValAssign::LocInfo LocInfo,
34                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
35   unsigned Offset = State.AllocateStack(ValVT.getStoreSize(),
36                                         ArgFlags.getOrigAlign());
37   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
38
39   return true;
40 }
41
42 #include "AMDGPUGenCallingConv.inc"
43
44 AMDGPUTargetLowering::AMDGPUTargetLowering(TargetMachine &TM) :
45   TargetLowering(TM, new TargetLoweringObjectFileELF()) {
46
47   // Initialize target lowering borrowed from AMDIL
48   InitAMDILLowering();
49
50   // We need to custom lower some of the intrinsics
51   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
52
53   // Library functions.  These default to Expand, but we have instructions
54   // for them.
55   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
56   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
57   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
58   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
59   setOperationAction(ISD::FABS,   MVT::f32, Legal);
60   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
61   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
62   setOperationAction(ISD::FROUND, MVT::f32, Legal);
63
64   // The hardware supports ROTR, but not ROTL
65   setOperationAction(ISD::ROTL, MVT::i32, Expand);
66
67   // Lower floating point store/load to integer store/load to reduce the number
68   // of patterns in tablegen.
69   setOperationAction(ISD::STORE, MVT::f32, Promote);
70   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
71
72   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
73   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
74
75   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
76   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
77
78   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
79   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
80
81   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
82   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
83
84   setOperationAction(ISD::STORE, MVT::f64, Promote);
85   AddPromotedToType(ISD::STORE, MVT::f64, MVT::i64);
86
87   // Custom lowering of vector stores is required for local address space
88   // stores.
89   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
90   // XXX: Native v2i32 local address space stores are possible, but not
91   // currently implemented.
92   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
93
94   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
95   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
96   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Custom);
97   // XXX: This can be change to Custom, once ExpandVectorStores can
98   // handle 64-bit stores.
99   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
100
101   setOperationAction(ISD::LOAD, MVT::f32, Promote);
102   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
103
104   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
105   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
106
107   setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
108   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
109
110   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
111   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
112
113   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
114   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
115
116   setOperationAction(ISD::LOAD, MVT::f64, Promote);
117   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::i64);
118
119   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
120   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
121   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
123
124   setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Expand);
125   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Expand);
126   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i8, Expand);
127   setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Expand);
128   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Expand);
129   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i8, Expand);
130   setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Expand);
131   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Expand);
132   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i16, Expand);
133   setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Expand);
134   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Expand);
135   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, Expand);
136
137   setOperationAction(ISD::FNEG, MVT::v2f32, Expand);
138   setOperationAction(ISD::FNEG, MVT::v4f32, Expand);
139
140   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
141
142   setOperationAction(ISD::MUL, MVT::i64, Expand);
143
144   setOperationAction(ISD::UDIV, MVT::i32, Expand);
145   setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
146   setOperationAction(ISD::UREM, MVT::i32, Expand);
147   setOperationAction(ISD::VSELECT, MVT::v2f32, Expand);
148   setOperationAction(ISD::VSELECT, MVT::v4f32, Expand);
149
150   static const MVT::SimpleValueType IntTypes[] = {
151     MVT::v2i32, MVT::v4i32
152   };
153   const size_t NumIntTypes = array_lengthof(IntTypes);
154
155   for (unsigned int x  = 0; x < NumIntTypes; ++x) {
156     MVT::SimpleValueType VT = IntTypes[x];
157     //Expand the following operations for the current type by default
158     setOperationAction(ISD::ADD,  VT, Expand);
159     setOperationAction(ISD::AND,  VT, Expand);
160     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
161     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
162     setOperationAction(ISD::MUL,  VT, Expand);
163     setOperationAction(ISD::OR,   VT, Expand);
164     setOperationAction(ISD::SHL,  VT, Expand);
165     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
166     setOperationAction(ISD::SRL,  VT, Expand);
167     setOperationAction(ISD::SRA,  VT, Expand);
168     setOperationAction(ISD::SUB,  VT, Expand);
169     setOperationAction(ISD::UDIV, VT, Expand);
170     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
171     setOperationAction(ISD::UREM, VT, Expand);
172     setOperationAction(ISD::VSELECT, VT, Expand);
173     setOperationAction(ISD::XOR,  VT, Expand);
174   }
175
176   static const MVT::SimpleValueType FloatTypes[] = {
177     MVT::v2f32, MVT::v4f32
178   };
179   const size_t NumFloatTypes = array_lengthof(FloatTypes);
180
181   for (unsigned int x = 0; x < NumFloatTypes; ++x) {
182     MVT::SimpleValueType VT = FloatTypes[x];
183     setOperationAction(ISD::FABS, VT, Expand);
184     setOperationAction(ISD::FADD, VT, Expand);
185     setOperationAction(ISD::FDIV, VT, Expand);
186     setOperationAction(ISD::FFLOOR, VT, Expand);
187     setOperationAction(ISD::FMUL, VT, Expand);
188     setOperationAction(ISD::FRINT, VT, Expand);
189     setOperationAction(ISD::FSQRT, VT, Expand);
190     setOperationAction(ISD::FSUB, VT, Expand);
191   }
192 }
193
194 //===----------------------------------------------------------------------===//
195 // Target Information
196 //===----------------------------------------------------------------------===//
197
198 MVT AMDGPUTargetLowering::getVectorIdxTy() const {
199   return MVT::i32;
200 }
201
202 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
203                                                    EVT CastTy) const {
204   if (LoadTy.getSizeInBits() != CastTy.getSizeInBits())
205     return true;
206
207   unsigned LScalarSize = LoadTy.getScalarType().getSizeInBits();
208   unsigned CastScalarSize = CastTy.getScalarType().getSizeInBits();
209
210   return ((LScalarSize <= CastScalarSize) ||
211           (CastScalarSize >= 32) ||
212           (LScalarSize < 32));
213 }
214
215 //===---------------------------------------------------------------------===//
216 // Target Properties
217 //===---------------------------------------------------------------------===//
218
219 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
220   assert(VT.isFloatingPoint());
221   return VT == MVT::f32;
222 }
223
224 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
225   assert(VT.isFloatingPoint());
226   return VT == MVT::f32;
227 }
228
229 //===---------------------------------------------------------------------===//
230 // TargetLowering Callbacks
231 //===---------------------------------------------------------------------===//
232
233 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
234                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
235
236   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
237 }
238
239 SDValue AMDGPUTargetLowering::LowerReturn(
240                                      SDValue Chain,
241                                      CallingConv::ID CallConv,
242                                      bool isVarArg,
243                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
244                                      const SmallVectorImpl<SDValue> &OutVals,
245                                      SDLoc DL, SelectionDAG &DAG) const {
246   return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, Chain);
247 }
248
249 //===---------------------------------------------------------------------===//
250 // Target specific lowering
251 //===---------------------------------------------------------------------===//
252
253 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG)
254     const {
255   switch (Op.getOpcode()) {
256   default:
257     Op.getNode()->dump();
258     llvm_unreachable("Custom lowering code for this"
259                      "instruction is not implemented yet!");
260     break;
261   // AMDIL DAG lowering
262   case ISD::SDIV: return LowerSDIV(Op, DAG);
263   case ISD::SREM: return LowerSREM(Op, DAG);
264   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
265   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
266   // AMDGPU DAG lowering
267   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
268   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
269   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
270   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
271   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
272   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
273   }
274   return Op;
275 }
276
277 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
278                                                  SDValue Op,
279                                                  SelectionDAG &DAG) const {
280
281   const DataLayout *TD = getTargetMachine().getDataLayout();
282   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
283
284   assert(G->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS);
285   // XXX: What does the value of G->getOffset() mean?
286   assert(G->getOffset() == 0 &&
287          "Do not know what to do with an non-zero offset");
288
289   const GlobalValue *GV = G->getGlobal();
290
291   unsigned Offset;
292   if (MFI->LocalMemoryObjects.count(GV) == 0) {
293     uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
294     Offset = MFI->LDSSize;
295     MFI->LocalMemoryObjects[GV] = Offset;
296     // XXX: Account for alignment?
297     MFI->LDSSize += Size;
298   } else {
299     Offset = MFI->LocalMemoryObjects[GV];
300   }
301
302   return DAG.getConstant(Offset, getPointerTy(G->getAddressSpace()));
303 }
304
305 void AMDGPUTargetLowering::ExtractVectorElements(SDValue Op, SelectionDAG &DAG,
306                                          SmallVectorImpl<SDValue> &Args,
307                                          unsigned Start,
308                                          unsigned Count) const {
309   EVT VT = Op.getValueType();
310   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
311     Args.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op),
312                                VT.getVectorElementType(),
313                                Op, DAG.getConstant(i, MVT::i32)));
314   }
315 }
316
317 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
318                                                   SelectionDAG &DAG) const {
319   SmallVector<SDValue, 8> Args;
320   SDValue A = Op.getOperand(0);
321   SDValue B = Op.getOperand(1);
322
323   ExtractVectorElements(A, DAG, Args, 0,
324                         A.getValueType().getVectorNumElements());
325   ExtractVectorElements(B, DAG, Args, 0,
326                         B.getValueType().getVectorNumElements());
327
328   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(),
329                      &Args[0], Args.size());
330 }
331
332 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
333                                                      SelectionDAG &DAG) const {
334
335   SmallVector<SDValue, 8> Args;
336   EVT VT = Op.getValueType();
337   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
338   ExtractVectorElements(Op.getOperand(0), DAG, Args, Start,
339                         VT.getVectorNumElements());
340
341   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(),
342                      &Args[0], Args.size());
343 }
344
345 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
346                                               SelectionDAG &DAG) const {
347
348   MachineFunction &MF = DAG.getMachineFunction();
349   const AMDGPUFrameLowering *TFL =
350    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
351
352   FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op);
353   assert(FIN);
354
355   unsigned FrameIndex = FIN->getIndex();
356   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
357   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF),
358                          Op.getValueType());
359 }
360
361 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
362     SelectionDAG &DAG) const {
363   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
364   SDLoc DL(Op);
365   EVT VT = Op.getValueType();
366
367   switch (IntrinsicID) {
368     default: return Op;
369     case AMDGPUIntrinsic::AMDIL_abs:
370       return LowerIntrinsicIABS(Op, DAG);
371     case AMDGPUIntrinsic::AMDIL_exp:
372       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
373     case AMDGPUIntrinsic::AMDGPU_lrp:
374       return LowerIntrinsicLRP(Op, DAG);
375     case AMDGPUIntrinsic::AMDIL_fraction:
376       return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
377     case AMDGPUIntrinsic::AMDIL_max:
378       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, Op.getOperand(1),
379                                                   Op.getOperand(2));
380     case AMDGPUIntrinsic::AMDGPU_imax:
381       return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Op.getOperand(1),
382                                                   Op.getOperand(2));
383     case AMDGPUIntrinsic::AMDGPU_umax:
384       return DAG.getNode(AMDGPUISD::UMAX, DL, VT, Op.getOperand(1),
385                                                   Op.getOperand(2));
386     case AMDGPUIntrinsic::AMDIL_min:
387       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, Op.getOperand(1),
388                                                   Op.getOperand(2));
389     case AMDGPUIntrinsic::AMDGPU_imin:
390       return DAG.getNode(AMDGPUISD::SMIN, DL, VT, Op.getOperand(1),
391                                                   Op.getOperand(2));
392     case AMDGPUIntrinsic::AMDGPU_umin:
393       return DAG.getNode(AMDGPUISD::UMIN, DL, VT, Op.getOperand(1),
394                                                   Op.getOperand(2));
395     case AMDGPUIntrinsic::AMDIL_round_nearest:
396       return DAG.getNode(ISD::FRINT, DL, VT, Op.getOperand(1));
397   }
398 }
399
400 ///IABS(a) = SMAX(sub(0, a), a)
401 SDValue AMDGPUTargetLowering::LowerIntrinsicIABS(SDValue Op,
402     SelectionDAG &DAG) const {
403
404   SDLoc DL(Op);
405   EVT VT = Op.getValueType();
406   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
407                                               Op.getOperand(1));
408
409   return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Neg, Op.getOperand(1));
410 }
411
412 /// Linear Interpolation
413 /// LRP(a, b, c) = muladd(a,  b, (1 - a) * c)
414 SDValue AMDGPUTargetLowering::LowerIntrinsicLRP(SDValue Op,
415     SelectionDAG &DAG) const {
416   SDLoc DL(Op);
417   EVT VT = Op.getValueType();
418   SDValue OneSubA = DAG.getNode(ISD::FSUB, DL, VT,
419                                 DAG.getConstantFP(1.0f, MVT::f32),
420                                 Op.getOperand(1));
421   SDValue OneSubAC = DAG.getNode(ISD::FMUL, DL, VT, OneSubA,
422                                                     Op.getOperand(3));
423   return DAG.getNode(ISD::FADD, DL, VT,
424       DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), Op.getOperand(2)),
425       OneSubAC);
426 }
427
428 /// \brief Generate Min/Max node
429 SDValue AMDGPUTargetLowering::LowerMinMax(SDValue Op,
430     SelectionDAG &DAG) const {
431   SDLoc DL(Op);
432   EVT VT = Op.getValueType();
433
434   SDValue LHS = Op.getOperand(0);
435   SDValue RHS = Op.getOperand(1);
436   SDValue True = Op.getOperand(2);
437   SDValue False = Op.getOperand(3);
438   SDValue CC = Op.getOperand(4);
439
440   if (VT != MVT::f32 ||
441       !((LHS == True && RHS == False) || (LHS == False && RHS == True))) {
442     return SDValue();
443   }
444
445   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
446   switch (CCOpcode) {
447   case ISD::SETOEQ:
448   case ISD::SETONE:
449   case ISD::SETUNE:
450   case ISD::SETNE:
451   case ISD::SETUEQ:
452   case ISD::SETEQ:
453   case ISD::SETFALSE:
454   case ISD::SETFALSE2:
455   case ISD::SETTRUE:
456   case ISD::SETTRUE2:
457   case ISD::SETUO:
458   case ISD::SETO:
459     llvm_unreachable("Operation should already be optimised!");
460   case ISD::SETULE:
461   case ISD::SETULT:
462   case ISD::SETOLE:
463   case ISD::SETOLT:
464   case ISD::SETLE:
465   case ISD::SETLT: {
466     if (LHS == True)
467       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, LHS, RHS);
468     else
469       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, LHS, RHS);
470   }
471   case ISD::SETGT:
472   case ISD::SETGE:
473   case ISD::SETUGE:
474   case ISD::SETOGE:
475   case ISD::SETUGT:
476   case ISD::SETOGT: {
477     if (LHS == True)
478       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, LHS, RHS);
479     else
480       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, LHS, RHS);
481   }
482   case ISD::SETCC_INVALID:
483     llvm_unreachable("Invalid setcc condcode!");
484   }
485   return Op;
486 }
487
488 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue &Op,
489                                               SelectionDAG &DAG) const {
490   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
491   EVT MemEltVT = Load->getMemoryVT().getVectorElementType();
492   EVT EltVT = Op.getValueType().getVectorElementType();
493   EVT PtrVT = Load->getBasePtr().getValueType();
494   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
495   SmallVector<SDValue, 8> Loads;
496   SDLoc SL(Op);
497
498   for (unsigned i = 0, e = NumElts; i != e; ++i) {
499     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
500                     DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8), PtrVT));
501     Loads.push_back(DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
502                         Load->getChain(), Ptr,
503                         MachinePointerInfo(Load->getMemOperand()->getValue()),
504                         MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
505                         Load->getAlignment()));
506   }
507   return DAG.getNode(ISD::BUILD_VECTOR, SL, Op.getValueType(), &Loads[0],
508                      Loads.size());
509 }
510
511 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
512                                                SelectionDAG &DAG) const {
513   StoreSDNode *Store = dyn_cast<StoreSDNode>(Op);
514   EVT MemVT = Store->getMemoryVT();
515   unsigned MemBits = MemVT.getSizeInBits();
516
517   // Byte stores are really expensive, so if possible, try to pack
518   // 32-bit vector truncatating store into an i32 store.
519   // XXX: We could also handle optimize other vector bitwidths
520   if (!MemVT.isVector() || MemBits > 32) {
521     return SDValue();
522   }
523
524   SDLoc DL(Op);
525   const SDValue &Value = Store->getValue();
526   EVT VT = Value.getValueType();
527   const SDValue &Ptr = Store->getBasePtr();
528   EVT MemEltVT = MemVT.getVectorElementType();
529   unsigned MemEltBits = MemEltVT.getSizeInBits();
530   unsigned MemNumElements = MemVT.getVectorNumElements();
531   EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
532   SDValue Mask;
533   switch(MemEltBits) {
534   case 8:
535     Mask = DAG.getConstant(0xFF, PackedVT);
536     break;
537   case 16:
538     Mask = DAG.getConstant(0xFFFF, PackedVT);
539     break;
540   default:
541     llvm_unreachable("Cannot lower this vector store");
542   }
543   SDValue PackedValue;
544   for (unsigned i = 0; i < MemNumElements; ++i) {
545     EVT ElemVT = VT.getVectorElementType();
546     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
547                               DAG.getConstant(i, MVT::i32));
548     Elt = DAG.getZExtOrTrunc(Elt, DL, PackedVT);
549     Elt = DAG.getNode(ISD::AND, DL, PackedVT, Elt, Mask);
550     SDValue Shift = DAG.getConstant(MemEltBits * i, PackedVT);
551     Elt = DAG.getNode(ISD::SHL, DL, PackedVT, Elt, Shift);
552     if (i == 0) {
553       PackedValue = Elt;
554     } else {
555       PackedValue = DAG.getNode(ISD::OR, DL, PackedVT, PackedValue, Elt);
556     }
557   }
558   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
559                       MachinePointerInfo(Store->getMemOperand()->getValue()),
560                       Store->isVolatile(),  Store->isNonTemporal(),
561                       Store->getAlignment());
562 }
563
564 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
565                                             SelectionDAG &DAG) const {
566   StoreSDNode *Store = cast<StoreSDNode>(Op);
567   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
568   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
569   EVT PtrVT = Store->getBasePtr().getValueType();
570   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
571   SDLoc SL(Op);
572
573   SmallVector<SDValue, 8> Chains;
574
575   for (unsigned i = 0, e = NumElts; i != e; ++i) {
576     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
577                               Store->getValue(), DAG.getConstant(i, MVT::i32));
578     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT,
579                               Store->getBasePtr(),
580                             DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8),
581                                             PtrVT));
582     Chains.push_back(DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
583                          MachinePointerInfo(Store->getMemOperand()->getValue()),
584                          MemEltVT, Store->isVolatile(), Store->isNonTemporal(),
585                          Store->getAlignment()));
586   }
587   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, &Chains[0], NumElts);
588 }
589
590 SDValue AMDGPUTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
591   SDValue Result = AMDGPUTargetLowering::MergeVectorStore(Op, DAG);
592   if (Result.getNode()) {
593     return Result;
594   }
595
596   StoreSDNode *Store = cast<StoreSDNode>(Op);
597   if ((Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
598        Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
599       Store->getValue().getValueType().isVector()) {
600     return SplitVectorStore(Op, DAG);
601   }
602   return SDValue();
603 }
604
605 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
606     SelectionDAG &DAG) const {
607   SDLoc DL(Op);
608   EVT VT = Op.getValueType();
609
610   SDValue Num = Op.getOperand(0);
611   SDValue Den = Op.getOperand(1);
612
613   SmallVector<SDValue, 8> Results;
614
615   // RCP =  URECIP(Den) = 2^32 / Den + e
616   // e is rounding error.
617   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
618
619   // RCP_LO = umulo(RCP, Den) */
620   SDValue RCP_LO = DAG.getNode(ISD::UMULO, DL, VT, RCP, Den);
621
622   // RCP_HI = mulhu (RCP, Den) */
623   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
624
625   // NEG_RCP_LO = -RCP_LO
626   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
627                                                      RCP_LO);
628
629   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
630   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
631                                            NEG_RCP_LO, RCP_LO,
632                                            ISD::SETEQ);
633   // Calculate the rounding error from the URECIP instruction
634   // E = mulhu(ABS_RCP_LO, RCP)
635   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
636
637   // RCP_A_E = RCP + E
638   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
639
640   // RCP_S_E = RCP - E
641   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
642
643   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
644   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
645                                      RCP_A_E, RCP_S_E,
646                                      ISD::SETEQ);
647   // Quotient = mulhu(Tmp0, Num)
648   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
649
650   // Num_S_Remainder = Quotient * Den
651   SDValue Num_S_Remainder = DAG.getNode(ISD::UMULO, DL, VT, Quotient, Den);
652
653   // Remainder = Num - Num_S_Remainder
654   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
655
656   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
657   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
658                                                  DAG.getConstant(-1, VT),
659                                                  DAG.getConstant(0, VT),
660                                                  ISD::SETUGE);
661   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
662   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
663                                                   Num_S_Remainder,
664                                                   DAG.getConstant(-1, VT),
665                                                   DAG.getConstant(0, VT),
666                                                   ISD::SETUGE);
667   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
668   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
669                                                Remainder_GE_Zero);
670
671   // Calculate Division result:
672
673   // Quotient_A_One = Quotient + 1
674   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
675                                                          DAG.getConstant(1, VT));
676
677   // Quotient_S_One = Quotient - 1
678   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
679                                                          DAG.getConstant(1, VT));
680
681   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
682   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
683                                      Quotient, Quotient_A_One, ISD::SETEQ);
684
685   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
686   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
687                             Quotient_S_One, Div, ISD::SETEQ);
688
689   // Calculate Rem result:
690
691   // Remainder_S_Den = Remainder - Den
692   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
693
694   // Remainder_A_Den = Remainder + Den
695   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
696
697   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
698   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
699                                     Remainder, Remainder_S_Den, ISD::SETEQ);
700
701   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
702   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
703                             Remainder_A_Den, Rem, ISD::SETEQ);
704   SDValue Ops[2];
705   Ops[0] = Div;
706   Ops[1] = Rem;
707   return DAG.getMergeValues(Ops, 2, DL);
708 }
709
710 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
711                                                SelectionDAG &DAG) const {
712   SDValue S0 = Op.getOperand(0);
713   SDLoc DL(Op);
714   if (Op.getValueType() != MVT::f32 || S0.getValueType() != MVT::i64)
715     return SDValue();
716
717   // f32 uint_to_fp i64
718   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
719                            DAG.getConstant(0, MVT::i32));
720   SDValue FloatLo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Lo);
721   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
722                            DAG.getConstant(1, MVT::i32));
723   SDValue FloatHi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Hi);
724   FloatHi = DAG.getNode(ISD::FMUL, DL, MVT::f32, FloatHi,
725                         DAG.getConstantFP(4294967296.0f, MVT::f32)); // 2^32
726   return DAG.getNode(ISD::FADD, DL, MVT::f32, FloatLo, FloatHi);
727
728 }
729
730 //===----------------------------------------------------------------------===//
731 // Helper functions
732 //===----------------------------------------------------------------------===//
733
734 void AMDGPUTargetLowering::getOriginalFunctionArgs(
735                                SelectionDAG &DAG,
736                                const Function *F,
737                                const SmallVectorImpl<ISD::InputArg> &Ins,
738                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
739
740   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
741     if (Ins[i].ArgVT == Ins[i].VT) {
742       OrigIns.push_back(Ins[i]);
743       continue;
744     }
745
746     EVT VT;
747     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
748       // Vector has been split into scalars.
749       VT = Ins[i].ArgVT.getVectorElementType();
750     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
751                Ins[i].ArgVT.getVectorElementType() !=
752                Ins[i].VT.getVectorElementType()) {
753       // Vector elements have been promoted
754       VT = Ins[i].ArgVT;
755     } else {
756       // Vector has been spilt into smaller vectors.
757       VT = Ins[i].VT;
758     }
759
760     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
761                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
762     OrigIns.push_back(Arg);
763   }
764 }
765
766 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
767   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
768     return CFP->isExactlyValue(1.0);
769   }
770   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
771     return C->isAllOnesValue();
772   }
773   return false;
774 }
775
776 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
777   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
778     return CFP->getValueAPF().isZero();
779   }
780   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
781     return C->isNullValue();
782   }
783   return false;
784 }
785
786 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
787                                                   const TargetRegisterClass *RC,
788                                                    unsigned Reg, EVT VT) const {
789   MachineFunction &MF = DAG.getMachineFunction();
790   MachineRegisterInfo &MRI = MF.getRegInfo();
791   unsigned VirtualRegister;
792   if (!MRI.isLiveIn(Reg)) {
793     VirtualRegister = MRI.createVirtualRegister(RC);
794     MRI.addLiveIn(Reg, VirtualRegister);
795   } else {
796     VirtualRegister = MRI.getLiveInVirtReg(Reg);
797   }
798   return DAG.getRegister(VirtualRegister, VT);
799 }
800
801 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
802
803 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
804   switch (Opcode) {
805   default: return 0;
806   // AMDIL DAG nodes
807   NODE_NAME_CASE(CALL);
808   NODE_NAME_CASE(UMUL);
809   NODE_NAME_CASE(DIV_INF);
810   NODE_NAME_CASE(RET_FLAG);
811   NODE_NAME_CASE(BRANCH_COND);
812
813   // AMDGPU DAG nodes
814   NODE_NAME_CASE(DWORDADDR)
815   NODE_NAME_CASE(FRACT)
816   NODE_NAME_CASE(FMAX)
817   NODE_NAME_CASE(SMAX)
818   NODE_NAME_CASE(UMAX)
819   NODE_NAME_CASE(FMIN)
820   NODE_NAME_CASE(SMIN)
821   NODE_NAME_CASE(UMIN)
822   NODE_NAME_CASE(URECIP)
823   NODE_NAME_CASE(EXPORT)
824   NODE_NAME_CASE(CONST_ADDRESS)
825   NODE_NAME_CASE(REGISTER_LOAD)
826   NODE_NAME_CASE(REGISTER_STORE)
827   NODE_NAME_CASE(LOAD_CONSTANT)
828   NODE_NAME_CASE(LOAD_INPUT)
829   NODE_NAME_CASE(SAMPLE)
830   NODE_NAME_CASE(SAMPLEB)
831   NODE_NAME_CASE(SAMPLED)
832   NODE_NAME_CASE(SAMPLEL)
833   NODE_NAME_CASE(STORE_MSKOR)
834   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
835   }
836 }