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