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