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