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