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