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