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