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