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