R600: Try to use lower types for 64bit division if possible
[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 "AMDGPUIntrinsicInfo.h"
20 #include "AMDGPURegisterInfo.h"
21 #include "AMDGPUSubtarget.h"
22 #include "R600MachineFunctionInfo.h"
23 #include "SIMachineFunctionInfo.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32
33 using namespace llvm;
34
35 namespace {
36
37 /// Diagnostic information for unimplemented or unsupported feature reporting.
38 class DiagnosticInfoUnsupported : public DiagnosticInfo {
39 private:
40   const Twine &Description;
41   const Function &Fn;
42
43   static int KindID;
44
45   static int getKindID() {
46     if (KindID == 0)
47       KindID = llvm::getNextAvailablePluginDiagnosticKind();
48     return KindID;
49   }
50
51 public:
52   DiagnosticInfoUnsupported(const Function &Fn, const Twine &Desc,
53                           DiagnosticSeverity Severity = DS_Error)
54     : DiagnosticInfo(getKindID(), Severity),
55       Description(Desc),
56       Fn(Fn) { }
57
58   const Function &getFunction() const { return Fn; }
59   const Twine &getDescription() const { return Description; }
60
61   void print(DiagnosticPrinter &DP) const override {
62     DP << "unsupported " << getDescription() << " in " << Fn.getName();
63   }
64
65   static bool classof(const DiagnosticInfo *DI) {
66     return DI->getKind() == getKindID();
67   }
68 };
69
70 int DiagnosticInfoUnsupported::KindID = 0;
71 }
72
73
74 static bool allocateStack(unsigned ValNo, MVT ValVT, MVT LocVT,
75                       CCValAssign::LocInfo LocInfo,
76                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
77   unsigned Offset = State.AllocateStack(ValVT.getStoreSize(),
78                                         ArgFlags.getOrigAlign());
79   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
80
81   return true;
82 }
83
84 #include "AMDGPUGenCallingConv.inc"
85
86 // Find a larger type to do a load / store of a vector with.
87 EVT AMDGPUTargetLowering::getEquivalentMemType(LLVMContext &Ctx, EVT VT) {
88   unsigned StoreSize = VT.getStoreSizeInBits();
89   if (StoreSize <= 32)
90     return EVT::getIntegerVT(Ctx, StoreSize);
91
92   assert(StoreSize % 32 == 0 && "Store size not a multiple of 32");
93   return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
94 }
95
96 // Type for a vector that will be loaded to.
97 EVT AMDGPUTargetLowering::getEquivalentLoadRegType(LLVMContext &Ctx, EVT VT) {
98   unsigned StoreSize = VT.getStoreSizeInBits();
99   if (StoreSize <= 32)
100     return EVT::getIntegerVT(Ctx, 32);
101
102   return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
103 }
104
105 AMDGPUTargetLowering::AMDGPUTargetLowering(TargetMachine &TM) :
106   TargetLowering(TM) {
107
108   Subtarget = &TM.getSubtarget<AMDGPUSubtarget>();
109
110   setOperationAction(ISD::Constant, MVT::i32, Legal);
111   setOperationAction(ISD::Constant, MVT::i64, Legal);
112   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
113   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
114
115   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
116   setOperationAction(ISD::BRIND, MVT::Other, Expand);
117
118   // We need to custom lower some of the intrinsics
119   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
120
121   // Library functions.  These default to Expand, but we have instructions
122   // for them.
123   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
124   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
125   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
126   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
127   setOperationAction(ISD::FABS,   MVT::f32, Legal);
128   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
129   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
130   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
131
132   setOperationAction(ISD::FROUND, MVT::f32, Custom);
133   setOperationAction(ISD::FROUND, MVT::f64, Custom);
134
135   setOperationAction(ISD::FREM, MVT::f32, Custom);
136   setOperationAction(ISD::FREM, MVT::f64, Custom);
137
138   // Lower floating point store/load to integer store/load to reduce the number
139   // of patterns in tablegen.
140   setOperationAction(ISD::STORE, MVT::f32, Promote);
141   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
142
143   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
144   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
145
146   setOperationAction(ISD::STORE, MVT::i64, Promote);
147   AddPromotedToType(ISD::STORE, MVT::i64, MVT::v2i32);
148
149   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
150   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
151
152   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
153   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
154
155   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
156   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
157
158   setOperationAction(ISD::STORE, MVT::f64, Promote);
159   AddPromotedToType(ISD::STORE, MVT::f64, MVT::i64);
160
161   setOperationAction(ISD::STORE, MVT::v2f64, Promote);
162   AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v2i64);
163
164   // Custom lowering of vector stores is required for local address space
165   // stores.
166   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
167   // XXX: Native v2i32 local address space stores are possible, but not
168   // currently implemented.
169   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
170
171   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
172   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
173   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Custom);
174
175   // XXX: This can be change to Custom, once ExpandVectorStores can
176   // handle 64-bit stores.
177   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
178
179   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
180   setTruncStoreAction(MVT::i64, MVT::i8, Expand);
181   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
182   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
183   setTruncStoreAction(MVT::v4i64, MVT::v4i1, Expand);
184
185
186   setOperationAction(ISD::LOAD, MVT::f32, Promote);
187   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
188
189   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
190   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
191
192   setOperationAction(ISD::LOAD, MVT::i64, Promote);
193   AddPromotedToType(ISD::LOAD, MVT::i64, MVT::v2i32);
194
195   setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
196   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
197
198   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
199   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
200
201   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
202   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
203
204   setOperationAction(ISD::LOAD, MVT::f64, Promote);
205   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::i64);
206
207   setOperationAction(ISD::LOAD, MVT::v2f64, Promote);
208   AddPromotedToType(ISD::LOAD, MVT::v2f64, MVT::v2i64);
209
210   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
211   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
212   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
213   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
214   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
215   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
216   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
217   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
218   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
219   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
220
221   // There are no 64-bit extloads. These should be done as a 32-bit extload and
222   // an extension to 64-bit.
223   for (MVT VT : MVT::integer_valuetypes()) {
224     setLoadExtAction(ISD::EXTLOAD, MVT::i64, VT, Expand);
225     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, VT, Expand);
226     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, VT, Expand);
227   }
228
229   for (MVT VT : MVT::integer_vector_valuetypes()) {
230     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Expand);
231     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Expand);
232     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i8, Expand);
233     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Expand);
234     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Expand);
235     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i8, Expand);
236     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Expand);
237     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Expand);
238     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i16, Expand);
239     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Expand);
240     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Expand);
241     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i16, Expand);
242   }
243
244   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
245
246   if (Subtarget->getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
247     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
248     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
249     setOperationAction(ISD::FRINT, MVT::f64, Custom);
250     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
251   }
252
253   if (!Subtarget->hasBFI()) {
254     // fcopysign can be done in a single instruction with BFI.
255     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
256     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
257   }
258
259   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
260
261   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
262   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
263   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
264   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
265
266   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
267   for (MVT VT : ScalarIntVTs) {
268     setOperationAction(ISD::SREM, VT, Expand);
269     setOperationAction(ISD::SDIV, VT, Expand);
270
271     // GPU does not have divrem function for signed or unsigned.
272     setOperationAction(ISD::SDIVREM, VT, Custom);
273     setOperationAction(ISD::UDIVREM, VT, Custom);
274
275     // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
276     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
277     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
278
279     setOperationAction(ISD::BSWAP, VT, Expand);
280     setOperationAction(ISD::CTTZ, VT, Expand);
281     setOperationAction(ISD::CTLZ, VT, Expand);
282   }
283
284   if (!Subtarget->hasBCNT(32))
285     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
286
287   if (!Subtarget->hasBCNT(64))
288     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
289
290   // The hardware supports 32-bit ROTR, but not ROTL.
291   setOperationAction(ISD::ROTL, MVT::i32, Expand);
292   setOperationAction(ISD::ROTL, MVT::i64, Expand);
293   setOperationAction(ISD::ROTR, MVT::i64, Expand);
294
295   setOperationAction(ISD::MUL, MVT::i64, Expand);
296   setOperationAction(ISD::MULHU, MVT::i64, Expand);
297   setOperationAction(ISD::MULHS, MVT::i64, Expand);
298   setOperationAction(ISD::UDIV, MVT::i32, Expand);
299   setOperationAction(ISD::UREM, MVT::i32, Expand);
300   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
301   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
302   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
303   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
304   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
305
306   if (!Subtarget->hasFFBH())
307     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
308
309   if (!Subtarget->hasFFBL())
310     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
311
312   static const MVT::SimpleValueType VectorIntTypes[] = {
313     MVT::v2i32, MVT::v4i32
314   };
315
316   for (MVT VT : VectorIntTypes) {
317     // Expand the following operations for the current type by default.
318     setOperationAction(ISD::ADD,  VT, Expand);
319     setOperationAction(ISD::AND,  VT, Expand);
320     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
321     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
322     setOperationAction(ISD::MUL,  VT, Expand);
323     setOperationAction(ISD::OR,   VT, Expand);
324     setOperationAction(ISD::SHL,  VT, Expand);
325     setOperationAction(ISD::SRA,  VT, Expand);
326     setOperationAction(ISD::SRL,  VT, Expand);
327     setOperationAction(ISD::ROTL, VT, Expand);
328     setOperationAction(ISD::ROTR, VT, Expand);
329     setOperationAction(ISD::SUB,  VT, Expand);
330     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
331     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
332     setOperationAction(ISD::SDIV, VT, Expand);
333     setOperationAction(ISD::UDIV, VT, Expand);
334     setOperationAction(ISD::SREM, VT, Expand);
335     setOperationAction(ISD::UREM, VT, Expand);
336     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
337     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
338     setOperationAction(ISD::SDIVREM, VT, Custom);
339     setOperationAction(ISD::UDIVREM, VT, Custom);
340     setOperationAction(ISD::ADDC, VT, Expand);
341     setOperationAction(ISD::SUBC, VT, Expand);
342     setOperationAction(ISD::ADDE, VT, Expand);
343     setOperationAction(ISD::SUBE, VT, Expand);
344     setOperationAction(ISD::SELECT, VT, Expand);
345     setOperationAction(ISD::VSELECT, VT, Expand);
346     setOperationAction(ISD::SELECT_CC, VT, Expand);
347     setOperationAction(ISD::XOR,  VT, Expand);
348     setOperationAction(ISD::BSWAP, VT, Expand);
349     setOperationAction(ISD::CTPOP, VT, Expand);
350     setOperationAction(ISD::CTTZ, VT, Expand);
351     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
352     setOperationAction(ISD::CTLZ, VT, Expand);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
354     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
355   }
356
357   static const MVT::SimpleValueType FloatVectorTypes[] = {
358     MVT::v2f32, MVT::v4f32
359   };
360
361   for (MVT VT : FloatVectorTypes) {
362     setOperationAction(ISD::FABS, VT, Expand);
363     setOperationAction(ISD::FMINNUM, VT, Expand);
364     setOperationAction(ISD::FMAXNUM, VT, Expand);
365     setOperationAction(ISD::FADD, VT, Expand);
366     setOperationAction(ISD::FCEIL, VT, Expand);
367     setOperationAction(ISD::FCOS, VT, Expand);
368     setOperationAction(ISD::FDIV, VT, Expand);
369     setOperationAction(ISD::FEXP2, VT, Expand);
370     setOperationAction(ISD::FLOG2, VT, Expand);
371     setOperationAction(ISD::FREM, VT, Expand);
372     setOperationAction(ISD::FPOW, VT, Expand);
373     setOperationAction(ISD::FFLOOR, VT, Expand);
374     setOperationAction(ISD::FTRUNC, VT, Expand);
375     setOperationAction(ISD::FMUL, VT, Expand);
376     setOperationAction(ISD::FMA, VT, Expand);
377     setOperationAction(ISD::FRINT, VT, Expand);
378     setOperationAction(ISD::FNEARBYINT, VT, Expand);
379     setOperationAction(ISD::FSQRT, VT, Expand);
380     setOperationAction(ISD::FSIN, VT, Expand);
381     setOperationAction(ISD::FSUB, VT, Expand);
382     setOperationAction(ISD::FNEG, VT, Expand);
383     setOperationAction(ISD::SELECT, VT, Expand);
384     setOperationAction(ISD::VSELECT, VT, Expand);
385     setOperationAction(ISD::SELECT_CC, VT, Expand);
386     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
387     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
388   }
389
390   setOperationAction(ISD::FNEARBYINT, MVT::f32, Custom);
391   setOperationAction(ISD::FNEARBYINT, MVT::f64, Custom);
392
393   setTargetDAGCombine(ISD::MUL);
394   setTargetDAGCombine(ISD::SELECT);
395   setTargetDAGCombine(ISD::SELECT_CC);
396   setTargetDAGCombine(ISD::STORE);
397
398   setBooleanContents(ZeroOrNegativeOneBooleanContent);
399   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
400
401   setSchedulingPreference(Sched::RegPressure);
402   setJumpIsExpensive(true);
403
404   // SI at least has hardware support for floating point exceptions, but no way
405   // of using or handling them is implemented. They are also optional in OpenCL
406   // (Section 7.3)
407   setHasFloatingPointExceptions(false);
408
409   setSelectIsExpensive(false);
410   PredictableSelectIsExpensive = false;
411
412   // There are no integer divide instructions, and these expand to a pretty
413   // large sequence of instructions.
414   setIntDivIsCheap(false);
415   setPow2SDivIsCheap(false);
416   setFsqrtIsCheap(true);
417
418   // FIXME: Need to really handle these.
419   MaxStoresPerMemcpy  = 4096;
420   MaxStoresPerMemmove = 4096;
421   MaxStoresPerMemset  = 4096;
422 }
423
424 //===----------------------------------------------------------------------===//
425 // Target Information
426 //===----------------------------------------------------------------------===//
427
428 MVT AMDGPUTargetLowering::getVectorIdxTy() const {
429   return MVT::i32;
430 }
431
432 bool AMDGPUTargetLowering::isSelectSupported(SelectSupportKind SelType) const {
433   return true;
434 }
435
436 // The backend supports 32 and 64 bit floating point immediates.
437 // FIXME: Why are we reporting vectors of FP immediates as legal?
438 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
439   EVT ScalarVT = VT.getScalarType();
440   return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64);
441 }
442
443 // We don't want to shrink f64 / f32 constants.
444 bool AMDGPUTargetLowering::ShouldShrinkFPConstant(EVT VT) const {
445   EVT ScalarVT = VT.getScalarType();
446   return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
447 }
448
449 bool AMDGPUTargetLowering::shouldReduceLoadWidth(SDNode *N,
450                                                  ISD::LoadExtType,
451                                                  EVT NewVT) const {
452
453   unsigned NewSize = NewVT.getStoreSizeInBits();
454
455   // If we are reducing to a 32-bit load, this is always better.
456   if (NewSize == 32)
457     return true;
458
459   EVT OldVT = N->getValueType(0);
460   unsigned OldSize = OldVT.getStoreSizeInBits();
461
462   // Don't produce extloads from sub 32-bit types. SI doesn't have scalar
463   // extloads, so doing one requires using a buffer_load. In cases where we
464   // still couldn't use a scalar load, using the wider load shouldn't really
465   // hurt anything.
466
467   // If the old size already had to be an extload, there's no harm in continuing
468   // to reduce the width.
469   return (OldSize < 32);
470 }
471
472 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
473                                                    EVT CastTy) const {
474   if (LoadTy.getSizeInBits() != CastTy.getSizeInBits())
475     return true;
476
477   unsigned LScalarSize = LoadTy.getScalarType().getSizeInBits();
478   unsigned CastScalarSize = CastTy.getScalarType().getSizeInBits();
479
480   return ((LScalarSize <= CastScalarSize) ||
481           (CastScalarSize >= 32) ||
482           (LScalarSize < 32));
483 }
484
485 // SI+ has instructions for cttz / ctlz for 32-bit values. This is probably also
486 // profitable with the expansion for 64-bit since it's generally good to
487 // speculate things.
488 // FIXME: These should really have the size as a parameter.
489 bool AMDGPUTargetLowering::isCheapToSpeculateCttz() const {
490   return true;
491 }
492
493 bool AMDGPUTargetLowering::isCheapToSpeculateCtlz() const {
494   return true;
495 }
496
497 //===---------------------------------------------------------------------===//
498 // Target Properties
499 //===---------------------------------------------------------------------===//
500
501 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
502   assert(VT.isFloatingPoint());
503   return VT == MVT::f32 || VT == MVT::f64;
504 }
505
506 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
507   assert(VT.isFloatingPoint());
508   return VT == MVT::f32 || VT == MVT::f64;
509 }
510
511 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
512   // Truncate is just accessing a subregister.
513   return Dest.bitsLT(Source) && (Dest.getSizeInBits() % 32 == 0);
514 }
515
516 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
517   // Truncate is just accessing a subregister.
518   return Dest->getPrimitiveSizeInBits() < Source->getPrimitiveSizeInBits() &&
519          (Dest->getPrimitiveSizeInBits() % 32 == 0);
520 }
521
522 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
523   const DataLayout *DL = getDataLayout();
524   unsigned SrcSize = DL->getTypeSizeInBits(Src->getScalarType());
525   unsigned DestSize = DL->getTypeSizeInBits(Dest->getScalarType());
526
527   return SrcSize == 32 && DestSize == 64;
528 }
529
530 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
531   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
532   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
533   // this will enable reducing 64-bit operations the 32-bit, which is always
534   // good.
535   return Src == MVT::i32 && Dest == MVT::i64;
536 }
537
538 bool AMDGPUTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
539   return isZExtFree(Val.getValueType(), VT2);
540 }
541
542 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
543   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
544   // limited number of native 64-bit operations. Shrinking an operation to fit
545   // in a single 32-bit register should always be helpful. As currently used,
546   // this is much less general than the name suggests, and is only used in
547   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
548   // not profitable, and may actually be harmful.
549   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
550 }
551
552 //===---------------------------------------------------------------------===//
553 // TargetLowering Callbacks
554 //===---------------------------------------------------------------------===//
555
556 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
557                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
558
559   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
560 }
561
562 SDValue AMDGPUTargetLowering::LowerReturn(
563                                      SDValue Chain,
564                                      CallingConv::ID CallConv,
565                                      bool isVarArg,
566                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
567                                      const SmallVectorImpl<SDValue> &OutVals,
568                                      SDLoc DL, SelectionDAG &DAG) const {
569   return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, Chain);
570 }
571
572 //===---------------------------------------------------------------------===//
573 // Target specific lowering
574 //===---------------------------------------------------------------------===//
575
576 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
577                                         SmallVectorImpl<SDValue> &InVals) const {
578   SDValue Callee = CLI.Callee;
579   SelectionDAG &DAG = CLI.DAG;
580
581   const Function &Fn = *DAG.getMachineFunction().getFunction();
582
583   StringRef FuncName("<unknown>");
584
585   if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
586     FuncName = G->getSymbol();
587   else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
588     FuncName = G->getGlobal()->getName();
589
590   DiagnosticInfoUnsupported NoCalls(Fn, "call to function " + FuncName);
591   DAG.getContext()->diagnose(NoCalls);
592   return SDValue();
593 }
594
595 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op,
596                                              SelectionDAG &DAG) const {
597   switch (Op.getOpcode()) {
598   default:
599     Op.getNode()->dump();
600     llvm_unreachable("Custom lowering code for this"
601                      "instruction is not implemented yet!");
602     break;
603   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
604   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
605   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
606   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
607   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
608   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
609   case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
610   case ISD::FREM: return LowerFREM(Op, DAG);
611   case ISD::FCEIL: return LowerFCEIL(Op, DAG);
612   case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
613   case ISD::FRINT: return LowerFRINT(Op, DAG);
614   case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
615   case ISD::FROUND: return LowerFROUND(Op, DAG);
616   case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
617   case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
618   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
619   case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
620   case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
621   }
622   return Op;
623 }
624
625 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
626                                               SmallVectorImpl<SDValue> &Results,
627                                               SelectionDAG &DAG) const {
628   switch (N->getOpcode()) {
629   case ISD::SIGN_EXTEND_INREG:
630     // Different parts of legalization seem to interpret which type of
631     // sign_extend_inreg is the one to check for custom lowering. The extended
632     // from type is what really matters, but some places check for custom
633     // lowering of the result type. This results in trying to use
634     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
635     // nothing here and let the illegal result integer be handled normally.
636     return;
637   case ISD::LOAD: {
638     SDNode *Node = LowerLOAD(SDValue(N, 0), DAG).getNode();
639     if (!Node)
640       return;
641
642     Results.push_back(SDValue(Node, 0));
643     Results.push_back(SDValue(Node, 1));
644     // XXX: LLVM seems not to replace Chain Value inside CustomWidenLowerNode
645     // function
646     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), SDValue(Node, 1));
647     return;
648   }
649   case ISD::STORE: {
650     SDValue Lowered = LowerSTORE(SDValue(N, 0), DAG);
651     if (Lowered.getNode())
652       Results.push_back(Lowered);
653     return;
654   }
655   default:
656     return;
657   }
658 }
659
660 // FIXME: This implements accesses to initialized globals in the constant
661 // address space by copying them to private and accessing that. It does not
662 // properly handle illegal types or vectors. The private vector loads are not
663 // scalarized, and the illegal scalars hit an assertion. This technique will not
664 // work well with large initializers, and this should eventually be
665 // removed. Initialized globals should be placed into a data section that the
666 // runtime will load into a buffer before the kernel is executed. Uses of the
667 // global need to be replaced with a pointer loaded from an implicit kernel
668 // argument into this buffer holding the copy of the data, which will remove the
669 // need for any of this.
670 SDValue AMDGPUTargetLowering::LowerConstantInitializer(const Constant* Init,
671                                                        const GlobalValue *GV,
672                                                        const SDValue &InitPtr,
673                                                        SDValue Chain,
674                                                        SelectionDAG &DAG) const {
675   const DataLayout *TD = getTargetMachine().getSubtargetImpl()->getDataLayout();
676   SDLoc DL(InitPtr);
677   Type *InitTy = Init->getType();
678
679   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Init)) {
680     EVT VT = EVT::getEVT(InitTy);
681     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
682     return DAG.getStore(Chain, DL, DAG.getConstant(*CI, VT), InitPtr,
683                         MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
684                         TD->getPrefTypeAlignment(InitTy));
685   }
686
687   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Init)) {
688     EVT VT = EVT::getEVT(CFP->getType());
689     PointerType *PtrTy = PointerType::get(CFP->getType(), 0);
690     return DAG.getStore(Chain, DL, DAG.getConstantFP(*CFP, VT), InitPtr,
691                  MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
692                  TD->getPrefTypeAlignment(CFP->getType()));
693   }
694
695   if (StructType *ST = dyn_cast<StructType>(InitTy)) {
696     const StructLayout *SL = TD->getStructLayout(ST);
697
698     EVT PtrVT = InitPtr.getValueType();
699     SmallVector<SDValue, 8> Chains;
700
701     for (unsigned I = 0, N = ST->getNumElements(); I != N; ++I) {
702       SDValue Offset = DAG.getConstant(SL->getElementOffset(I), PtrVT);
703       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
704
705       Constant *Elt = Init->getAggregateElement(I);
706       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
707     }
708
709     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
710   }
711
712   if (SequentialType *SeqTy = dyn_cast<SequentialType>(InitTy)) {
713     EVT PtrVT = InitPtr.getValueType();
714
715     unsigned NumElements;
716     if (ArrayType *AT = dyn_cast<ArrayType>(SeqTy))
717       NumElements = AT->getNumElements();
718     else if (VectorType *VT = dyn_cast<VectorType>(SeqTy))
719       NumElements = VT->getNumElements();
720     else
721       llvm_unreachable("Unexpected type");
722
723     unsigned EltSize = TD->getTypeAllocSize(SeqTy->getElementType());
724     SmallVector<SDValue, 8> Chains;
725     for (unsigned i = 0; i < NumElements; ++i) {
726       SDValue Offset = DAG.getConstant(i * EltSize, PtrVT);
727       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
728
729       Constant *Elt = Init->getAggregateElement(i);
730       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
731     }
732
733     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
734   }
735
736   if (isa<UndefValue>(Init)) {
737     EVT VT = EVT::getEVT(InitTy);
738     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
739     return DAG.getStore(Chain, DL, DAG.getUNDEF(VT), InitPtr,
740                         MachinePointerInfo(UndefValue::get(PtrTy)), false, false,
741                         TD->getPrefTypeAlignment(InitTy));
742   }
743
744   Init->dump();
745   llvm_unreachable("Unhandled constant initializer");
746 }
747
748 static bool hasDefinedInitializer(const GlobalValue *GV) {
749   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
750   if (!GVar || !GVar->hasInitializer())
751     return false;
752
753   if (isa<UndefValue>(GVar->getInitializer()))
754     return false;
755
756   return true;
757 }
758
759 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
760                                                  SDValue Op,
761                                                  SelectionDAG &DAG) const {
762
763   const DataLayout *TD = getTargetMachine().getSubtargetImpl()->getDataLayout();
764   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
765   const GlobalValue *GV = G->getGlobal();
766
767   switch (G->getAddressSpace()) {
768   case AMDGPUAS::LOCAL_ADDRESS: {
769     // XXX: What does the value of G->getOffset() mean?
770     assert(G->getOffset() == 0 &&
771          "Do not know what to do with an non-zero offset");
772
773     // TODO: We could emit code to handle the initialization somewhere.
774     if (hasDefinedInitializer(GV))
775       break;
776
777     unsigned Offset;
778     if (MFI->LocalMemoryObjects.count(GV) == 0) {
779       uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
780       Offset = MFI->LDSSize;
781       MFI->LocalMemoryObjects[GV] = Offset;
782       // XXX: Account for alignment?
783       MFI->LDSSize += Size;
784     } else {
785       Offset = MFI->LocalMemoryObjects[GV];
786     }
787
788     return DAG.getConstant(Offset, getPointerTy(AMDGPUAS::LOCAL_ADDRESS));
789   }
790   case AMDGPUAS::CONSTANT_ADDRESS: {
791     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
792     Type *EltType = GV->getType()->getElementType();
793     unsigned Size = TD->getTypeAllocSize(EltType);
794     unsigned Alignment = TD->getPrefTypeAlignment(EltType);
795
796     MVT PrivPtrVT = getPointerTy(AMDGPUAS::PRIVATE_ADDRESS);
797     MVT ConstPtrVT = getPointerTy(AMDGPUAS::CONSTANT_ADDRESS);
798
799     int FI = FrameInfo->CreateStackObject(Size, Alignment, false);
800     SDValue InitPtr = DAG.getFrameIndex(FI, PrivPtrVT);
801
802     const GlobalVariable *Var = cast<GlobalVariable>(GV);
803     if (!Var->hasInitializer()) {
804       // This has no use, but bugpoint will hit it.
805       return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
806     }
807
808     const Constant *Init = Var->getInitializer();
809     SmallVector<SDNode*, 8> WorkList;
810
811     for (SDNode::use_iterator I = DAG.getEntryNode()->use_begin(),
812                               E = DAG.getEntryNode()->use_end(); I != E; ++I) {
813       if (I->getOpcode() != AMDGPUISD::REGISTER_LOAD && I->getOpcode() != ISD::LOAD)
814         continue;
815       WorkList.push_back(*I);
816     }
817     SDValue Chain = LowerConstantInitializer(Init, GV, InitPtr, DAG.getEntryNode(), DAG);
818     for (SmallVector<SDNode*, 8>::iterator I = WorkList.begin(),
819                                            E = WorkList.end(); I != E; ++I) {
820       SmallVector<SDValue, 8> Ops;
821       Ops.push_back(Chain);
822       for (unsigned i = 1; i < (*I)->getNumOperands(); ++i) {
823         Ops.push_back((*I)->getOperand(i));
824       }
825       DAG.UpdateNodeOperands(*I, Ops);
826     }
827     return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
828   }
829   }
830
831   const Function &Fn = *DAG.getMachineFunction().getFunction();
832   DiagnosticInfoUnsupported BadInit(Fn,
833                                     "initializer for address space");
834   DAG.getContext()->diagnose(BadInit);
835   return SDValue();
836 }
837
838 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
839                                                   SelectionDAG &DAG) const {
840   SmallVector<SDValue, 8> Args;
841   SDValue A = Op.getOperand(0);
842   SDValue B = Op.getOperand(1);
843
844   DAG.ExtractVectorElements(A, Args);
845   DAG.ExtractVectorElements(B, Args);
846
847   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
848 }
849
850 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
851                                                      SelectionDAG &DAG) const {
852
853   SmallVector<SDValue, 8> Args;
854   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
855   EVT VT = Op.getValueType();
856   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
857                             VT.getVectorNumElements());
858
859   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
860 }
861
862 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
863                                               SelectionDAG &DAG) const {
864
865   MachineFunction &MF = DAG.getMachineFunction();
866   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering *>(
867       getTargetMachine().getSubtargetImpl()->getFrameLowering());
868
869   FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(Op);
870
871   unsigned FrameIndex = FIN->getIndex();
872   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
873   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF),
874                          Op.getValueType());
875 }
876
877 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
878     SelectionDAG &DAG) const {
879   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
880   SDLoc DL(Op);
881   EVT VT = Op.getValueType();
882
883   switch (IntrinsicID) {
884     default: return Op;
885     case AMDGPUIntrinsic::AMDGPU_abs:
886     case AMDGPUIntrinsic::AMDIL_abs: // Legacy name.
887       return LowerIntrinsicIABS(Op, DAG);
888     case AMDGPUIntrinsic::AMDGPU_lrp:
889       return LowerIntrinsicLRP(Op, DAG);
890     case AMDGPUIntrinsic::AMDGPU_fract:
891     case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
892       return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
893
894     case AMDGPUIntrinsic::AMDGPU_clamp:
895     case AMDGPUIntrinsic::AMDIL_clamp: // Legacy name.
896       return DAG.getNode(AMDGPUISD::CLAMP, DL, VT,
897                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
898
899     case Intrinsic::AMDGPU_div_scale: {
900       // 3rd parameter required to be a constant.
901       const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
902       if (!Param)
903         return DAG.getUNDEF(VT);
904
905       // Translate to the operands expected by the machine instruction. The
906       // first parameter must be the same as the first instruction.
907       SDValue Numerator = Op.getOperand(1);
908       SDValue Denominator = Op.getOperand(2);
909
910       // Note this order is opposite of the machine instruction's operations,
911       // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
912       // intrinsic has the numerator as the first operand to match a normal
913       // division operation.
914
915       SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
916
917       return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
918                          Denominator, Numerator);
919     }
920
921     case Intrinsic::AMDGPU_div_fmas:
922       // FIXME: Dropping bool parameter. Work is needed to support the implicit
923       // read from VCC.
924       return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
925                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
926
927     case Intrinsic::AMDGPU_div_fixup:
928       return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
929                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
930
931     case Intrinsic::AMDGPU_trig_preop:
932       return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
933                          Op.getOperand(1), Op.getOperand(2));
934
935     case Intrinsic::AMDGPU_rcp:
936       return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
937
938     case Intrinsic::AMDGPU_rsq:
939       return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
940
941     case AMDGPUIntrinsic::AMDGPU_legacy_rsq:
942       return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
943
944     case Intrinsic::AMDGPU_rsq_clamped:
945       if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
946         Type *Type = VT.getTypeForEVT(*DAG.getContext());
947         APFloat Max = APFloat::getLargest(Type->getFltSemantics());
948         APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
949
950         SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
951         SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
952                                   DAG.getConstantFP(Max, VT));
953         return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
954                            DAG.getConstantFP(Min, VT));
955       } else {
956         return DAG.getNode(AMDGPUISD::RSQ_CLAMPED, DL, VT, Op.getOperand(1));
957       }
958
959     case Intrinsic::AMDGPU_ldexp:
960       return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, Op.getOperand(1),
961                                                    Op.getOperand(2));
962
963     case AMDGPUIntrinsic::AMDGPU_imax:
964       return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Op.getOperand(1),
965                                                   Op.getOperand(2));
966     case AMDGPUIntrinsic::AMDGPU_umax:
967       return DAG.getNode(AMDGPUISD::UMAX, DL, VT, Op.getOperand(1),
968                                                   Op.getOperand(2));
969     case AMDGPUIntrinsic::AMDGPU_imin:
970       return DAG.getNode(AMDGPUISD::SMIN, DL, VT, Op.getOperand(1),
971                                                   Op.getOperand(2));
972     case AMDGPUIntrinsic::AMDGPU_umin:
973       return DAG.getNode(AMDGPUISD::UMIN, DL, VT, Op.getOperand(1),
974                                                   Op.getOperand(2));
975
976     case AMDGPUIntrinsic::AMDGPU_umul24:
977       return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT,
978                          Op.getOperand(1), Op.getOperand(2));
979
980     case AMDGPUIntrinsic::AMDGPU_imul24:
981       return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT,
982                          Op.getOperand(1), Op.getOperand(2));
983
984     case AMDGPUIntrinsic::AMDGPU_umad24:
985       return DAG.getNode(AMDGPUISD::MAD_U24, DL, VT,
986                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
987
988     case AMDGPUIntrinsic::AMDGPU_imad24:
989       return DAG.getNode(AMDGPUISD::MAD_I24, DL, VT,
990                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
991
992     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte0:
993       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Op.getOperand(1));
994
995     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte1:
996       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE1, DL, VT, Op.getOperand(1));
997
998     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte2:
999       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE2, DL, VT, Op.getOperand(1));
1000
1001     case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte3:
1002       return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE3, DL, VT, Op.getOperand(1));
1003
1004     case AMDGPUIntrinsic::AMDGPU_bfe_i32:
1005       return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
1006                          Op.getOperand(1),
1007                          Op.getOperand(2),
1008                          Op.getOperand(3));
1009
1010     case AMDGPUIntrinsic::AMDGPU_bfe_u32:
1011       return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
1012                          Op.getOperand(1),
1013                          Op.getOperand(2),
1014                          Op.getOperand(3));
1015
1016     case AMDGPUIntrinsic::AMDGPU_bfi:
1017       return DAG.getNode(AMDGPUISD::BFI, DL, VT,
1018                          Op.getOperand(1),
1019                          Op.getOperand(2),
1020                          Op.getOperand(3));
1021
1022     case AMDGPUIntrinsic::AMDGPU_bfm:
1023       return DAG.getNode(AMDGPUISD::BFM, DL, VT,
1024                          Op.getOperand(1),
1025                          Op.getOperand(2));
1026
1027     case AMDGPUIntrinsic::AMDGPU_brev:
1028       return DAG.getNode(AMDGPUISD::BREV, DL, VT, Op.getOperand(1));
1029
1030   case Intrinsic::AMDGPU_class:
1031     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
1032                        Op.getOperand(1), Op.getOperand(2));
1033
1034     case AMDGPUIntrinsic::AMDIL_exp: // Legacy name.
1035       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
1036
1037     case AMDGPUIntrinsic::AMDIL_round_nearest: // Legacy name.
1038       return DAG.getNode(ISD::FRINT, DL, VT, Op.getOperand(1));
1039     case AMDGPUIntrinsic::AMDGPU_trunc: // Legacy name.
1040       return DAG.getNode(ISD::FTRUNC, DL, VT, Op.getOperand(1));
1041   }
1042 }
1043
1044 ///IABS(a) = SMAX(sub(0, a), a)
1045 SDValue AMDGPUTargetLowering::LowerIntrinsicIABS(SDValue Op,
1046                                                  SelectionDAG &DAG) const {
1047   SDLoc DL(Op);
1048   EVT VT = Op.getValueType();
1049   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
1050                                               Op.getOperand(1));
1051
1052   return DAG.getNode(AMDGPUISD::SMAX, DL, VT, Neg, Op.getOperand(1));
1053 }
1054
1055 /// Linear Interpolation
1056 /// LRP(a, b, c) = muladd(a,  b, (1 - a) * c)
1057 SDValue AMDGPUTargetLowering::LowerIntrinsicLRP(SDValue Op,
1058                                                 SelectionDAG &DAG) const {
1059   SDLoc DL(Op);
1060   EVT VT = Op.getValueType();
1061   SDValue OneSubA = DAG.getNode(ISD::FSUB, DL, VT,
1062                                 DAG.getConstantFP(1.0f, MVT::f32),
1063                                 Op.getOperand(1));
1064   SDValue OneSubAC = DAG.getNode(ISD::FMUL, DL, VT, OneSubA,
1065                                                     Op.getOperand(3));
1066   return DAG.getNode(ISD::FADD, DL, VT,
1067       DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), Op.getOperand(2)),
1068       OneSubAC);
1069 }
1070
1071 /// \brief Generate Min/Max node
1072 SDValue AMDGPUTargetLowering::CombineFMinMaxLegacy(SDLoc DL,
1073                                                    EVT VT,
1074                                                    SDValue LHS,
1075                                                    SDValue RHS,
1076                                                    SDValue True,
1077                                                    SDValue False,
1078                                                    SDValue CC,
1079                                                    DAGCombinerInfo &DCI) const {
1080   if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1081     return SDValue();
1082
1083   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
1084     return SDValue();
1085
1086   SelectionDAG &DAG = DCI.DAG;
1087   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1088   switch (CCOpcode) {
1089   case ISD::SETOEQ:
1090   case ISD::SETONE:
1091   case ISD::SETUNE:
1092   case ISD::SETNE:
1093   case ISD::SETUEQ:
1094   case ISD::SETEQ:
1095   case ISD::SETFALSE:
1096   case ISD::SETFALSE2:
1097   case ISD::SETTRUE:
1098   case ISD::SETTRUE2:
1099   case ISD::SETUO:
1100   case ISD::SETO:
1101     break;
1102   case ISD::SETULE:
1103   case ISD::SETULT: {
1104     if (LHS == True)
1105       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1106     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1107   }
1108   case ISD::SETOLE:
1109   case ISD::SETOLT:
1110   case ISD::SETLE:
1111   case ISD::SETLT: {
1112     // Ordered. Assume ordered for undefined.
1113
1114     // Only do this after legalization to avoid interfering with other combines
1115     // which might occur.
1116     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1117         !DCI.isCalledByLegalizer())
1118       return SDValue();
1119
1120     // We need to permute the operands to get the correct NaN behavior. The
1121     // selected operand is the second one based on the failing compare with NaN,
1122     // so permute it based on the compare type the hardware uses.
1123     if (LHS == True)
1124       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1125     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1126   }
1127   case ISD::SETUGE:
1128   case ISD::SETUGT: {
1129     if (LHS == True)
1130       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1131     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1132   }
1133   case ISD::SETGT:
1134   case ISD::SETGE:
1135   case ISD::SETOGE:
1136   case ISD::SETOGT: {
1137     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1138         !DCI.isCalledByLegalizer())
1139       return SDValue();
1140
1141     if (LHS == True)
1142       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1143     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1144   }
1145   case ISD::SETCC_INVALID:
1146     llvm_unreachable("Invalid setcc condcode!");
1147   }
1148   return SDValue();
1149 }
1150
1151 /// \brief Generate Min/Max node
1152 SDValue AMDGPUTargetLowering::CombineIMinMax(SDLoc DL,
1153                                              EVT VT,
1154                                              SDValue LHS,
1155                                              SDValue RHS,
1156                                              SDValue True,
1157                                              SDValue False,
1158                                              SDValue CC,
1159                                              SelectionDAG &DAG) const {
1160   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
1161     return SDValue();
1162
1163   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1164   switch (CCOpcode) {
1165   case ISD::SETULE:
1166   case ISD::SETULT: {
1167     unsigned Opc = (LHS == True) ? AMDGPUISD::UMIN : AMDGPUISD::UMAX;
1168     return DAG.getNode(Opc, DL, VT, LHS, RHS);
1169   }
1170   case ISD::SETLE:
1171   case ISD::SETLT: {
1172     unsigned Opc = (LHS == True) ? AMDGPUISD::SMIN : AMDGPUISD::SMAX;
1173     return DAG.getNode(Opc, DL, VT, LHS, RHS);
1174   }
1175   case ISD::SETGT:
1176   case ISD::SETGE: {
1177     unsigned Opc = (LHS == True) ? AMDGPUISD::SMAX : AMDGPUISD::SMIN;
1178     return DAG.getNode(Opc, DL, VT, LHS, RHS);
1179   }
1180   case ISD::SETUGE:
1181   case ISD::SETUGT: {
1182     unsigned Opc = (LHS == True) ? AMDGPUISD::UMAX : AMDGPUISD::UMIN;
1183     return DAG.getNode(Opc, DL, VT, LHS, RHS);
1184   }
1185   default:
1186     return SDValue();
1187   }
1188 }
1189
1190 SDValue AMDGPUTargetLowering::ScalarizeVectorLoad(const SDValue Op,
1191                                                   SelectionDAG &DAG) const {
1192   LoadSDNode *Load = cast<LoadSDNode>(Op);
1193   EVT MemVT = Load->getMemoryVT();
1194   EVT MemEltVT = MemVT.getVectorElementType();
1195
1196   EVT LoadVT = Op.getValueType();
1197   EVT EltVT = LoadVT.getVectorElementType();
1198   EVT PtrVT = Load->getBasePtr().getValueType();
1199
1200   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
1201   SmallVector<SDValue, 8> Loads;
1202   SmallVector<SDValue, 8> Chains;
1203
1204   SDLoc SL(Op);
1205   unsigned MemEltSize = MemEltVT.getStoreSize();
1206   MachinePointerInfo SrcValue(Load->getMemOperand()->getValue());
1207
1208   for (unsigned i = 0; i < NumElts; ++i) {
1209     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
1210                               DAG.getConstant(i * MemEltSize, PtrVT));
1211
1212     SDValue NewLoad
1213       = DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
1214                        Load->getChain(), Ptr,
1215                        SrcValue.getWithOffset(i * MemEltSize),
1216                        MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
1217                        Load->isInvariant(), Load->getAlignment());
1218     Loads.push_back(NewLoad.getValue(0));
1219     Chains.push_back(NewLoad.getValue(1));
1220   }
1221
1222   SDValue Ops[] = {
1223     DAG.getNode(ISD::BUILD_VECTOR, SL, LoadVT, Loads),
1224     DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains)
1225   };
1226
1227   return DAG.getMergeValues(Ops, SL);
1228 }
1229
1230 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue Op,
1231                                               SelectionDAG &DAG) const {
1232   EVT VT = Op.getValueType();
1233
1234   // If this is a 2 element vector, we really want to scalarize and not create
1235   // weird 1 element vectors.
1236   if (VT.getVectorNumElements() == 2)
1237     return ScalarizeVectorLoad(Op, DAG);
1238
1239   LoadSDNode *Load = cast<LoadSDNode>(Op);
1240   SDValue BasePtr = Load->getBasePtr();
1241   EVT PtrVT = BasePtr.getValueType();
1242   EVT MemVT = Load->getMemoryVT();
1243   SDLoc SL(Op);
1244   MachinePointerInfo SrcValue(Load->getMemOperand()->getValue());
1245
1246   EVT LoVT, HiVT;
1247   EVT LoMemVT, HiMemVT;
1248   SDValue Lo, Hi;
1249
1250   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1251   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1252   std::tie(Lo, Hi) = DAG.SplitVector(Op, SL, LoVT, HiVT);
1253   SDValue LoLoad
1254     = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1255                      Load->getChain(), BasePtr,
1256                      SrcValue,
1257                      LoMemVT, Load->isVolatile(), Load->isNonTemporal(),
1258                      Load->isInvariant(), Load->getAlignment());
1259
1260   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1261                               DAG.getConstant(LoMemVT.getStoreSize(), PtrVT));
1262
1263   SDValue HiLoad
1264     = DAG.getExtLoad(Load->getExtensionType(), SL, HiVT,
1265                      Load->getChain(), HiPtr,
1266                      SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1267                      HiMemVT, Load->isVolatile(), Load->isNonTemporal(),
1268                      Load->isInvariant(), Load->getAlignment());
1269
1270   SDValue Ops[] = {
1271     DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad),
1272     DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
1273                 LoLoad.getValue(1), HiLoad.getValue(1))
1274   };
1275
1276   return DAG.getMergeValues(Ops, SL);
1277 }
1278
1279 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
1280                                                SelectionDAG &DAG) const {
1281   StoreSDNode *Store = cast<StoreSDNode>(Op);
1282   EVT MemVT = Store->getMemoryVT();
1283   unsigned MemBits = MemVT.getSizeInBits();
1284
1285   // Byte stores are really expensive, so if possible, try to pack 32-bit vector
1286   // truncating store into an i32 store.
1287   // XXX: We could also handle optimize other vector bitwidths.
1288   if (!MemVT.isVector() || MemBits > 32) {
1289     return SDValue();
1290   }
1291
1292   SDLoc DL(Op);
1293   SDValue Value = Store->getValue();
1294   EVT VT = Value.getValueType();
1295   EVT ElemVT = VT.getVectorElementType();
1296   SDValue Ptr = Store->getBasePtr();
1297   EVT MemEltVT = MemVT.getVectorElementType();
1298   unsigned MemEltBits = MemEltVT.getSizeInBits();
1299   unsigned MemNumElements = MemVT.getVectorNumElements();
1300   unsigned PackedSize = MemVT.getStoreSizeInBits();
1301   SDValue Mask = DAG.getConstant((1 << MemEltBits) - 1, MVT::i32);
1302
1303   assert(Value.getValueType().getScalarSizeInBits() >= 32);
1304
1305   SDValue PackedValue;
1306   for (unsigned i = 0; i < MemNumElements; ++i) {
1307     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
1308                               DAG.getConstant(i, MVT::i32));
1309     Elt = DAG.getZExtOrTrunc(Elt, DL, MVT::i32);
1310     Elt = DAG.getNode(ISD::AND, DL, MVT::i32, Elt, Mask); // getZeroExtendInReg
1311
1312     SDValue Shift = DAG.getConstant(MemEltBits * i, MVT::i32);
1313     Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt, Shift);
1314
1315     if (i == 0) {
1316       PackedValue = Elt;
1317     } else {
1318       PackedValue = DAG.getNode(ISD::OR, DL, MVT::i32, PackedValue, Elt);
1319     }
1320   }
1321
1322   if (PackedSize < 32) {
1323     EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), PackedSize);
1324     return DAG.getTruncStore(Store->getChain(), DL, PackedValue, Ptr,
1325                              Store->getMemOperand()->getPointerInfo(),
1326                              PackedVT,
1327                              Store->isNonTemporal(), Store->isVolatile(),
1328                              Store->getAlignment());
1329   }
1330
1331   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
1332                       Store->getMemOperand()->getPointerInfo(),
1333                       Store->isVolatile(),  Store->isNonTemporal(),
1334                       Store->getAlignment());
1335 }
1336
1337 SDValue AMDGPUTargetLowering::ScalarizeVectorStore(SDValue Op,
1338                                                    SelectionDAG &DAG) const {
1339   StoreSDNode *Store = cast<StoreSDNode>(Op);
1340   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
1341   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
1342   EVT PtrVT = Store->getBasePtr().getValueType();
1343   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
1344   SDLoc SL(Op);
1345
1346   SmallVector<SDValue, 8> Chains;
1347
1348   unsigned EltSize = MemEltVT.getStoreSize();
1349   MachinePointerInfo SrcValue(Store->getMemOperand()->getValue());
1350
1351   for (unsigned i = 0, e = NumElts; i != e; ++i) {
1352     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
1353                               Store->getValue(),
1354                               DAG.getConstant(i, MVT::i32));
1355
1356     SDValue Offset = DAG.getConstant(i * MemEltVT.getStoreSize(), PtrVT);
1357     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Store->getBasePtr(), Offset);
1358     SDValue NewStore =
1359       DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
1360                         SrcValue.getWithOffset(i * EltSize),
1361                         MemEltVT, Store->isNonTemporal(), Store->isVolatile(),
1362                         Store->getAlignment());
1363     Chains.push_back(NewStore);
1364   }
1365
1366   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains);
1367 }
1368
1369 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1370                                                SelectionDAG &DAG) const {
1371   StoreSDNode *Store = cast<StoreSDNode>(Op);
1372   SDValue Val = Store->getValue();
1373   EVT VT = Val.getValueType();
1374
1375   // If this is a 2 element vector, we really want to scalarize and not create
1376   // weird 1 element vectors.
1377   if (VT.getVectorNumElements() == 2)
1378     return ScalarizeVectorStore(Op, DAG);
1379
1380   EVT MemVT = Store->getMemoryVT();
1381   SDValue Chain = Store->getChain();
1382   SDValue BasePtr = Store->getBasePtr();
1383   SDLoc SL(Op);
1384
1385   EVT LoVT, HiVT;
1386   EVT LoMemVT, HiMemVT;
1387   SDValue Lo, Hi;
1388
1389   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1390   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1391   std::tie(Lo, Hi) = DAG.SplitVector(Val, SL, LoVT, HiVT);
1392
1393   EVT PtrVT = BasePtr.getValueType();
1394   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1395                               DAG.getConstant(LoMemVT.getStoreSize(), PtrVT));
1396
1397   MachinePointerInfo SrcValue(Store->getMemOperand()->getValue());
1398   SDValue LoStore
1399     = DAG.getTruncStore(Chain, SL, Lo,
1400                         BasePtr,
1401                         SrcValue,
1402                         LoMemVT,
1403                         Store->isNonTemporal(),
1404                         Store->isVolatile(),
1405                         Store->getAlignment());
1406   SDValue HiStore
1407     = DAG.getTruncStore(Chain, SL, Hi,
1408                         HiPtr,
1409                         SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1410                         HiMemVT,
1411                         Store->isNonTemporal(),
1412                         Store->isVolatile(),
1413                         Store->getAlignment());
1414
1415   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1416 }
1417
1418
1419 SDValue AMDGPUTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1420   SDLoc DL(Op);
1421   LoadSDNode *Load = cast<LoadSDNode>(Op);
1422   ISD::LoadExtType ExtType = Load->getExtensionType();
1423   EVT VT = Op.getValueType();
1424   EVT MemVT = Load->getMemoryVT();
1425
1426   if (ExtType == ISD::NON_EXTLOAD && VT.getSizeInBits() < 32) {
1427     assert(VT == MVT::i1 && "Only i1 non-extloads expected");
1428     // FIXME: Copied from PPC
1429     // First, load into 32 bits, then truncate to 1 bit.
1430
1431     SDValue Chain = Load->getChain();
1432     SDValue BasePtr = Load->getBasePtr();
1433     MachineMemOperand *MMO = Load->getMemOperand();
1434
1435     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
1436                                    BasePtr, MVT::i8, MMO);
1437
1438     SDValue Ops[] = {
1439       DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD),
1440       NewLD.getValue(1)
1441     };
1442
1443     return DAG.getMergeValues(Ops, DL);
1444   }
1445
1446   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS ||
1447       Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS ||
1448       ExtType == ISD::NON_EXTLOAD || Load->getMemoryVT().bitsGE(MVT::i32))
1449     return SDValue();
1450
1451
1452   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
1453                             DAG.getConstant(2, MVT::i32));
1454   SDValue Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, Op.getValueType(),
1455                             Load->getChain(), Ptr,
1456                             DAG.getTargetConstant(0, MVT::i32),
1457                             Op.getOperand(2));
1458   SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32,
1459                                 Load->getBasePtr(),
1460                                 DAG.getConstant(0x3, MVT::i32));
1461   SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1462                                  DAG.getConstant(3, MVT::i32));
1463
1464   Ret = DAG.getNode(ISD::SRL, DL, MVT::i32, Ret, ShiftAmt);
1465
1466   EVT MemEltVT = MemVT.getScalarType();
1467   if (ExtType == ISD::SEXTLOAD) {
1468     SDValue MemEltVTNode = DAG.getValueType(MemEltVT);
1469
1470     SDValue Ops[] = {
1471       DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, Ret, MemEltVTNode),
1472       Load->getChain()
1473     };
1474
1475     return DAG.getMergeValues(Ops, DL);
1476   }
1477
1478   SDValue Ops[] = {
1479     DAG.getZeroExtendInReg(Ret, DL, MemEltVT),
1480     Load->getChain()
1481   };
1482
1483   return DAG.getMergeValues(Ops, DL);
1484 }
1485
1486 SDValue AMDGPUTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1487   SDLoc DL(Op);
1488   SDValue Result = AMDGPUTargetLowering::MergeVectorStore(Op, DAG);
1489   if (Result.getNode()) {
1490     return Result;
1491   }
1492
1493   StoreSDNode *Store = cast<StoreSDNode>(Op);
1494   SDValue Chain = Store->getChain();
1495   if ((Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1496        Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) &&
1497       Store->getValue().getValueType().isVector()) {
1498     return ScalarizeVectorStore(Op, DAG);
1499   }
1500
1501   EVT MemVT = Store->getMemoryVT();
1502   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS &&
1503       MemVT.bitsLT(MVT::i32)) {
1504     unsigned Mask = 0;
1505     if (Store->getMemoryVT() == MVT::i8) {
1506       Mask = 0xff;
1507     } else if (Store->getMemoryVT() == MVT::i16) {
1508       Mask = 0xffff;
1509     }
1510     SDValue BasePtr = Store->getBasePtr();
1511     SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, BasePtr,
1512                               DAG.getConstant(2, MVT::i32));
1513     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
1514                               Chain, Ptr, DAG.getTargetConstant(0, MVT::i32));
1515
1516     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, BasePtr,
1517                                   DAG.getConstant(0x3, MVT::i32));
1518
1519     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1520                                    DAG.getConstant(3, MVT::i32));
1521
1522     SDValue SExtValue = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32,
1523                                     Store->getValue());
1524
1525     SDValue MaskedValue = DAG.getZeroExtendInReg(SExtValue, DL, MemVT);
1526
1527     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
1528                                        MaskedValue, ShiftAmt);
1529
1530     SDValue DstMask = DAG.getNode(ISD::SHL, DL, MVT::i32, DAG.getConstant(Mask, MVT::i32),
1531                                   ShiftAmt);
1532     DstMask = DAG.getNode(ISD::XOR, DL, MVT::i32, DstMask,
1533                           DAG.getConstant(0xffffffff, MVT::i32));
1534     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
1535
1536     SDValue Value = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
1537     return DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
1538                        Chain, Value, Ptr, DAG.getTargetConstant(0, MVT::i32));
1539   }
1540   return SDValue();
1541 }
1542
1543 // This is a shortcut for integer division because we have fast i32<->f32
1544 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1545 // float is enough to accurately represent up to a 24-bit integer.
1546 SDValue AMDGPUTargetLowering::LowerDIVREM24(SDValue Op, SelectionDAG &DAG, bool sign) const {
1547   SDLoc DL(Op);
1548   EVT VT = Op.getValueType();
1549   SDValue LHS = Op.getOperand(0);
1550   SDValue RHS = Op.getOperand(1);
1551   MVT IntVT = MVT::i32;
1552   MVT FltVT = MVT::f32;
1553
1554   ISD::NodeType ToFp  = sign ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
1555   ISD::NodeType ToInt = sign ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
1556
1557   if (VT.isVector()) {
1558     unsigned NElts = VT.getVectorNumElements();
1559     IntVT = MVT::getVectorVT(MVT::i32, NElts);
1560     FltVT = MVT::getVectorVT(MVT::f32, NElts);
1561   }
1562
1563   unsigned BitSize = VT.getScalarType().getSizeInBits();
1564
1565   SDValue jq = DAG.getConstant(1, IntVT);
1566
1567   if (sign) {
1568     // char|short jq = ia ^ ib;
1569     jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1570
1571     // jq = jq >> (bitsize - 2)
1572     jq = DAG.getNode(ISD::SRA, DL, VT, jq, DAG.getConstant(BitSize - 2, VT));
1573
1574     // jq = jq | 0x1
1575     jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, VT));
1576
1577     // jq = (int)jq
1578     jq = DAG.getSExtOrTrunc(jq, DL, IntVT);
1579   }
1580
1581   // int ia = (int)LHS;
1582   SDValue ia = sign ?
1583     DAG.getSExtOrTrunc(LHS, DL, IntVT) : DAG.getZExtOrTrunc(LHS, DL, IntVT);
1584
1585   // int ib, (int)RHS;
1586   SDValue ib = sign ?
1587     DAG.getSExtOrTrunc(RHS, DL, IntVT) : DAG.getZExtOrTrunc(RHS, DL, IntVT);
1588
1589   // float fa = (float)ia;
1590   SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1591
1592   // float fb = (float)ib;
1593   SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1594
1595   // float fq = native_divide(fa, fb);
1596   SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1597                            fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1598
1599   // fq = trunc(fq);
1600   fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1601
1602   // float fqneg = -fq;
1603   SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1604
1605   // float fr = mad(fqneg, fb, fa);
1606   SDValue fr = DAG.getNode(ISD::FADD, DL, FltVT,
1607                            DAG.getNode(ISD::FMUL, DL, FltVT, fqneg, fb), fa);
1608
1609   // int iq = (int)fq;
1610   SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1611
1612   // fr = fabs(fr);
1613   fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1614
1615   // fb = fabs(fb);
1616   fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1617
1618   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), VT);
1619
1620   // int cv = fr >= fb;
1621   SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1622
1623   // jq = (cv ? jq : 0);
1624   jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, VT));
1625
1626   // dst = trunc/extend to legal type
1627   iq = sign ? DAG.getSExtOrTrunc(iq, DL, VT) : DAG.getZExtOrTrunc(iq, DL, VT);
1628
1629   // dst = iq + jq;
1630   SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1631
1632   // Rem needs compensation, it's easier to recompute it
1633   SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1634   Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1635
1636   SDValue Res[2] = {
1637     Div,
1638     Rem
1639   };
1640   return DAG.getMergeValues(Res, DL);
1641 }
1642
1643 void AMDGPUTargetLowering::LowerUDIVREM64(SDValue Op,
1644                                       SelectionDAG &DAG,
1645                                       SmallVectorImpl<SDValue> &Results) const {
1646   assert(Op.getValueType() == MVT::i64);
1647
1648   SDLoc DL(Op);
1649   EVT VT = Op.getValueType();
1650   EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1651
1652   SDValue one = DAG.getConstant(1, HalfVT);
1653   SDValue zero = DAG.getConstant(0, HalfVT);
1654
1655   //HiLo split
1656   SDValue LHS = Op.getOperand(0);
1657   SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, zero);
1658   SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, one);
1659
1660   SDValue RHS = Op.getOperand(1);
1661   SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, zero);
1662   SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, one);
1663
1664   if (VT == MVT::i64 &&
1665     DAG.MaskedValueIsZero(RHS, APInt::getHighBitsSet(64, 32)) &&
1666     DAG.MaskedValueIsZero(LHS, APInt::getHighBitsSet(64, 32))) {
1667
1668     SDValue Res = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1669                               LHS_Lo, RHS_Lo);
1670
1671     SDValue DIV = DAG.getNode(ISD::BUILD_PAIR, DL, VT, Res.getValue(0), zero);
1672     SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, Res.getValue(1), zero);
1673     Results.push_back(DIV);
1674     Results.push_back(REM);
1675     return;
1676   }
1677
1678   // Get Speculative values
1679   SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
1680   SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
1681
1682   SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, zero, REM_Part, LHS_Hi, ISD::SETEQ);
1683   SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, REM_Lo, zero);
1684
1685   SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, zero, DIV_Part, zero, ISD::SETEQ);
1686   SDValue DIV_Lo = zero;
1687
1688   const unsigned halfBitWidth = HalfVT.getSizeInBits();
1689
1690   for (unsigned i = 0; i < halfBitWidth; ++i) {
1691     const unsigned bitPos = halfBitWidth - i - 1;
1692     SDValue POS = DAG.getConstant(bitPos, HalfVT);
1693     // Get value of high bit
1694     // TODO: Remove the BFE part when the optimization is fixed
1695     SDValue HBit;
1696     if (halfBitWidth == 32 && Subtarget->hasBFE()) {
1697       HBit = DAG.getNode(AMDGPUISD::BFE_U32, DL, HalfVT, LHS_Lo, POS, one);
1698     } else {
1699       HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
1700       HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, one);
1701     }
1702     HBit = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, HBit);
1703
1704     // Shift
1705     REM = DAG.getNode(ISD::SHL, DL, VT, REM, DAG.getConstant(1, VT));
1706     // Add LHS high bit
1707     REM = DAG.getNode(ISD::OR, DL, VT, REM, HBit);
1708
1709     SDValue BIT = DAG.getConstant(1 << bitPos, HalfVT);
1710     SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, zero, ISD::SETUGE);
1711
1712     DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
1713
1714     // Update REM
1715     SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
1716     REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETUGE);
1717   }
1718
1719   SDValue DIV = DAG.getNode(ISD::BUILD_PAIR, DL, VT, DIV_Lo, DIV_Hi);
1720   Results.push_back(DIV);
1721   Results.push_back(REM);
1722 }
1723
1724 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1725                                            SelectionDAG &DAG) const {
1726   SDLoc DL(Op);
1727   EVT VT = Op.getValueType();
1728
1729   if (VT == MVT::i64) {
1730     SmallVector<SDValue, 2> Results;
1731     LowerUDIVREM64(Op, DAG, Results);
1732     return DAG.getMergeValues(Results, DL);
1733   }
1734
1735   SDValue Num = Op.getOperand(0);
1736   SDValue Den = Op.getOperand(1);
1737
1738   if (VT == MVT::i32) {
1739     if (DAG.MaskedValueIsZero(Num, APInt::getHighBitsSet(32, 8)) &&
1740         DAG.MaskedValueIsZero(Den, APInt::getHighBitsSet(32, 8))) {
1741       // TODO: We technically could do this for i64, but shouldn't that just be
1742       // handled by something generally reducing 64-bit division on 32-bit
1743       // values to 32-bit?
1744       return LowerDIVREM24(Op, DAG, false);
1745     }
1746   }
1747
1748   // RCP =  URECIP(Den) = 2^32 / Den + e
1749   // e is rounding error.
1750   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1751
1752   // RCP_LO = mul(RCP, Den) */
1753   SDValue RCP_LO = DAG.getNode(ISD::MUL, DL, VT, RCP, Den);
1754
1755   // RCP_HI = mulhu (RCP, Den) */
1756   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1757
1758   // NEG_RCP_LO = -RCP_LO
1759   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
1760                                                      RCP_LO);
1761
1762   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1763   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1764                                            NEG_RCP_LO, RCP_LO,
1765                                            ISD::SETEQ);
1766   // Calculate the rounding error from the URECIP instruction
1767   // E = mulhu(ABS_RCP_LO, RCP)
1768   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1769
1770   // RCP_A_E = RCP + E
1771   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1772
1773   // RCP_S_E = RCP - E
1774   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1775
1776   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1777   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, VT),
1778                                      RCP_A_E, RCP_S_E,
1779                                      ISD::SETEQ);
1780   // Quotient = mulhu(Tmp0, Num)
1781   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1782
1783   // Num_S_Remainder = Quotient * Den
1784   SDValue Num_S_Remainder = DAG.getNode(ISD::MUL, DL, VT, Quotient, Den);
1785
1786   // Remainder = Num - Num_S_Remainder
1787   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1788
1789   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1790   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1791                                                  DAG.getConstant(-1, VT),
1792                                                  DAG.getConstant(0, VT),
1793                                                  ISD::SETUGE);
1794   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1795   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1796                                                   Num_S_Remainder,
1797                                                   DAG.getConstant(-1, VT),
1798                                                   DAG.getConstant(0, VT),
1799                                                   ISD::SETUGE);
1800   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1801   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1802                                                Remainder_GE_Zero);
1803
1804   // Calculate Division result:
1805
1806   // Quotient_A_One = Quotient + 1
1807   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1808                                                          DAG.getConstant(1, VT));
1809
1810   // Quotient_S_One = Quotient - 1
1811   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1812                                                          DAG.getConstant(1, VT));
1813
1814   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1815   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1816                                      Quotient, Quotient_A_One, ISD::SETEQ);
1817
1818   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1819   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1820                             Quotient_S_One, Div, ISD::SETEQ);
1821
1822   // Calculate Rem result:
1823
1824   // Remainder_S_Den = Remainder - Den
1825   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1826
1827   // Remainder_A_Den = Remainder + Den
1828   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1829
1830   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1831   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, VT),
1832                                     Remainder, Remainder_S_Den, ISD::SETEQ);
1833
1834   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1835   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, VT),
1836                             Remainder_A_Den, Rem, ISD::SETEQ);
1837   SDValue Ops[2] = {
1838     Div,
1839     Rem
1840   };
1841   return DAG.getMergeValues(Ops, DL);
1842 }
1843
1844 SDValue AMDGPUTargetLowering::LowerSDIVREM(SDValue Op,
1845                                            SelectionDAG &DAG) const {
1846   SDLoc DL(Op);
1847   EVT VT = Op.getValueType();
1848
1849   SDValue LHS = Op.getOperand(0);
1850   SDValue RHS = Op.getOperand(1);
1851
1852   SDValue Zero = DAG.getConstant(0, VT);
1853   SDValue NegOne = DAG.getConstant(-1, VT);
1854
1855   if (VT == MVT::i32 &&
1856       DAG.ComputeNumSignBits(LHS) > 8 &&
1857       DAG.ComputeNumSignBits(RHS) > 8) {
1858     return LowerDIVREM24(Op, DAG, true);
1859   }
1860   if (VT == MVT::i64 &&
1861       DAG.ComputeNumSignBits(LHS) > 32 &&
1862       DAG.ComputeNumSignBits(RHS) > 32) {
1863     EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1864
1865     //HiLo split
1866     SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1867     SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1868     SDValue DIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1869                                  LHS_Lo, RHS_Lo);
1870     SDValue Res[2] = {
1871       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(0)),
1872       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(1))
1873     };
1874     return DAG.getMergeValues(Res, DL);
1875   }
1876
1877   SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
1878   SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
1879   SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
1880   SDValue RSign = LHSign; // Remainder sign is the same as LHS
1881
1882   LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
1883   RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
1884
1885   LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
1886   RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
1887
1888   SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
1889   SDValue Rem = Div.getValue(1);
1890
1891   Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
1892   Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
1893
1894   Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
1895   Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
1896
1897   SDValue Res[2] = {
1898     Div,
1899     Rem
1900   };
1901   return DAG.getMergeValues(Res, DL);
1902 }
1903
1904 // (frem x, y) -> (fsub x, (fmul (ftrunc (fdiv x, y)), y))
1905 SDValue AMDGPUTargetLowering::LowerFREM(SDValue Op, SelectionDAG &DAG) const {
1906   SDLoc SL(Op);
1907   EVT VT = Op.getValueType();
1908   SDValue X = Op.getOperand(0);
1909   SDValue Y = Op.getOperand(1);
1910
1911   SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y);
1912   SDValue Floor = DAG.getNode(ISD::FTRUNC, SL, VT, Div);
1913   SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Floor, Y);
1914
1915   return DAG.getNode(ISD::FSUB, SL, VT, X, Mul);
1916 }
1917
1918 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
1919   SDLoc SL(Op);
1920   SDValue Src = Op.getOperand(0);
1921
1922   // result = trunc(src)
1923   // if (src > 0.0 && src != result)
1924   //   result += 1.0
1925
1926   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1927
1928   const SDValue Zero = DAG.getConstantFP(0.0, MVT::f64);
1929   const SDValue One = DAG.getConstantFP(1.0, MVT::f64);
1930
1931   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
1932
1933   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
1934   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1935   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1936
1937   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
1938   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1939 }
1940
1941 static SDValue extractF64Exponent(SDValue Hi, SDLoc SL, SelectionDAG &DAG) {
1942   const unsigned FractBits = 52;
1943   const unsigned ExpBits = 11;
1944
1945   SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
1946                                 Hi,
1947                                 DAG.getConstant(FractBits - 32, MVT::i32),
1948                                 DAG.getConstant(ExpBits, MVT::i32));
1949   SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
1950                             DAG.getConstant(1023, MVT::i32));
1951
1952   return Exp;
1953 }
1954
1955 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
1956   SDLoc SL(Op);
1957   SDValue Src = Op.getOperand(0);
1958
1959   assert(Op.getValueType() == MVT::f64);
1960
1961   const SDValue Zero = DAG.getConstant(0, MVT::i32);
1962   const SDValue One = DAG.getConstant(1, MVT::i32);
1963
1964   SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1965
1966   // Extract the upper half, since this is where we will find the sign and
1967   // exponent.
1968   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
1969
1970   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
1971
1972   const unsigned FractBits = 52;
1973
1974   // Extract the sign bit.
1975   const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, MVT::i32);
1976   SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
1977
1978   // Extend back to to 64-bits.
1979   SDValue SignBit64 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
1980                                   Zero, SignBit);
1981   SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
1982
1983   SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
1984   const SDValue FractMask
1985     = DAG.getConstant((UINT64_C(1) << FractBits) - 1, MVT::i64);
1986
1987   SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
1988   SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
1989   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
1990
1991   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::i32);
1992
1993   const SDValue FiftyOne = DAG.getConstant(FractBits - 1, MVT::i32);
1994
1995   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1996   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1997
1998   SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
1999   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
2000
2001   return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
2002 }
2003
2004 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
2005   SDLoc SL(Op);
2006   SDValue Src = Op.getOperand(0);
2007
2008   assert(Op.getValueType() == MVT::f64);
2009
2010   APFloat C1Val(APFloat::IEEEdouble, "0x1.0p+52");
2011   SDValue C1 = DAG.getConstantFP(C1Val, MVT::f64);
2012   SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
2013
2014   SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
2015   SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
2016
2017   SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
2018
2019   APFloat C2Val(APFloat::IEEEdouble, "0x1.fffffffffffffp+51");
2020   SDValue C2 = DAG.getConstantFP(C2Val, MVT::f64);
2021
2022   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
2023   SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
2024
2025   return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
2026 }
2027
2028 SDValue AMDGPUTargetLowering::LowerFNEARBYINT(SDValue Op, SelectionDAG &DAG) const {
2029   // FNEARBYINT and FRINT are the same, except in their handling of FP
2030   // exceptions. Those aren't really meaningful for us, and OpenCL only has
2031   // rint, so just treat them as equivalent.
2032   return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
2033 }
2034
2035 // XXX - May require not supporting f32 denormals?
2036 SDValue AMDGPUTargetLowering::LowerFROUND32(SDValue Op, SelectionDAG &DAG) const {
2037   SDLoc SL(Op);
2038   SDValue X = Op.getOperand(0);
2039
2040   SDValue T = DAG.getNode(ISD::FTRUNC, SL, MVT::f32, X);
2041
2042   SDValue Diff = DAG.getNode(ISD::FSUB, SL, MVT::f32, X, T);
2043
2044   SDValue AbsDiff = DAG.getNode(ISD::FABS, SL, MVT::f32, Diff);
2045
2046   const SDValue Zero = DAG.getConstantFP(0.0, MVT::f32);
2047   const SDValue One = DAG.getConstantFP(1.0, MVT::f32);
2048   const SDValue Half = DAG.getConstantFP(0.5, MVT::f32);
2049
2050   SDValue SignOne = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f32, One, X);
2051
2052   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
2053
2054   SDValue Cmp = DAG.getSetCC(SL, SetCCVT, AbsDiff, Half, ISD::SETOGE);
2055
2056   SDValue Sel = DAG.getNode(ISD::SELECT, SL, MVT::f32, Cmp, SignOne, Zero);
2057
2058   return DAG.getNode(ISD::FADD, SL, MVT::f32, T, Sel);
2059 }
2060
2061 SDValue AMDGPUTargetLowering::LowerFROUND64(SDValue Op, SelectionDAG &DAG) const {
2062   SDLoc SL(Op);
2063   SDValue X = Op.getOperand(0);
2064
2065   SDValue L = DAG.getNode(ISD::BITCAST, SL, MVT::i64, X);
2066
2067   const SDValue Zero = DAG.getConstant(0, MVT::i32);
2068   const SDValue One = DAG.getConstant(1, MVT::i32);
2069   const SDValue NegOne = DAG.getConstant(-1, MVT::i32);
2070   const SDValue FiftyOne = DAG.getConstant(51, MVT::i32);
2071   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::i32);
2072
2073
2074   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
2075
2076   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC, One);
2077
2078   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2079
2080   const SDValue Mask = DAG.getConstant(INT64_C(0x000fffffffffffff), MVT::i64);
2081
2082   SDValue M = DAG.getNode(ISD::SRA, SL, MVT::i64, Mask, Exp);
2083   SDValue D = DAG.getNode(ISD::SRA, SL, MVT::i64,
2084                           DAG.getConstant(INT64_C(0x0008000000000000), MVT::i64),
2085                           Exp);
2086
2087   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, L, M);
2088   SDValue Tmp1 = DAG.getSetCC(SL, SetCCVT,
2089                               DAG.getConstant(0, MVT::i64), Tmp0,
2090                               ISD::SETNE);
2091
2092   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, Tmp1,
2093                              D, DAG.getConstant(0, MVT::i64));
2094   SDValue K = DAG.getNode(ISD::ADD, SL, MVT::i64, L, Tmp2);
2095
2096   K = DAG.getNode(ISD::AND, SL, MVT::i64, K, DAG.getNOT(SL, M, MVT::i64));
2097   K = DAG.getNode(ISD::BITCAST, SL, MVT::f64, K);
2098
2099   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2100   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2101   SDValue ExpEqNegOne = DAG.getSetCC(SL, SetCCVT, NegOne, Exp, ISD::SETEQ);
2102
2103   SDValue Mag = DAG.getNode(ISD::SELECT, SL, MVT::f64,
2104                             ExpEqNegOne,
2105                             DAG.getConstantFP(1.0, MVT::f64),
2106                             DAG.getConstantFP(0.0, MVT::f64));
2107
2108   SDValue S = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, Mag, X);
2109
2110   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpLt0, S, K);
2111   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpGt51, X, K);
2112
2113   return K;
2114 }
2115
2116 SDValue AMDGPUTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
2117   EVT VT = Op.getValueType();
2118
2119   if (VT == MVT::f32)
2120     return LowerFROUND32(Op, DAG);
2121
2122   if (VT == MVT::f64)
2123     return LowerFROUND64(Op, DAG);
2124
2125   llvm_unreachable("unhandled type");
2126 }
2127
2128 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
2129   SDLoc SL(Op);
2130   SDValue Src = Op.getOperand(0);
2131
2132   // result = trunc(src);
2133   // if (src < 0.0 && src != result)
2134   //   result += -1.0.
2135
2136   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2137
2138   const SDValue Zero = DAG.getConstantFP(0.0, MVT::f64);
2139   const SDValue NegOne = DAG.getConstantFP(-1.0, MVT::f64);
2140
2141   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f64);
2142
2143   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
2144   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2145   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2146
2147   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
2148   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2149 }
2150
2151 SDValue AMDGPUTargetLowering::LowerINT_TO_FP64(SDValue Op, SelectionDAG &DAG,
2152                                                bool Signed) const {
2153   SDLoc SL(Op);
2154   SDValue Src = Op.getOperand(0);
2155
2156   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2157
2158   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2159                            DAG.getConstant(0, MVT::i32));
2160   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2161                            DAG.getConstant(1, MVT::i32));
2162
2163   SDValue CvtHi = DAG.getNode(Signed ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
2164                               SL, MVT::f64, Hi);
2165
2166   SDValue CvtLo = DAG.getNode(ISD::UINT_TO_FP, SL, MVT::f64, Lo);
2167
2168   SDValue LdExp = DAG.getNode(AMDGPUISD::LDEXP, SL, MVT::f64, CvtHi,
2169                               DAG.getConstant(32, MVT::i32));
2170
2171   return DAG.getNode(ISD::FADD, SL, MVT::f64, LdExp, CvtLo);
2172 }
2173
2174 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
2175                                                SelectionDAG &DAG) const {
2176   SDValue S0 = Op.getOperand(0);
2177   if (S0.getValueType() != MVT::i64)
2178     return SDValue();
2179
2180   EVT DestVT = Op.getValueType();
2181   if (DestVT == MVT::f64)
2182     return LowerINT_TO_FP64(Op, DAG, false);
2183
2184   assert(DestVT == MVT::f32);
2185
2186   SDLoc DL(Op);
2187
2188   // f32 uint_to_fp i64
2189   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
2190                            DAG.getConstant(0, MVT::i32));
2191   SDValue FloatLo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Lo);
2192   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, S0,
2193                            DAG.getConstant(1, MVT::i32));
2194   SDValue FloatHi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, Hi);
2195   FloatHi = DAG.getNode(ISD::FMUL, DL, MVT::f32, FloatHi,
2196                         DAG.getConstantFP(4294967296.0f, MVT::f32)); // 2^32
2197   return DAG.getNode(ISD::FADD, DL, MVT::f32, FloatLo, FloatHi);
2198 }
2199
2200 SDValue AMDGPUTargetLowering::LowerSINT_TO_FP(SDValue Op,
2201                                               SelectionDAG &DAG) const {
2202   SDValue Src = Op.getOperand(0);
2203   if (Src.getValueType() == MVT::i64 && Op.getValueType() == MVT::f64)
2204     return LowerINT_TO_FP64(Op, DAG, true);
2205
2206   return SDValue();
2207 }
2208
2209 SDValue AMDGPUTargetLowering::LowerFP64_TO_INT(SDValue Op, SelectionDAG &DAG,
2210                                                bool Signed) const {
2211   SDLoc SL(Op);
2212
2213   SDValue Src = Op.getOperand(0);
2214
2215   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2216
2217   SDValue K0
2218     = DAG.getConstantFP(BitsToDouble(UINT64_C(0x3df0000000000000)), MVT::f64);
2219   SDValue K1
2220     = DAG.getConstantFP(BitsToDouble(UINT64_C(0xc1f0000000000000)), MVT::f64);
2221
2222   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, Trunc, K0);
2223
2224   SDValue FloorMul = DAG.getNode(ISD::FFLOOR, SL, MVT::f64, Mul);
2225
2226
2227   SDValue Fma = DAG.getNode(ISD::FMA, SL, MVT::f64, FloorMul, K1, Trunc);
2228
2229   SDValue Hi = DAG.getNode(Signed ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, SL,
2230                            MVT::i32, FloorMul);
2231   SDValue Lo = DAG.getNode(ISD::FP_TO_UINT, SL, MVT::i32, Fma);
2232
2233   SDValue Result = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Lo, Hi);
2234
2235   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Result);
2236 }
2237
2238 SDValue AMDGPUTargetLowering::LowerFP_TO_SINT(SDValue Op,
2239                                               SelectionDAG &DAG) const {
2240   SDValue Src = Op.getOperand(0);
2241
2242   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2243     return LowerFP64_TO_INT(Op, DAG, true);
2244
2245   return SDValue();
2246 }
2247
2248 SDValue AMDGPUTargetLowering::LowerFP_TO_UINT(SDValue Op,
2249                                               SelectionDAG &DAG) const {
2250   SDValue Src = Op.getOperand(0);
2251
2252   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2253     return LowerFP64_TO_INT(Op, DAG, false);
2254
2255   return SDValue();
2256 }
2257
2258 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
2259                                                      SelectionDAG &DAG) const {
2260   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2261   MVT VT = Op.getSimpleValueType();
2262   MVT ScalarVT = VT.getScalarType();
2263
2264   if (!VT.isVector())
2265     return SDValue();
2266
2267   SDValue Src = Op.getOperand(0);
2268   SDLoc DL(Op);
2269
2270   // TODO: Don't scalarize on Evergreen?
2271   unsigned NElts = VT.getVectorNumElements();
2272   SmallVector<SDValue, 8> Args;
2273   DAG.ExtractVectorElements(Src, Args, 0, NElts);
2274
2275   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
2276   for (unsigned I = 0; I < NElts; ++I)
2277     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
2278
2279   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args);
2280 }
2281
2282 //===----------------------------------------------------------------------===//
2283 // Custom DAG optimizations
2284 //===----------------------------------------------------------------------===//
2285
2286 static bool isU24(SDValue Op, SelectionDAG &DAG) {
2287   APInt KnownZero, KnownOne;
2288   EVT VT = Op.getValueType();
2289   DAG.computeKnownBits(Op, KnownZero, KnownOne);
2290
2291   return (VT.getSizeInBits() - KnownZero.countLeadingOnes()) <= 24;
2292 }
2293
2294 static bool isI24(SDValue Op, SelectionDAG &DAG) {
2295   EVT VT = Op.getValueType();
2296
2297   // In order for this to be a signed 24-bit value, bit 23, must
2298   // be a sign bit.
2299   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
2300                                      // as unsigned 24-bit values.
2301          (VT.getSizeInBits() - DAG.ComputeNumSignBits(Op)) < 24;
2302 }
2303
2304 static void simplifyI24(SDValue Op, TargetLowering::DAGCombinerInfo &DCI) {
2305
2306   SelectionDAG &DAG = DCI.DAG;
2307   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2308   EVT VT = Op.getValueType();
2309
2310   APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
2311   APInt KnownZero, KnownOne;
2312   TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
2313   if (TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
2314     DCI.CommitTargetLoweringOpt(TLO);
2315 }
2316
2317 template <typename IntTy>
2318 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0,
2319                                uint32_t Offset, uint32_t Width) {
2320   if (Width + Offset < 32) {
2321     uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
2322     IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
2323     return DAG.getConstant(Result, MVT::i32);
2324   }
2325
2326   return DAG.getConstant(Src0 >> Offset, MVT::i32);
2327 }
2328
2329 static bool usesAllNormalStores(SDNode *LoadVal) {
2330   for (SDNode::use_iterator I = LoadVal->use_begin(); !I.atEnd(); ++I) {
2331     if (!ISD::isNormalStore(*I))
2332       return false;
2333   }
2334
2335   return true;
2336 }
2337
2338 // If we have a copy of an illegal type, replace it with a load / store of an
2339 // equivalently sized legal type. This avoids intermediate bit pack / unpack
2340 // instructions emitted when handling extloads and truncstores. Ideally we could
2341 // recognize the pack / unpack pattern to eliminate it.
2342 SDValue AMDGPUTargetLowering::performStoreCombine(SDNode *N,
2343                                                   DAGCombinerInfo &DCI) const {
2344   if (!DCI.isBeforeLegalize())
2345     return SDValue();
2346
2347   StoreSDNode *SN = cast<StoreSDNode>(N);
2348   SDValue Value = SN->getValue();
2349   EVT VT = Value.getValueType();
2350
2351   if (isTypeLegal(VT) || SN->isVolatile() ||
2352       !ISD::isNormalLoad(Value.getNode()) || VT.getSizeInBits() < 8)
2353     return SDValue();
2354
2355   LoadSDNode *LoadVal = cast<LoadSDNode>(Value);
2356   if (LoadVal->isVolatile() || !usesAllNormalStores(LoadVal))
2357     return SDValue();
2358
2359   EVT MemVT = LoadVal->getMemoryVT();
2360
2361   SDLoc SL(N);
2362   SelectionDAG &DAG = DCI.DAG;
2363   EVT LoadVT = getEquivalentMemType(*DAG.getContext(), MemVT);
2364
2365   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
2366                                 LoadVT, SL,
2367                                 LoadVal->getChain(),
2368                                 LoadVal->getBasePtr(),
2369                                 LoadVal->getOffset(),
2370                                 LoadVT,
2371                                 LoadVal->getMemOperand());
2372
2373   SDValue CastLoad = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad.getValue(0));
2374   DCI.CombineTo(LoadVal, CastLoad, NewLoad.getValue(1), false);
2375
2376   return DAG.getStore(SN->getChain(), SL, NewLoad,
2377                       SN->getBasePtr(), SN->getMemOperand());
2378 }
2379
2380 SDValue AMDGPUTargetLowering::performMulCombine(SDNode *N,
2381                                                 DAGCombinerInfo &DCI) const {
2382   EVT VT = N->getValueType(0);
2383
2384   if (VT.isVector() || VT.getSizeInBits() > 32)
2385     return SDValue();
2386
2387   SelectionDAG &DAG = DCI.DAG;
2388   SDLoc DL(N);
2389
2390   SDValue N0 = N->getOperand(0);
2391   SDValue N1 = N->getOperand(1);
2392   SDValue Mul;
2393
2394   if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
2395     N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
2396     N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
2397     Mul = DAG.getNode(AMDGPUISD::MUL_U24, DL, MVT::i32, N0, N1);
2398   } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
2399     N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
2400     N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
2401     Mul = DAG.getNode(AMDGPUISD::MUL_I24, DL, MVT::i32, N0, N1);
2402   } else {
2403     return SDValue();
2404   }
2405
2406   // We need to use sext even for MUL_U24, because MUL_U24 is used
2407   // for signed multiply of 8 and 16-bit types.
2408   return DAG.getSExtOrTrunc(Mul, DL, VT);
2409 }
2410
2411 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
2412                                                 DAGCombinerInfo &DCI) const {
2413   SelectionDAG &DAG = DCI.DAG;
2414   SDLoc DL(N);
2415
2416   switch(N->getOpcode()) {
2417     default: break;
2418     case ISD::MUL:
2419       return performMulCombine(N, DCI);
2420     case AMDGPUISD::MUL_I24:
2421     case AMDGPUISD::MUL_U24: {
2422       SDValue N0 = N->getOperand(0);
2423       SDValue N1 = N->getOperand(1);
2424       simplifyI24(N0, DCI);
2425       simplifyI24(N1, DCI);
2426       return SDValue();
2427     }
2428   case ISD::SELECT: {
2429     SDValue Cond = N->getOperand(0);
2430     if (Cond.getOpcode() == ISD::SETCC && Cond.hasOneUse()) {
2431       SDLoc DL(N);
2432       EVT VT = N->getValueType(0);
2433       SDValue LHS = Cond.getOperand(0);
2434       SDValue RHS = Cond.getOperand(1);
2435       SDValue CC = Cond.getOperand(2);
2436
2437       SDValue True = N->getOperand(1);
2438       SDValue False = N->getOperand(2);
2439
2440       if (VT == MVT::f32)
2441         return CombineFMinMaxLegacy(DL, VT, LHS, RHS, True, False, CC, DCI);
2442
2443       // TODO: Implement min / max Evergreen instructions.
2444       if (VT == MVT::i32 &&
2445           Subtarget->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
2446         return CombineIMinMax(DL, VT, LHS, RHS, True, False, CC, DAG);
2447       }
2448     }
2449
2450     break;
2451   }
2452   case AMDGPUISD::BFE_I32:
2453   case AMDGPUISD::BFE_U32: {
2454     assert(!N->getValueType(0).isVector() &&
2455            "Vector handling of BFE not implemented");
2456     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
2457     if (!Width)
2458       break;
2459
2460     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
2461     if (WidthVal == 0)
2462       return DAG.getConstant(0, MVT::i32);
2463
2464     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
2465     if (!Offset)
2466       break;
2467
2468     SDValue BitsFrom = N->getOperand(0);
2469     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
2470
2471     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
2472
2473     if (OffsetVal == 0) {
2474       // This is already sign / zero extended, so try to fold away extra BFEs.
2475       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
2476
2477       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
2478       if (OpSignBits >= SignBits)
2479         return BitsFrom;
2480
2481       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
2482       if (Signed) {
2483         // This is a sign_extend_inreg. Replace it to take advantage of existing
2484         // DAG Combines. If not eliminated, we will match back to BFE during
2485         // selection.
2486
2487         // TODO: The sext_inreg of extended types ends, although we can could
2488         // handle them in a single BFE.
2489         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
2490                            DAG.getValueType(SmallVT));
2491       }
2492
2493       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
2494     }
2495
2496     if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(BitsFrom)) {
2497       if (Signed) {
2498         return constantFoldBFE<int32_t>(DAG,
2499                                         CVal->getSExtValue(),
2500                                         OffsetVal,
2501                                         WidthVal);
2502       }
2503
2504       return constantFoldBFE<uint32_t>(DAG,
2505                                        CVal->getZExtValue(),
2506                                        OffsetVal,
2507                                        WidthVal);
2508     }
2509
2510     if ((OffsetVal + WidthVal) >= 32) {
2511       SDValue ShiftVal = DAG.getConstant(OffsetVal, MVT::i32);
2512       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2513                          BitsFrom, ShiftVal);
2514     }
2515
2516     if (BitsFrom.hasOneUse()) {
2517       APInt Demanded = APInt::getBitsSet(32,
2518                                          OffsetVal,
2519                                          OffsetVal + WidthVal);
2520
2521       APInt KnownZero, KnownOne;
2522       TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2523                                             !DCI.isBeforeLegalizeOps());
2524       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2525       if (TLO.ShrinkDemandedConstant(BitsFrom, Demanded) ||
2526           TLI.SimplifyDemandedBits(BitsFrom, Demanded,
2527                                    KnownZero, KnownOne, TLO)) {
2528         DCI.CommitTargetLoweringOpt(TLO);
2529       }
2530     }
2531
2532     break;
2533   }
2534
2535   case ISD::STORE:
2536     return performStoreCombine(N, DCI);
2537   }
2538   return SDValue();
2539 }
2540
2541 //===----------------------------------------------------------------------===//
2542 // Helper functions
2543 //===----------------------------------------------------------------------===//
2544
2545 void AMDGPUTargetLowering::getOriginalFunctionArgs(
2546                                SelectionDAG &DAG,
2547                                const Function *F,
2548                                const SmallVectorImpl<ISD::InputArg> &Ins,
2549                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
2550
2551   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
2552     if (Ins[i].ArgVT == Ins[i].VT) {
2553       OrigIns.push_back(Ins[i]);
2554       continue;
2555     }
2556
2557     EVT VT;
2558     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
2559       // Vector has been split into scalars.
2560       VT = Ins[i].ArgVT.getVectorElementType();
2561     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
2562                Ins[i].ArgVT.getVectorElementType() !=
2563                Ins[i].VT.getVectorElementType()) {
2564       // Vector elements have been promoted
2565       VT = Ins[i].ArgVT;
2566     } else {
2567       // Vector has been spilt into smaller vectors.
2568       VT = Ins[i].VT;
2569     }
2570
2571     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
2572                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
2573     OrigIns.push_back(Arg);
2574   }
2575 }
2576
2577 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
2578   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
2579     return CFP->isExactlyValue(1.0);
2580   }
2581   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2582     return C->isAllOnesValue();
2583   }
2584   return false;
2585 }
2586
2587 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
2588   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
2589     return CFP->getValueAPF().isZero();
2590   }
2591   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2592     return C->isNullValue();
2593   }
2594   return false;
2595 }
2596
2597 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2598                                                   const TargetRegisterClass *RC,
2599                                                    unsigned Reg, EVT VT) const {
2600   MachineFunction &MF = DAG.getMachineFunction();
2601   MachineRegisterInfo &MRI = MF.getRegInfo();
2602   unsigned VirtualRegister;
2603   if (!MRI.isLiveIn(Reg)) {
2604     VirtualRegister = MRI.createVirtualRegister(RC);
2605     MRI.addLiveIn(Reg, VirtualRegister);
2606   } else {
2607     VirtualRegister = MRI.getLiveInVirtReg(Reg);
2608   }
2609   return DAG.getRegister(VirtualRegister, VT);
2610 }
2611
2612 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
2613
2614 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
2615   switch (Opcode) {
2616   default: return nullptr;
2617   // AMDIL DAG nodes
2618   NODE_NAME_CASE(CALL);
2619   NODE_NAME_CASE(UMUL);
2620   NODE_NAME_CASE(RET_FLAG);
2621   NODE_NAME_CASE(BRANCH_COND);
2622
2623   // AMDGPU DAG nodes
2624   NODE_NAME_CASE(DWORDADDR)
2625   NODE_NAME_CASE(FRACT)
2626   NODE_NAME_CASE(CLAMP)
2627   NODE_NAME_CASE(MAD)
2628   NODE_NAME_CASE(FMAX_LEGACY)
2629   NODE_NAME_CASE(SMAX)
2630   NODE_NAME_CASE(UMAX)
2631   NODE_NAME_CASE(FMIN_LEGACY)
2632   NODE_NAME_CASE(SMIN)
2633   NODE_NAME_CASE(UMIN)
2634   NODE_NAME_CASE(FMAX3)
2635   NODE_NAME_CASE(SMAX3)
2636   NODE_NAME_CASE(UMAX3)
2637   NODE_NAME_CASE(FMIN3)
2638   NODE_NAME_CASE(SMIN3)
2639   NODE_NAME_CASE(UMIN3)
2640   NODE_NAME_CASE(URECIP)
2641   NODE_NAME_CASE(DIV_SCALE)
2642   NODE_NAME_CASE(DIV_FMAS)
2643   NODE_NAME_CASE(DIV_FIXUP)
2644   NODE_NAME_CASE(TRIG_PREOP)
2645   NODE_NAME_CASE(RCP)
2646   NODE_NAME_CASE(RSQ)
2647   NODE_NAME_CASE(RSQ_LEGACY)
2648   NODE_NAME_CASE(RSQ_CLAMPED)
2649   NODE_NAME_CASE(LDEXP)
2650   NODE_NAME_CASE(FP_CLASS)
2651   NODE_NAME_CASE(DOT4)
2652   NODE_NAME_CASE(BFE_U32)
2653   NODE_NAME_CASE(BFE_I32)
2654   NODE_NAME_CASE(BFI)
2655   NODE_NAME_CASE(BFM)
2656   NODE_NAME_CASE(BREV)
2657   NODE_NAME_CASE(MUL_U24)
2658   NODE_NAME_CASE(MUL_I24)
2659   NODE_NAME_CASE(MAD_U24)
2660   NODE_NAME_CASE(MAD_I24)
2661   NODE_NAME_CASE(EXPORT)
2662   NODE_NAME_CASE(CONST_ADDRESS)
2663   NODE_NAME_CASE(REGISTER_LOAD)
2664   NODE_NAME_CASE(REGISTER_STORE)
2665   NODE_NAME_CASE(LOAD_CONSTANT)
2666   NODE_NAME_CASE(LOAD_INPUT)
2667   NODE_NAME_CASE(SAMPLE)
2668   NODE_NAME_CASE(SAMPLEB)
2669   NODE_NAME_CASE(SAMPLED)
2670   NODE_NAME_CASE(SAMPLEL)
2671   NODE_NAME_CASE(CVT_F32_UBYTE0)
2672   NODE_NAME_CASE(CVT_F32_UBYTE1)
2673   NODE_NAME_CASE(CVT_F32_UBYTE2)
2674   NODE_NAME_CASE(CVT_F32_UBYTE3)
2675   NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
2676   NODE_NAME_CASE(CONST_DATA_PTR)
2677   NODE_NAME_CASE(STORE_MSKOR)
2678   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
2679   }
2680 }
2681
2682 SDValue AMDGPUTargetLowering::getRsqrtEstimate(SDValue Operand,
2683                                                DAGCombinerInfo &DCI,
2684                                                unsigned &RefinementSteps,
2685                                                bool &UseOneConstNR) const {
2686   SelectionDAG &DAG = DCI.DAG;
2687   EVT VT = Operand.getValueType();
2688
2689   if (VT == MVT::f32) {
2690     RefinementSteps = 0;
2691     return DAG.getNode(AMDGPUISD::RSQ, SDLoc(Operand), VT, Operand);
2692   }
2693
2694   // TODO: There is also f64 rsq instruction, but the documentation is less
2695   // clear on its precision.
2696
2697   return SDValue();
2698 }
2699
2700 SDValue AMDGPUTargetLowering::getRecipEstimate(SDValue Operand,
2701                                                DAGCombinerInfo &DCI,
2702                                                unsigned &RefinementSteps) const {
2703   SelectionDAG &DAG = DCI.DAG;
2704   EVT VT = Operand.getValueType();
2705
2706   if (VT == MVT::f32) {
2707     // Reciprocal, < 1 ulp error.
2708     //
2709     // This reciprocal approximation converges to < 0.5 ulp error with one
2710     // newton rhapson performed with two fused multiple adds (FMAs).
2711
2712     RefinementSteps = 0;
2713     return DAG.getNode(AMDGPUISD::RCP, SDLoc(Operand), VT, Operand);
2714   }
2715
2716   // TODO: There is also f64 rcp instruction, but the documentation is less
2717   // clear on its precision.
2718
2719   return SDValue();
2720 }
2721
2722 static void computeKnownBitsForMinMax(const SDValue Op0,
2723                                       const SDValue Op1,
2724                                       APInt &KnownZero,
2725                                       APInt &KnownOne,
2726                                       const SelectionDAG &DAG,
2727                                       unsigned Depth) {
2728   APInt Op0Zero, Op0One;
2729   APInt Op1Zero, Op1One;
2730   DAG.computeKnownBits(Op0, Op0Zero, Op0One, Depth);
2731   DAG.computeKnownBits(Op1, Op1Zero, Op1One, Depth);
2732
2733   KnownZero = Op0Zero & Op1Zero;
2734   KnownOne = Op0One & Op1One;
2735 }
2736
2737 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
2738   const SDValue Op,
2739   APInt &KnownZero,
2740   APInt &KnownOne,
2741   const SelectionDAG &DAG,
2742   unsigned Depth) const {
2743
2744   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
2745
2746   APInt KnownZero2;
2747   APInt KnownOne2;
2748   unsigned Opc = Op.getOpcode();
2749
2750   switch (Opc) {
2751   default:
2752     break;
2753   case ISD::INTRINSIC_WO_CHAIN: {
2754     // FIXME: The intrinsic should just use the node.
2755     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
2756     case AMDGPUIntrinsic::AMDGPU_imax:
2757     case AMDGPUIntrinsic::AMDGPU_umax:
2758     case AMDGPUIntrinsic::AMDGPU_imin:
2759     case AMDGPUIntrinsic::AMDGPU_umin:
2760       computeKnownBitsForMinMax(Op.getOperand(1), Op.getOperand(2),
2761                                 KnownZero, KnownOne, DAG, Depth);
2762       break;
2763     default:
2764       break;
2765     }
2766
2767     break;
2768   }
2769   case AMDGPUISD::SMAX:
2770   case AMDGPUISD::UMAX:
2771   case AMDGPUISD::SMIN:
2772   case AMDGPUISD::UMIN:
2773     computeKnownBitsForMinMax(Op.getOperand(0), Op.getOperand(1),
2774                               KnownZero, KnownOne, DAG, Depth);
2775     break;
2776
2777   case AMDGPUISD::BFE_I32:
2778   case AMDGPUISD::BFE_U32: {
2779     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2780     if (!CWidth)
2781       return;
2782
2783     unsigned BitWidth = 32;
2784     uint32_t Width = CWidth->getZExtValue() & 0x1f;
2785
2786     if (Opc == AMDGPUISD::BFE_U32)
2787       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
2788
2789     break;
2790   }
2791   }
2792 }
2793
2794 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
2795   SDValue Op,
2796   const SelectionDAG &DAG,
2797   unsigned Depth) const {
2798   switch (Op.getOpcode()) {
2799   case AMDGPUISD::BFE_I32: {
2800     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2801     if (!Width)
2802       return 1;
2803
2804     unsigned SignBits = 32 - Width->getZExtValue() + 1;
2805     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2806     if (!Offset || !Offset->isNullValue())
2807       return SignBits;
2808
2809     // TODO: Could probably figure something out with non-0 offsets.
2810     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
2811     return std::max(SignBits, Op0SignBits);
2812   }
2813
2814   case AMDGPUISD::BFE_U32: {
2815     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2816     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
2817   }
2818
2819   default:
2820     return 1;
2821   }
2822 }