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