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