R600: Handle fcopysign
[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/Analysis/ValueTracking.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33
34 using namespace llvm;
35
36 namespace {
37
38 /// Diagnostic information for unimplemented or unsupported feature reporting.
39 class DiagnosticInfoUnsupported : public DiagnosticInfo {
40 private:
41   const Twine &Description;
42   const Function &Fn;
43
44   static int KindID;
45
46   static int getKindID() {
47     if (KindID == 0)
48       KindID = llvm::getNextAvailablePluginDiagnosticKind();
49     return KindID;
50   }
51
52 public:
53   DiagnosticInfoUnsupported(const Function &Fn, const Twine &Desc,
54                           DiagnosticSeverity Severity = DS_Error)
55     : DiagnosticInfo(getKindID(), Severity),
56       Description(Desc),
57       Fn(Fn) { }
58
59   const Function &getFunction() const { return Fn; }
60   const Twine &getDescription() const { return Description; }
61
62   void print(DiagnosticPrinter &DP) const override {
63     DP << "unsupported " << getDescription() << " in " << Fn.getName();
64   }
65
66   static bool classof(const DiagnosticInfo *DI) {
67     return DI->getKind() == getKindID();
68   }
69 };
70
71 int DiagnosticInfoUnsupported::KindID = 0;
72 }
73
74
75 static bool allocateStack(unsigned ValNo, MVT ValVT, MVT LocVT,
76                       CCValAssign::LocInfo LocInfo,
77                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
78   unsigned Offset = State.AllocateStack(ValVT.getStoreSize(),
79                                         ArgFlags.getOrigAlign());
80   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
81
82   return true;
83 }
84
85 #include "AMDGPUGenCallingConv.inc"
86
87 AMDGPUTargetLowering::AMDGPUTargetLowering(TargetMachine &TM) :
88   TargetLowering(TM, new TargetLoweringObjectFileELF()) {
89
90   Subtarget = &TM.getSubtarget<AMDGPUSubtarget>();
91
92   // Initialize target lowering borrowed from AMDIL
93   InitAMDILLowering();
94
95   // We need to custom lower some of the intrinsics
96   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
97
98   // Library functions.  These default to Expand, but we have instructions
99   // for them.
100   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
101   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
102   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
103   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
104   setOperationAction(ISD::FABS,   MVT::f32, Legal);
105   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
106   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
107   setOperationAction(ISD::FROUND, MVT::f32, Legal);
108   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
109
110   // The hardware supports ROTR, but not ROTL
111   setOperationAction(ISD::ROTL, MVT::i32, Expand);
112
113   // Lower floating point store/load to integer store/load to reduce the number
114   // of patterns in tablegen.
115   setOperationAction(ISD::STORE, MVT::f32, Promote);
116   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
117
118   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
119   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
120
121   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
122   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
123
124   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
125   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
126
127   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
128   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
129
130   setOperationAction(ISD::STORE, MVT::f64, Promote);
131   AddPromotedToType(ISD::STORE, MVT::f64, MVT::i64);
132
133   setOperationAction(ISD::STORE, MVT::v2f64, Promote);
134   AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v2i64);
135
136   // Custom lowering of vector stores is required for local address space
137   // stores.
138   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
139   // XXX: Native v2i32 local address space stores are possible, but not
140   // currently implemented.
141   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
142
143   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
144   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
145   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Custom);
146
147   // XXX: This can be change to Custom, once ExpandVectorStores can
148   // handle 64-bit stores.
149   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
150
151   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
152   setTruncStoreAction(MVT::i64, MVT::i8, Expand);
153   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
154   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
155   setTruncStoreAction(MVT::v4i64, MVT::v4i1, Expand);
156
157
158   setOperationAction(ISD::LOAD, MVT::f32, Promote);
159   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
160
161   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
162   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
163
164   setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
165   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
166
167   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
168   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
169
170   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
171   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
172
173   setOperationAction(ISD::LOAD, MVT::f64, Promote);
174   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::i64);
175
176   setOperationAction(ISD::LOAD, MVT::v2f64, Promote);
177   AddPromotedToType(ISD::LOAD, MVT::v2f64, MVT::v2i64);
178
179   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
180   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
181   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
182   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
183   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
184   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
185   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
186   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
187   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
188   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
189
190   setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Expand);
191   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Expand);
192   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i8, Expand);
193   setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Expand);
194   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Expand);
195   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i8, Expand);
196   setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Expand);
197   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Expand);
198   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i16, Expand);
199   setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Expand);
200   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Expand);
201   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, Expand);
202
203   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
204
205   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
206
207   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
208
209   setOperationAction(ISD::MUL, MVT::i64, Expand);
210   setOperationAction(ISD::SUB, MVT::i64, Expand);
211
212   setOperationAction(ISD::UDIV, MVT::i32, Expand);
213   setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
214   setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
215   setOperationAction(ISD::UREM, MVT::i32, Expand);
216
217   if (!Subtarget->hasBFI()) {
218     // fcopysign can be done in a single instruction with BFI.
219     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
220     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
221   }
222
223   static const MVT::SimpleValueType IntTypes[] = {
224     MVT::v2i32, MVT::v4i32
225   };
226
227   for (MVT VT : IntTypes) {
228     //Expand the following operations for the current type by default
229     setOperationAction(ISD::ADD,  VT, Expand);
230     setOperationAction(ISD::AND,  VT, Expand);
231     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
232     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
233     setOperationAction(ISD::MUL,  VT, Expand);
234     setOperationAction(ISD::OR,   VT, Expand);
235     setOperationAction(ISD::SHL,  VT, Expand);
236     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
237     setOperationAction(ISD::SRL,  VT, Expand);
238     setOperationAction(ISD::SRA,  VT, Expand);
239     setOperationAction(ISD::SUB,  VT, Expand);
240     setOperationAction(ISD::UDIV, VT, Expand);
241     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
242     setOperationAction(ISD::UREM, VT, Expand);
243     setOperationAction(ISD::SELECT, VT, Expand);
244     setOperationAction(ISD::VSELECT, VT, Expand);
245     setOperationAction(ISD::XOR,  VT, Expand);
246     setOperationAction(ISD::BSWAP, VT, Expand);
247   }
248
249   static const MVT::SimpleValueType FloatTypes[] = {
250     MVT::v2f32, MVT::v4f32
251   };
252
253   for (MVT VT : FloatTypes) {
254     setOperationAction(ISD::FABS, VT, Expand);
255     setOperationAction(ISD::FADD, VT, Expand);
256     setOperationAction(ISD::FCOS, VT, Expand);
257     setOperationAction(ISD::FDIV, VT, Expand);
258     setOperationAction(ISD::FPOW, VT, Expand);
259     setOperationAction(ISD::FFLOOR, VT, Expand);
260     setOperationAction(ISD::FTRUNC, VT, Expand);
261     setOperationAction(ISD::FMUL, VT, Expand);
262     setOperationAction(ISD::FRINT, VT, Expand);
263     setOperationAction(ISD::FSQRT, VT, Expand);
264     setOperationAction(ISD::FSIN, VT, Expand);
265     setOperationAction(ISD::FSUB, VT, Expand);
266     setOperationAction(ISD::FNEG, VT, Expand);
267     setOperationAction(ISD::SELECT, VT, Expand);
268     setOperationAction(ISD::VSELECT, VT, Expand);
269     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
270   }
271
272   setTargetDAGCombine(ISD::MUL);
273   setTargetDAGCombine(ISD::SELECT_CC);
274 }
275
276 //===----------------------------------------------------------------------===//
277 // Target Information
278 //===----------------------------------------------------------------------===//
279
280 MVT AMDGPUTargetLowering::getVectorIdxTy() const {
281   return MVT::i32;
282 }
283
284 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
285                                                    EVT CastTy) const {
286   if (LoadTy.getSizeInBits() != CastTy.getSizeInBits())
287     return true;
288
289   unsigned LScalarSize = LoadTy.getScalarType().getSizeInBits();
290   unsigned CastScalarSize = CastTy.getScalarType().getSizeInBits();
291
292   return ((LScalarSize <= CastScalarSize) ||
293           (CastScalarSize >= 32) ||
294           (LScalarSize < 32));
295 }
296
297 //===---------------------------------------------------------------------===//
298 // Target Properties
299 //===---------------------------------------------------------------------===//
300
301 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
302   assert(VT.isFloatingPoint());
303   return VT == MVT::f32;
304 }
305
306 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
307   assert(VT.isFloatingPoint());
308   return VT == MVT::f32;
309 }
310
311 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
312   // Truncate is just accessing a subregister.
313   return Dest.bitsLT(Source) && (Dest.getSizeInBits() % 32 == 0);
314 }
315
316 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
317   // Truncate is just accessing a subregister.
318   return Dest->getPrimitiveSizeInBits() < Source->getPrimitiveSizeInBits() &&
319          (Dest->getPrimitiveSizeInBits() % 32 == 0);
320 }
321
322 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
323   const DataLayout *DL = getDataLayout();
324   unsigned SrcSize = DL->getTypeSizeInBits(Src->getScalarType());
325   unsigned DestSize = DL->getTypeSizeInBits(Dest->getScalarType());
326
327   return SrcSize == 32 && DestSize == 64;
328 }
329
330 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
331   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
332   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
333   // this will enable reducing 64-bit operations the 32-bit, which is always
334   // good.
335   return Src == MVT::i32 && Dest == MVT::i64;
336 }
337
338 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
339   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
340   // limited number of native 64-bit operations. Shrinking an operation to fit
341   // in a single 32-bit register should always be helpful. As currently used,
342   // this is much less general than the name suggests, and is only used in
343   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
344   // not profitable, and may actually be harmful.
345   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
346 }
347
348 //===---------------------------------------------------------------------===//
349 // TargetLowering Callbacks
350 //===---------------------------------------------------------------------===//
351
352 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
353                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
354
355   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
356 }
357
358 SDValue AMDGPUTargetLowering::LowerReturn(
359                                      SDValue Chain,
360                                      CallingConv::ID CallConv,
361                                      bool isVarArg,
362                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
363                                      const SmallVectorImpl<SDValue> &OutVals,
364                                      SDLoc DL, SelectionDAG &DAG) const {
365   return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, Chain);
366 }
367
368 //===---------------------------------------------------------------------===//
369 // Target specific lowering
370 //===---------------------------------------------------------------------===//
371
372 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
373                                         SmallVectorImpl<SDValue> &InVals) const {
374   SDValue Callee = CLI.Callee;
375   SelectionDAG &DAG = CLI.DAG;
376
377   const Function &Fn = *DAG.getMachineFunction().getFunction();
378
379   StringRef FuncName("<unknown>");
380
381   if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
382     FuncName = G->getSymbol();
383   else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
384     FuncName = G->getGlobal()->getName();
385
386   DiagnosticInfoUnsupported NoCalls(Fn, "call to function " + FuncName);
387   DAG.getContext()->diagnose(NoCalls);
388   return SDValue();
389 }
390
391 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG)
392     const {
393   switch (Op.getOpcode()) {
394   default:
395     Op.getNode()->dump();
396     llvm_unreachable("Custom lowering code for this"
397                      "instruction is not implemented yet!");
398     break;
399   // AMDIL DAG lowering
400   case ISD::SDIV: return LowerSDIV(Op, DAG);
401   case ISD::SREM: return LowerSREM(Op, DAG);
402   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
403   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
404   // AMDGPU DAG lowering
405   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
406   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
407   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
408   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
409   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
410   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
411   }
412   return Op;
413 }
414
415 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
416                                               SmallVectorImpl<SDValue> &Results,
417                                               SelectionDAG &DAG) const {
418   switch (N->getOpcode()) {
419   case ISD::SIGN_EXTEND_INREG:
420     // Different parts of legalization seem to interpret which type of
421     // sign_extend_inreg is the one to check for custom lowering. The extended
422     // from type is what really matters, but some places check for custom
423     // lowering of the result type. This results in trying to use
424     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
425     // nothing here and let the illegal result integer be handled normally.
426     return;
427   case ISD::UDIV: {
428     SDValue Op = SDValue(N, 0);
429     SDLoc DL(Op);
430     EVT VT = Op.getValueType();
431     SDValue UDIVREM = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT),
432       N->getOperand(0), N->getOperand(1));
433     Results.push_back(UDIVREM);
434     break;
435   }
436   case ISD::UREM: {
437     SDValue Op = SDValue(N, 0);
438     SDLoc DL(Op);
439     EVT VT = Op.getValueType();
440     SDValue UDIVREM = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT),
441       N->getOperand(0), N->getOperand(1));
442     Results.push_back(UDIVREM.getValue(1));
443     break;
444   }
445   case ISD::UDIVREM: {
446     SDValue Op = SDValue(N, 0);
447     SDLoc DL(Op);
448     EVT VT = Op.getValueType();
449     EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
450
451     SDValue one = DAG.getConstant(1, HalfVT);
452     SDValue zero = DAG.getConstant(0, HalfVT);
453
454     //HiLo split
455     SDValue LHS = N->getOperand(0);
456     SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, zero);
457     SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, one);
458
459     SDValue RHS = N->getOperand(1);
460     SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, zero);
461     SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, one);
462
463     // Get Speculative values
464     SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
465     SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
466
467     SDValue REM_Hi = zero;
468     SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, zero, REM_Part, LHS_Hi, ISD::SETEQ);
469
470     SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, zero, DIV_Part, zero, ISD::SETEQ);
471     SDValue DIV_Lo = zero;
472
473     const unsigned halfBitWidth = HalfVT.getSizeInBits();
474
475     for (unsigned i = 0; i < halfBitWidth; ++i) {
476       SDValue POS = DAG.getConstant(halfBitWidth - i - 1, HalfVT);
477       // Get Value of high bit
478       SDValue HBit;
479       if (halfBitWidth == 32 && Subtarget->hasBFE()) {
480         HBit = DAG.getNode(AMDGPUISD::BFE_U32, DL, HalfVT, LHS_Lo, POS, one);
481       } else {
482         HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
483         HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, one);
484       }
485
486       SDValue Carry = DAG.getNode(ISD::SRL, DL, HalfVT, REM_Lo,
487         DAG.getConstant(halfBitWidth - 1, HalfVT));
488       REM_Hi = DAG.getNode(ISD::SHL, DL, HalfVT, REM_Hi, one);
489       REM_Hi = DAG.getNode(ISD::OR, DL, HalfVT, REM_Hi, Carry);
490
491       REM_Lo = DAG.getNode(ISD::SHL, DL, HalfVT, REM_Lo, one);
492       REM_Lo = DAG.getNode(ISD::OR, DL, HalfVT, REM_Lo, HBit);
493
494
495       SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, REM_Lo, REM_Hi);
496
497       SDValue BIT = DAG.getConstant(1 << (halfBitWidth - i - 1), HalfVT);
498       SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, zero, ISD::SETGE);
499
500       DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
501
502       // Update REM
503
504       SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
505
506       REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETGE);
507       REM_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, REM, zero);
508       REM_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, REM, one);
509     }
510
511     SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, REM_Lo, REM_Hi);
512     SDValue DIV = DAG.getNode(ISD::BUILD_PAIR, DL, VT, DIV_Lo, DIV_Hi);
513     Results.push_back(DIV);
514     Results.push_back(REM);
515     break;
516   }
517   default:
518     return;
519   }
520 }
521
522 // FIXME: This implements accesses to initialized globals in the constant
523 // address space by copying them to private and accessing that. It does not
524 // properly handle illegal types or vectors. The private vector loads are not
525 // scalarized, and the illegal scalars hit an assertion. This technique will not
526 // work well with large initializers, and this should eventually be
527 // removed. Initialized globals should be placed into a data section that the
528 // runtime will load into a buffer before the kernel is executed. Uses of the
529 // global need to be replaced with a pointer loaded from an implicit kernel
530 // argument into this buffer holding the copy of the data, which will remove the
531 // need for any of this.
532 SDValue AMDGPUTargetLowering::LowerConstantInitializer(const Constant* Init,
533                                                        const GlobalValue *GV,
534                                                        const SDValue &InitPtr,
535                                                        SDValue Chain,
536                                                        SelectionDAG &DAG) const {
537   const DataLayout *TD = getTargetMachine().getDataLayout();
538   SDLoc DL(InitPtr);
539   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Init)) {
540     EVT VT = EVT::getEVT(CI->getType());
541     PointerType *PtrTy = PointerType::get(CI->getType(), 0);
542     return DAG.getStore(Chain, DL,  DAG.getConstant(*CI, VT), InitPtr,
543                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
544                  TD->getPrefTypeAlignment(CI->getType()));
545   }
546
547   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Init)) {
548     EVT VT = EVT::getEVT(CFP->getType());
549     PointerType *PtrTy = PointerType::get(CFP->getType(), 0);
550     return DAG.getStore(Chain, DL, DAG.getConstantFP(*CFP, VT), InitPtr,
551                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
552                  TD->getPrefTypeAlignment(CFP->getType()));
553   }
554
555   Type *InitTy = Init->getType();
556   if (StructType *ST = dyn_cast<StructType>(InitTy)) {
557     const StructLayout *SL = TD->getStructLayout(ST);
558
559     EVT PtrVT = InitPtr.getValueType();
560     SmallVector<SDValue, 8> Chains;
561
562     for (unsigned I = 0, N = ST->getNumElements(); I != N; ++I) {
563       SDValue Offset = DAG.getConstant(SL->getElementOffset(I), PtrVT);
564       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
565
566       Constant *Elt = Init->getAggregateElement(I);
567       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
568     }
569
570     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
571   }
572
573   if (SequentialType *SeqTy = dyn_cast<SequentialType>(InitTy)) {
574     EVT PtrVT = InitPtr.getValueType();
575
576     unsigned NumElements;
577     if (ArrayType *AT = dyn_cast<ArrayType>(SeqTy))
578       NumElements = AT->getNumElements();
579     else if (VectorType *VT = dyn_cast<VectorType>(SeqTy))
580       NumElements = VT->getNumElements();
581     else
582       llvm_unreachable("Unexpected type");
583
584     unsigned EltSize = TD->getTypeAllocSize(SeqTy->getElementType());
585     SmallVector<SDValue, 8> Chains;
586     for (unsigned i = 0; i < NumElements; ++i) {
587       SDValue Offset = DAG.getConstant(i * EltSize, PtrVT);
588       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
589
590       Constant *Elt = Init->getAggregateElement(i);
591       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
592     }
593
594     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
595   }
596
597   Init->dump();
598   llvm_unreachable("Unhandled constant initializer");
599 }
600
601 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
602                                                  SDValue Op,
603                                                  SelectionDAG &DAG) const {
604
605   const DataLayout *TD = getTargetMachine().getDataLayout();
606   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
607   const GlobalValue *GV = G->getGlobal();
608
609   switch (G->getAddressSpace()) {
610   default: llvm_unreachable("Global Address lowering not implemented for this "
611                             "address space");
612   case AMDGPUAS::LOCAL_ADDRESS: {
613     // XXX: What does the value of G->getOffset() mean?
614     assert(G->getOffset() == 0 &&
615          "Do not know what to do with an non-zero offset");
616
617     unsigned Offset;
618     if (MFI->LocalMemoryObjects.count(GV) == 0) {
619       uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
620       Offset = MFI->LDSSize;
621       MFI->LocalMemoryObjects[GV] = Offset;
622       // XXX: Account for alignment?
623       MFI->LDSSize += Size;
624     } else {
625       Offset = MFI->LocalMemoryObjects[GV];
626     }
627
628     return DAG.getConstant(Offset, getPointerTy(G->getAddressSpace()));
629   }
630   case AMDGPUAS::CONSTANT_ADDRESS: {
631     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
632     Type *EltType = GV->getType()->getElementType();
633     unsigned Size = TD->getTypeAllocSize(EltType);
634     unsigned Alignment = TD->getPrefTypeAlignment(EltType);
635
636     const GlobalVariable *Var = cast<GlobalVariable>(GV);
637     const Constant *Init = Var->getInitializer();
638     int FI = FrameInfo->CreateStackObject(Size, Alignment, false);
639     SDValue InitPtr = DAG.getFrameIndex(FI,
640         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
641     SmallVector<SDNode*, 8> WorkList;
642
643     for (SDNode::use_iterator I = DAG.getEntryNode()->use_begin(),
644                               E = DAG.getEntryNode()->use_end(); I != E; ++I) {
645       if (I->getOpcode() != AMDGPUISD::REGISTER_LOAD && I->getOpcode() != ISD::LOAD)
646         continue;
647       WorkList.push_back(*I);
648     }
649     SDValue Chain = LowerConstantInitializer(Init, GV, InitPtr, DAG.getEntryNode(), DAG);
650     for (SmallVector<SDNode*, 8>::iterator I = WorkList.begin(),
651                                            E = WorkList.end(); I != E; ++I) {
652       SmallVector<SDValue, 8> Ops;
653       Ops.push_back(Chain);
654       for (unsigned i = 1; i < (*I)->getNumOperands(); ++i) {
655         Ops.push_back((*I)->getOperand(i));
656       }
657       DAG.UpdateNodeOperands(*I, Ops);
658     }
659     return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op),
660         getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
661   }
662   }
663 }
664
665 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
666                                                   SelectionDAG &DAG) const {
667   SmallVector<SDValue, 8> Args;
668   SDValue A = Op.getOperand(0);
669   SDValue B = Op.getOperand(1);
670
671   DAG.ExtractVectorElements(A, Args);
672   DAG.ExtractVectorElements(B, Args);
673
674   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
675 }
676
677 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
678                                                      SelectionDAG &DAG) const {
679
680   SmallVector<SDValue, 8> Args;
681   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
682   EVT VT = Op.getValueType();
683   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
684                             VT.getVectorNumElements());
685
686   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
687 }
688
689 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
690                                               SelectionDAG &DAG) const {
691
692   MachineFunction &MF = DAG.getMachineFunction();
693   const AMDGPUFrameLowering *TFL =
694    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
695
696   FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op);
697   assert(FIN);
698
699   unsigned FrameIndex = FIN->getIndex();
700   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
701   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF),
702                          Op.getValueType());
703 }
704
705 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
706     SelectionDAG &DAG) const {
707   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
708   SDLoc DL(Op);
709   EVT VT = Op.getValueType();
710
711   switch (IntrinsicID) {
712     default: return Op;
713     case AMDGPUIntrinsic::AMDIL_abs:
714       return LowerIntrinsicIABS(Op, DAG);
715     case AMDGPUIntrinsic::AMDIL_exp:
716       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
717     case AMDGPUIntrinsic::AMDGPU_lrp:
718       return LowerIntrinsicLRP(Op, DAG);
719     case AMDGPUIntrinsic::AMDIL_fraction:
720       return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
721     case AMDGPUIntrinsic::AMDIL_max:
722       return DAG.getNode(AMDGPUISD::FMAX, DL, VT, Op.getOperand(1),
723                                                   Op.getOperand(2));
724     case AMDGPUIntrinsic::AMDGPU_imax:
725       return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Op.getOperand(1),
726                                                   Op.getOperand(2));
727     case AMDGPUIntrinsic::AMDGPU_umax:
728       return DAG.getNode(AMDGPUISD::UMAX, DL, VT, Op.getOperand(1),
729                                                   Op.getOperand(2));
730     case AMDGPUIntrinsic::AMDIL_min:
731       return DAG.getNode(AMDGPUISD::FMIN, DL, VT, Op.getOperand(1),
732                                                   Op.getOperand(2));
733     case AMDGPUIntrinsic::AMDGPU_imin:
734       return DAG.getNode(AMDGPUISD::SMIN, DL, VT, Op.getOperand(1),
735                                                   Op.getOperand(2));
736     case AMDGPUIntrinsic::AMDGPU_umin:
737       return DAG.getNode(AMDGPUISD::UMIN, DL, VT, Op.getOperand(1),
738                                                   Op.getOperand(2));
739
740     case AMDGPUIntrinsic::AMDGPU_umul24:
741       return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT,
742                          Op.getOperand(1), Op.getOperand(2));
743
744     case AMDGPUIntrinsic::AMDGPU_imul24:
745       return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT,
746                          Op.getOperand(1), Op.getOperand(2));
747
748     case AMDGPUIntrinsic::AMDGPU_umad24:
749       return DAG.getNode(AMDGPUISD::MAD_U24, DL, VT,
750                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
751
752     case AMDGPUIntrinsic::AMDGPU_imad24:
753       return DAG.getNode(AMDGPUISD::MAD_I24, DL, VT,
754                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
755
756     case AMDGPUIntrinsic::AMDGPU_bfe_i32:
757       return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
758                          Op.getOperand(1),
759                          Op.getOperand(2),
760                          Op.getOperand(3));
761
762     case AMDGPUIntrinsic::AMDGPU_bfe_u32:
763       return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
764                          Op.getOperand(1),
765                          Op.getOperand(2),
766                          Op.getOperand(3));
767
768     case AMDGPUIntrinsic::AMDGPU_bfi:
769       return DAG.getNode(AMDGPUISD::BFI, DL, VT,
770                          Op.getOperand(1),
771                          Op.getOperand(2),
772                          Op.getOperand(3));
773
774     case AMDGPUIntrinsic::AMDGPU_bfm:
775       return DAG.getNode(AMDGPUISD::BFM, DL, VT,
776                          Op.getOperand(1),
777                          Op.getOperand(2));
778
779     case AMDGPUIntrinsic::AMDIL_round_nearest:
780       return DAG.getNode(ISD::FRINT, DL, VT, Op.getOperand(1));
781   }
782 }
783
784 ///IABS(a) = SMAX(sub(0, a), a)
785 SDValue AMDGPUTargetLowering::LowerIntrinsicIABS(SDValue Op,
786                                                  SelectionDAG &DAG) const {
787   SDLoc DL(Op);
788   EVT VT = Op.getValueType();
789   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
790                                               Op.getOperand(1));
791
792   return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Neg, Op.getOperand(1));
793 }
794
795 /// Linear Interpolation
796 /// LRP(a, b, c) = muladd(a,  b, (1 - a) * c)
797 SDValue AMDGPUTargetLowering::LowerIntrinsicLRP(SDValue Op,
798                                                 SelectionDAG &DAG) const {
799   SDLoc DL(Op);
800   EVT VT = Op.getValueType();
801   SDValue OneSubA = DAG.getNode(ISD::FSUB, DL, VT,
802                                 DAG.getConstantFP(1.0f, MVT::f32),
803                                 Op.getOperand(1));
804   SDValue OneSubAC = DAG.getNode(ISD::FMUL, DL, VT, OneSubA,
805                                                     Op.getOperand(3));
806   return DAG.getNode(ISD::FADD, DL, VT,
807       DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), Op.getOperand(2)),
808       OneSubAC);
809 }
810
811 /// \brief Generate Min/Max node
812 SDValue AMDGPUTargetLowering::CombineMinMax(SDNode *N,
813                                             SelectionDAG &DAG) const {
814   SDLoc DL(N);
815   EVT VT = N->getValueType(0);
816
817   SDValue LHS = N->getOperand(0);
818   SDValue RHS = N->getOperand(1);
819   SDValue True = N->getOperand(2);
820   SDValue False = N->getOperand(3);
821   SDValue CC = N->getOperand(4);
822
823   if (VT != MVT::f32 ||
824       !((LHS == True && RHS == False) || (LHS == False && RHS == True))) {
825     return SDValue();
826   }
827
828   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
829   switch (CCOpcode) {
830   case ISD::SETOEQ:
831   case ISD::SETONE:
832   case ISD::SETUNE:
833   case ISD::SETNE:
834   case ISD::SETUEQ:
835   case ISD::SETEQ:
836   case ISD::SETFALSE:
837   case ISD::SETFALSE2:
838   case ISD::SETTRUE:
839   case ISD::SETTRUE2:
840   case ISD::SETUO:
841   case ISD::SETO:
842     llvm_unreachable("Operation should already be optimised!");
843   case ISD::SETULE:
844   case ISD::SETULT:
845   case ISD::SETOLE:
846   case ISD::SETOLT:
847   case ISD::SETLE:
848   case ISD::SETLT: {
849     unsigned Opc = (LHS == True) ? AMDGPUISD::FMIN : AMDGPUISD::FMAX;
850     return DAG.getNode(Opc, DL, VT, LHS, RHS);
851   }
852   case ISD::SETGT:
853   case ISD::SETGE:
854   case ISD::SETUGE:
855   case ISD::SETOGE:
856   case ISD::SETUGT:
857   case ISD::SETOGT: {
858     unsigned Opc = (LHS == True) ? AMDGPUISD::FMAX : AMDGPUISD::FMIN;
859     return DAG.getNode(Opc, DL, VT, LHS, RHS);
860   }
861   case ISD::SETCC_INVALID:
862     llvm_unreachable("Invalid setcc condcode!");
863   }
864   return SDValue();
865 }
866
867 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue &Op,
868                                               SelectionDAG &DAG) const {
869   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
870   EVT MemEltVT = Load->getMemoryVT().getVectorElementType();
871   EVT EltVT = Op.getValueType().getVectorElementType();
872   EVT PtrVT = Load->getBasePtr().getValueType();
873   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
874   SmallVector<SDValue, 8> Loads;
875   SDLoc SL(Op);
876
877   for (unsigned i = 0, e = NumElts; i != e; ++i) {
878     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
879                     DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8), PtrVT));
880     Loads.push_back(DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
881                         Load->getChain(), Ptr,
882                         MachinePointerInfo(Load->getMemOperand()->getValue()),
883                         MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
884                         Load->getAlignment()));
885   }
886   return DAG.getNode(ISD::BUILD_VECTOR, SL, Op.getValueType(), Loads);
887 }
888
889 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
890                                                SelectionDAG &DAG) const {
891   StoreSDNode *Store = dyn_cast<StoreSDNode>(Op);
892   EVT MemVT = Store->getMemoryVT();
893   unsigned MemBits = MemVT.getSizeInBits();
894
895   // Byte stores are really expensive, so if possible, try to pack 32-bit vector
896   // truncating store into an i32 store.
897   // XXX: We could also handle optimize other vector bitwidths.
898   if (!MemVT.isVector() || MemBits > 32) {
899     return SDValue();
900   }
901
902   SDLoc DL(Op);
903   SDValue Value = Store->getValue();
904   EVT VT = Value.getValueType();
905   EVT ElemVT = VT.getVectorElementType();
906   SDValue Ptr = Store->getBasePtr();
907   EVT MemEltVT = MemVT.getVectorElementType();
908   unsigned MemEltBits = MemEltVT.getSizeInBits();
909   unsigned MemNumElements = MemVT.getVectorNumElements();
910   unsigned PackedSize = MemVT.getStoreSizeInBits();
911   SDValue Mask = DAG.getConstant((1 << MemEltBits) - 1, MVT::i32);
912
913   assert(Value.getValueType().getScalarSizeInBits() >= 32);
914
915   SDValue PackedValue;
916   for (unsigned i = 0; i < MemNumElements; ++i) {
917     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
918                               DAG.getConstant(i, MVT::i32));
919     Elt = DAG.getZExtOrTrunc(Elt, DL, MVT::i32);
920     Elt = DAG.getNode(ISD::AND, DL, MVT::i32, Elt, Mask); // getZeroExtendInReg
921
922     SDValue Shift = DAG.getConstant(MemEltBits * i, MVT::i32);
923     Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt, Shift);
924
925     if (i == 0) {
926       PackedValue = Elt;
927     } else {
928       PackedValue = DAG.getNode(ISD::OR, DL, MVT::i32, PackedValue, Elt);
929     }
930   }
931
932   if (PackedSize < 32) {
933     EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), PackedSize);
934     return DAG.getTruncStore(Store->getChain(), DL, PackedValue, Ptr,
935                              Store->getMemOperand()->getPointerInfo(),
936                              PackedVT,
937                              Store->isNonTemporal(), Store->isVolatile(),
938                              Store->getAlignment());
939   }
940
941   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
942                       Store->getMemOperand()->getPointerInfo(),
943                       Store->isVolatile(),  Store->isNonTemporal(),
944                       Store->getAlignment());
945 }
946
947 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
948                                             SelectionDAG &DAG) const {
949   StoreSDNode *Store = cast<StoreSDNode>(Op);
950   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
951   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
952   EVT PtrVT = Store->getBasePtr().getValueType();
953   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
954   SDLoc SL(Op);
955
956   SmallVector<SDValue, 8> Chains;
957
958   for (unsigned i = 0, e = NumElts; i != e; ++i) {
959     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
960                               Store->getValue(), DAG.getConstant(i, MVT::i32));
961     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT,
962                               Store->getBasePtr(),
963                             DAG.getConstant(i * (MemEltVT.getSizeInBits() / 8),
964                                             PtrVT));
965     Chains.push_back(DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
966                          MachinePointerInfo(Store->getMemOperand()->getValue()),
967                          MemEltVT, Store->isVolatile(), Store->isNonTemporal(),
968                          Store->getAlignment()));
969   }
970   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains);
971 }
972
973 SDValue AMDGPUTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
974   SDLoc DL(Op);
975   LoadSDNode *Load = cast<LoadSDNode>(Op);
976   ISD::LoadExtType ExtType = Load->getExtensionType();
977   EVT VT = Op.getValueType();
978   EVT MemVT = Load->getMemoryVT();
979
980   if (ExtType != ISD::NON_EXTLOAD && !VT.isVector() && VT.getSizeInBits() > 32) {
981     // We can do the extload to 32-bits, and then need to separately extend to
982     // 64-bits.
983
984     SDValue ExtLoad32 = DAG.getExtLoad(ExtType, DL, MVT::i32,
985                                        Load->getChain(),
986                                        Load->getBasePtr(),
987                                        MemVT,
988                                        Load->getMemOperand());
989     return DAG.getNode(ISD::getExtForLoadExtType(ExtType), DL, VT, ExtLoad32);
990   }
991
992   if (ExtType == ISD::NON_EXTLOAD && VT.getSizeInBits() < 32) {
993     assert(VT == MVT::i1 && "Only i1 non-extloads expected");
994     // FIXME: Copied from PPC
995     // First, load into 32 bits, then truncate to 1 bit.
996
997     SDValue Chain = Load->getChain();
998     SDValue BasePtr = Load->getBasePtr();
999     MachineMemOperand *MMO = Load->getMemOperand();
1000
1001     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
1002                                    BasePtr, MVT::i8, MMO);
1003     return DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1004   }
1005
1006   // Lower loads constant address space global variable loads
1007   if (Load->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
1008       isa<GlobalVariable>(
1009           GetUnderlyingObject(Load->getMemOperand()->getValue()))) {
1010
1011     SDValue Ptr = DAG.getZExtOrTrunc(Load->getBasePtr(), DL,
1012         getPointerTy(AMDGPUAS::PRIVATE_ADDRESS));
1013     Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr,
1014         DAG.getConstant(2, MVT::i32));
1015     return DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
1016                        Load->getChain(), Ptr,
1017                        DAG.getTargetConstant(0, MVT::i32), Op.getOperand(2));
1018   }
1019
1020   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS ||
1021       ExtType == ISD::NON_EXTLOAD || Load->getMemoryVT().bitsGE(MVT::i32))
1022     return SDValue();
1023
1024
1025   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
1026                             DAG.getConstant(2, MVT::i32));
1027   SDValue Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
1028                             Load->getChain(), Ptr,
1029                             DAG.getTargetConstant(0, MVT::i32),
1030                             Op.getOperand(2));
1031   SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32,
1032                                 Load->getBasePtr(),
1033                                 DAG.getConstant(0x3, MVT::i32));
1034   SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1035                                  DAG.getConstant(3, MVT::i32));
1036
1037   Ret = DAG.getNode(ISD::SRL, DL, MVT::i32, Ret, ShiftAmt);
1038
1039   EVT MemEltVT = MemVT.getScalarType();
1040   if (ExtType == ISD::SEXTLOAD) {
1041     SDValue MemEltVTNode = DAG.getValueType(MemEltVT);
1042     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, Ret, MemEltVTNode);
1043   }
1044
1045   return DAG.getZeroExtendInReg(Ret, DL, MemEltVT);
1046 }
1047
1048 SDValue AMDGPUTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1049   SDLoc DL(Op);
1050   SDValue Result = AMDGPUTargetLowering::MergeVectorStore(Op, DAG);
1051   if (Result.getNode()) {
1052     return Result;
1053   }
1054
1055   StoreSDNode *Store = cast<StoreSDNode>(Op);
1056   SDValue Chain = Store->getChain();
1057   if ((Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1058        Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
1059       Store->getValue().getValueType().isVector()) {
1060     return SplitVectorStore(Op, DAG);
1061   }
1062
1063   EVT MemVT = Store->getMemoryVT();
1064   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS &&
1065       MemVT.bitsLT(MVT::i32)) {
1066     unsigned Mask = 0;
1067     if (Store->getMemoryVT() == MVT::i8) {
1068       Mask = 0xff;
1069     } else if (Store->getMemoryVT() == MVT::i16) {
1070       Mask = 0xffff;
1071     }
1072     SDValue BasePtr = Store->getBasePtr();
1073     SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, BasePtr,
1074                               DAG.getConstant(2, MVT::i32));
1075     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
1076                               Chain, Ptr, DAG.getTargetConstant(0, MVT::i32));
1077
1078     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, BasePtr,
1079                                   DAG.getConstant(0x3, MVT::i32));
1080
1081     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1082                                    DAG.getConstant(3, MVT::i32));
1083
1084     SDValue SExtValue = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32,
1085                                     Store->getValue());
1086
1087     SDValue MaskedValue = DAG.getZeroExtendInReg(SExtValue, DL, MemVT);
1088
1089     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
1090                                        MaskedValue, ShiftAmt);
1091
1092     SDValue DstMask = DAG.getNode(ISD::SHL, DL, MVT::i32, DAG.getConstant(Mask, MVT::i32),
1093                                   ShiftAmt);
1094     DstMask = DAG.getNode(ISD::XOR, DL, MVT::i32, DstMask,
1095                           DAG.getConstant(0xffffffff, MVT::i32));
1096     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
1097
1098     SDValue Value = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
1099     return DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
1100                        Chain, Value, Ptr, DAG.getTargetConstant(0, MVT::i32));
1101   }
1102   return SDValue();
1103 }
1104
1105 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1106                                            SelectionDAG &DAG) const {
1107   SDLoc DL(Op);
1108   EVT VT = Op.getValueType();
1109
1110   SDValue Num = Op.getOperand(0);
1111   SDValue Den = Op.getOperand(1);
1112
1113   // RCP =  URECIP(Den) = 2^32 / Den + e
1114   // e is rounding error.
1115   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1116
1117   // RCP_LO = umulo(RCP, Den) */
1118   SDValue RCP_LO = DAG.getNode(ISD::UMULO, DL, VT, RCP, Den);
1119
1120   // RCP_HI = mulhu (RCP, Den) */
1121   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1122
1123   // NEG_RCP_LO = -RCP_LO
1124   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
1125                                                      RCP_LO);
1126
1127   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1128   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1129                                            NEG_RCP_LO, RCP_LO,
1130                                            ISD::SETEQ);
1131   // Calculate the rounding error from the URECIP instruction
1132   // E = mulhu(ABS_RCP_LO, RCP)
1133   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1134
1135   // RCP_A_E = RCP + E
1136   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1137
1138   // RCP_S_E = RCP - E
1139   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1140
1141   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1142   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1143                                      RCP_A_E, RCP_S_E,
1144                                      ISD::SETEQ);
1145   // Quotient = mulhu(Tmp0, Num)
1146   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1147
1148   // Num_S_Remainder = Quotient * Den
1149   SDValue Num_S_Remainder = DAG.getNode(ISD::UMULO, DL, VT, Quotient, Den);
1150
1151   // Remainder = Num - Num_S_Remainder
1152   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1153
1154   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1155   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1156                                                  DAG.getConstant(-1, VT),
1157                                                  DAG.getConstant(0, VT),
1158                                                  ISD::SETUGE);
1159   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1160   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1161                                                   Num_S_Remainder,
1162                                                   DAG.getConstant(-1, VT),
1163                                                   DAG.getConstant(0, VT),
1164                                                   ISD::SETUGE);
1165   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1166   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1167                                                Remainder_GE_Zero);
1168
1169   // Calculate Division result:
1170
1171   // Quotient_A_One = Quotient + 1
1172   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1173                                                          DAG.getConstant(1, VT));
1174
1175   // Quotient_S_One = Quotient - 1
1176   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1177                                                          DAG.getConstant(1, VT));
1178
1179   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1180   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1181                                      Quotient, Quotient_A_One, ISD::SETEQ);
1182
1183   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1184   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1185                             Quotient_S_One, Div, ISD::SETEQ);
1186
1187   // Calculate Rem result:
1188
1189   // Remainder_S_Den = Remainder - Den
1190   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1191
1192   // Remainder_A_Den = Remainder + Den
1193   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1194
1195   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1196   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1197                                     Remainder, Remainder_S_Den, ISD::SETEQ);
1198
1199   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1200   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1201                             Remainder_A_Den, Rem, ISD::SETEQ);
1202   SDValue Ops[2] = {
1203     Div,
1204     Rem
1205   };
1206   return DAG.getMergeValues(Ops, DL);
1207 }
1208
1209 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
1210                                                SelectionDAG &DAG) const {
1211   SDValue S0 = Op.getOperand(0);
1212   SDLoc DL(Op);
1213   if (Op.getValueType() != MVT::f32 || S0.getValueType() != MVT::i64)
1214     return SDValue();
1215
1216   // f32 uint_to_fp i64
1217   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
1218                            DAG.getConstant(0, MVT::i32));
1219   SDValue FloatLo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Lo);
1220   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
1221                            DAG.getConstant(1, MVT::i32));
1222   SDValue FloatHi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Hi);
1223   FloatHi = DAG.getNode(ISD::FMUL, DL, MVT::f32, FloatHi,
1224                         DAG.getConstantFP(4294967296.0f, MVT::f32)); // 2^32
1225   return DAG.getNode(ISD::FADD, DL, MVT::f32, FloatLo, FloatHi);
1226
1227 }
1228
1229 SDValue AMDGPUTargetLowering::ExpandSIGN_EXTEND_INREG(SDValue Op,
1230                                                       unsigned BitsDiff,
1231                                                       SelectionDAG &DAG) const {
1232   MVT VT = Op.getSimpleValueType();
1233   SDLoc DL(Op);
1234   SDValue Shift = DAG.getConstant(BitsDiff, VT);
1235   // Shift left by 'Shift' bits.
1236   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Op.getOperand(0), Shift);
1237   // Signed shift Right by 'Shift' bits.
1238   return DAG.getNode(ISD::SRA, DL, VT, Shl, Shift);
1239 }
1240
1241 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1242                                                      SelectionDAG &DAG) const {
1243   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1244   MVT VT = Op.getSimpleValueType();
1245   MVT ScalarVT = VT.getScalarType();
1246
1247   if (!VT.isVector())
1248     return SDValue();
1249
1250   SDValue Src = Op.getOperand(0);
1251   SDLoc DL(Op);
1252
1253   // TODO: Don't scalarize on Evergreen?
1254   unsigned NElts = VT.getVectorNumElements();
1255   SmallVector<SDValue, 8> Args;
1256   DAG.ExtractVectorElements(Src, Args, 0, NElts);
1257
1258   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
1259   for (unsigned I = 0; I < NElts; ++I)
1260     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
1261
1262   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args);
1263 }
1264
1265 //===----------------------------------------------------------------------===//
1266 // Custom DAG optimizations
1267 //===----------------------------------------------------------------------===//
1268
1269 static bool isU24(SDValue Op, SelectionDAG &DAG) {
1270   APInt KnownZero, KnownOne;
1271   EVT VT = Op.getValueType();
1272   DAG.computeKnownBits(Op, KnownZero, KnownOne);
1273
1274   return (VT.getSizeInBits() - KnownZero.countLeadingOnes()) <= 24;
1275 }
1276
1277 static bool isI24(SDValue Op, SelectionDAG &DAG) {
1278   EVT VT = Op.getValueType();
1279
1280   // In order for this to be a signed 24-bit value, bit 23, must
1281   // be a sign bit.
1282   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
1283                                      // as unsigned 24-bit values.
1284          (VT.getSizeInBits() - DAG.ComputeNumSignBits(Op)) < 24;
1285 }
1286
1287 static void simplifyI24(SDValue Op, TargetLowering::DAGCombinerInfo &DCI) {
1288
1289   SelectionDAG &DAG = DCI.DAG;
1290   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1291   EVT VT = Op.getValueType();
1292
1293   APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
1294   APInt KnownZero, KnownOne;
1295   TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
1296   if (TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
1297     DCI.CommitTargetLoweringOpt(TLO);
1298 }
1299
1300 template <typename IntTy>
1301 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0,
1302                                uint32_t Offset, uint32_t Width) {
1303   if (Width + Offset < 32) {
1304     IntTy Result = (Src0 << (32 - Offset - Width)) >> (32 - Width);
1305     return DAG.getConstant(Result, MVT::i32);
1306   }
1307
1308   return DAG.getConstant(Src0 >> Offset, MVT::i32);
1309 }
1310
1311 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
1312                                             DAGCombinerInfo &DCI) const {
1313   SelectionDAG &DAG = DCI.DAG;
1314   SDLoc DL(N);
1315
1316   switch(N->getOpcode()) {
1317     default: break;
1318     case ISD::MUL: {
1319       EVT VT = N->getValueType(0);
1320       SDValue N0 = N->getOperand(0);
1321       SDValue N1 = N->getOperand(1);
1322       SDValue Mul;
1323
1324       // FIXME: Add support for 24-bit multiply with 64-bit output on SI.
1325       if (VT.isVector() || VT.getSizeInBits() > 32)
1326         break;
1327
1328       if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
1329         N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
1330         N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
1331         Mul = DAG.getNode(AMDGPUISD::MUL_U24, DL, MVT::i32, N0, N1);
1332       } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
1333         N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
1334         N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
1335         Mul = DAG.getNode(AMDGPUISD::MUL_I24, DL, MVT::i32, N0, N1);
1336       } else {
1337         break;
1338       }
1339
1340       // We need to use sext even for MUL_U24, because MUL_U24 is used
1341       // for signed multiply of 8 and 16-bit types.
1342       SDValue Reg = DAG.getSExtOrTrunc(Mul, DL, VT);
1343
1344       return Reg;
1345     }
1346     case AMDGPUISD::MUL_I24:
1347     case AMDGPUISD::MUL_U24: {
1348       SDValue N0 = N->getOperand(0);
1349       SDValue N1 = N->getOperand(1);
1350       simplifyI24(N0, DCI);
1351       simplifyI24(N1, DCI);
1352       return SDValue();
1353     }
1354     case ISD::SELECT_CC: {
1355       return CombineMinMax(N, DAG);
1356     }
1357   case AMDGPUISD::BFE_I32:
1358   case AMDGPUISD::BFE_U32: {
1359     assert(!N->getValueType(0).isVector() &&
1360            "Vector handling of BFE not implemented");
1361     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
1362     if (!Width)
1363       break;
1364
1365     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
1366     if (WidthVal == 0)
1367       return DAG.getConstant(0, MVT::i32);
1368
1369     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
1370     if (!Offset)
1371       break;
1372
1373     SDValue BitsFrom = N->getOperand(0);
1374     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
1375
1376     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
1377
1378     if (OffsetVal == 0) {
1379       // This is already sign / zero extended, so try to fold away extra BFEs.
1380       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
1381
1382       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
1383       if (OpSignBits >= SignBits)
1384         return BitsFrom;
1385
1386       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
1387       if (Signed) {
1388         // This is a sign_extend_inreg. Replace it to take advantage of existing
1389         // DAG Combines. If not eliminated, we will match back to BFE during
1390         // selection.
1391
1392         // TODO: The sext_inreg of extended types ends, although we can could
1393         // handle them in a single BFE.
1394         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
1395                            DAG.getValueType(SmallVT));
1396       }
1397
1398       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
1399     }
1400
1401     if (ConstantSDNode *Val = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
1402       if (Signed) {
1403         return constantFoldBFE<int32_t>(DAG,
1404                                         Val->getSExtValue(),
1405                                         OffsetVal,
1406                                         WidthVal);
1407       }
1408
1409       return constantFoldBFE<uint32_t>(DAG,
1410                                        Val->getZExtValue(),
1411                                        OffsetVal,
1412                                        WidthVal);
1413     }
1414
1415     APInt Demanded = APInt::getBitsSet(32,
1416                                        OffsetVal,
1417                                        OffsetVal + WidthVal);
1418
1419     if ((OffsetVal + WidthVal) >= 32) {
1420       SDValue ShiftVal = DAG.getConstant(OffsetVal, MVT::i32);
1421       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1422                          BitsFrom, ShiftVal);
1423     }
1424
1425     APInt KnownZero, KnownOne;
1426     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1427                                           !DCI.isBeforeLegalizeOps());
1428     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1429     if (TLO.ShrinkDemandedConstant(BitsFrom, Demanded) ||
1430         TLI.SimplifyDemandedBits(BitsFrom, Demanded, KnownZero, KnownOne, TLO)) {
1431       DCI.CommitTargetLoweringOpt(TLO);
1432     }
1433
1434     break;
1435   }
1436   }
1437   return SDValue();
1438 }
1439
1440 //===----------------------------------------------------------------------===//
1441 // Helper functions
1442 //===----------------------------------------------------------------------===//
1443
1444 void AMDGPUTargetLowering::getOriginalFunctionArgs(
1445                                SelectionDAG &DAG,
1446                                const Function *F,
1447                                const SmallVectorImpl<ISD::InputArg> &Ins,
1448                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
1449
1450   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
1451     if (Ins[i].ArgVT == Ins[i].VT) {
1452       OrigIns.push_back(Ins[i]);
1453       continue;
1454     }
1455
1456     EVT VT;
1457     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
1458       // Vector has been split into scalars.
1459       VT = Ins[i].ArgVT.getVectorElementType();
1460     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
1461                Ins[i].ArgVT.getVectorElementType() !=
1462                Ins[i].VT.getVectorElementType()) {
1463       // Vector elements have been promoted
1464       VT = Ins[i].ArgVT;
1465     } else {
1466       // Vector has been spilt into smaller vectors.
1467       VT = Ins[i].VT;
1468     }
1469
1470     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
1471                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
1472     OrigIns.push_back(Arg);
1473   }
1474 }
1475
1476 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
1477   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1478     return CFP->isExactlyValue(1.0);
1479   }
1480   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1481     return C->isAllOnesValue();
1482   }
1483   return false;
1484 }
1485
1486 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
1487   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
1488     return CFP->getValueAPF().isZero();
1489   }
1490   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
1491     return C->isNullValue();
1492   }
1493   return false;
1494 }
1495
1496 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1497                                                   const TargetRegisterClass *RC,
1498                                                    unsigned Reg, EVT VT) const {
1499   MachineFunction &MF = DAG.getMachineFunction();
1500   MachineRegisterInfo &MRI = MF.getRegInfo();
1501   unsigned VirtualRegister;
1502   if (!MRI.isLiveIn(Reg)) {
1503     VirtualRegister = MRI.createVirtualRegister(RC);
1504     MRI.addLiveIn(Reg, VirtualRegister);
1505   } else {
1506     VirtualRegister = MRI.getLiveInVirtReg(Reg);
1507   }
1508   return DAG.getRegister(VirtualRegister, VT);
1509 }
1510
1511 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
1512
1513 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
1514   switch (Opcode) {
1515   default: return nullptr;
1516   // AMDIL DAG nodes
1517   NODE_NAME_CASE(CALL);
1518   NODE_NAME_CASE(UMUL);
1519   NODE_NAME_CASE(DIV_INF);
1520   NODE_NAME_CASE(RET_FLAG);
1521   NODE_NAME_CASE(BRANCH_COND);
1522
1523   // AMDGPU DAG nodes
1524   NODE_NAME_CASE(DWORDADDR)
1525   NODE_NAME_CASE(FRACT)
1526   NODE_NAME_CASE(FMAX)
1527   NODE_NAME_CASE(SMAX)
1528   NODE_NAME_CASE(UMAX)
1529   NODE_NAME_CASE(FMIN)
1530   NODE_NAME_CASE(SMIN)
1531   NODE_NAME_CASE(UMIN)
1532   NODE_NAME_CASE(BFE_U32)
1533   NODE_NAME_CASE(BFE_I32)
1534   NODE_NAME_CASE(BFI)
1535   NODE_NAME_CASE(BFM)
1536   NODE_NAME_CASE(MUL_U24)
1537   NODE_NAME_CASE(MUL_I24)
1538   NODE_NAME_CASE(MAD_U24)
1539   NODE_NAME_CASE(MAD_I24)
1540   NODE_NAME_CASE(URECIP)
1541   NODE_NAME_CASE(DOT4)
1542   NODE_NAME_CASE(EXPORT)
1543   NODE_NAME_CASE(CONST_ADDRESS)
1544   NODE_NAME_CASE(REGISTER_LOAD)
1545   NODE_NAME_CASE(REGISTER_STORE)
1546   NODE_NAME_CASE(LOAD_CONSTANT)
1547   NODE_NAME_CASE(LOAD_INPUT)
1548   NODE_NAME_CASE(SAMPLE)
1549   NODE_NAME_CASE(SAMPLEB)
1550   NODE_NAME_CASE(SAMPLED)
1551   NODE_NAME_CASE(SAMPLEL)
1552   NODE_NAME_CASE(STORE_MSKOR)
1553   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
1554   }
1555 }
1556
1557 static void computeKnownBitsForMinMax(const SDValue Op0,
1558                                       const SDValue Op1,
1559                                       APInt &KnownZero,
1560                                       APInt &KnownOne,
1561                                       const SelectionDAG &DAG,
1562                                       unsigned Depth) {
1563   APInt Op0Zero, Op0One;
1564   APInt Op1Zero, Op1One;
1565   DAG.computeKnownBits(Op0, Op0Zero, Op0One, Depth);
1566   DAG.computeKnownBits(Op1, Op1Zero, Op1One, Depth);
1567
1568   KnownZero = Op0Zero & Op1Zero;
1569   KnownOne = Op0One & Op1One;
1570 }
1571
1572 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
1573   const SDValue Op,
1574   APInt &KnownZero,
1575   APInt &KnownOne,
1576   const SelectionDAG &DAG,
1577   unsigned Depth) const {
1578
1579   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
1580
1581   APInt KnownZero2;
1582   APInt KnownOne2;
1583   unsigned Opc = Op.getOpcode();
1584
1585   switch (Opc) {
1586   default:
1587     break;
1588   case ISD::INTRINSIC_WO_CHAIN: {
1589     // FIXME: The intrinsic should just use the node.
1590     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
1591     case AMDGPUIntrinsic::AMDGPU_imax:
1592     case AMDGPUIntrinsic::AMDGPU_umax:
1593     case AMDGPUIntrinsic::AMDGPU_imin:
1594     case AMDGPUIntrinsic::AMDGPU_umin:
1595       computeKnownBitsForMinMax(Op.getOperand(1), Op.getOperand(2),
1596                                 KnownZero, KnownOne, DAG, Depth);
1597       break;
1598     default:
1599       break;
1600     }
1601
1602     break;
1603   }
1604   case AMDGPUISD::SMAX:
1605   case AMDGPUISD::UMAX:
1606   case AMDGPUISD::SMIN:
1607   case AMDGPUISD::UMIN:
1608     computeKnownBitsForMinMax(Op.getOperand(0), Op.getOperand(1),
1609                               KnownZero, KnownOne, DAG, Depth);
1610     break;
1611
1612   case AMDGPUISD::BFE_I32:
1613   case AMDGPUISD::BFE_U32: {
1614     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1615     if (!CWidth)
1616       return;
1617
1618     unsigned BitWidth = 32;
1619     uint32_t Width = CWidth->getZExtValue() & 0x1f;
1620     if (Width == 0) {
1621       KnownZero = APInt::getAllOnesValue(BitWidth);
1622       KnownOne = APInt::getNullValue(BitWidth);
1623       return;
1624     }
1625
1626     // FIXME: This could do a lot more. If offset is 0, should be the same as
1627     // sign_extend_inreg implementation, but that involves duplicating it.
1628     if (Opc == AMDGPUISD::BFE_I32)
1629       KnownOne = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
1630     else
1631       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
1632
1633     break;
1634   }
1635   }
1636 }
1637
1638 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
1639   SDValue Op,
1640   const SelectionDAG &DAG,
1641   unsigned Depth) const {
1642   switch (Op.getOpcode()) {
1643   case AMDGPUISD::BFE_I32: {
1644     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1645     if (!Width)
1646       return 1;
1647
1648     unsigned SignBits = 32 - Width->getZExtValue() + 1;
1649     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1650     if (!Offset || !Offset->isNullValue())
1651       return SignBits;
1652
1653     // TODO: Could probably figure something out with non-0 offsets.
1654     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
1655     return std::max(SignBits, Op0SignBits);
1656   }
1657
1658   case AMDGPUISD::BFE_U32: {
1659     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1660     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
1661   }
1662
1663   default:
1664     return 1;
1665   }
1666 }