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