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