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