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