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