1 //===-- AMDGPUISelLowering.cpp - AMDGPU Common DAG lowering functions -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief This is the parent TargetLowering class for hardware code gen
12 /// targets.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "AMDGPUISelLowering.h"
17 #include "AMDGPU.h"
18 #include "AMDGPUFrameLowering.h"
19 #include "AMDGPUIntrinsicInfo.h"
20 #include "AMDGPURegisterInfo.h"
21 #include "AMDGPUSubtarget.h"
22 #include "R600MachineFunctionInfo.h"
23 #include "SIMachineFunctionInfo.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "SIInstrInfo.h"
32 using namespace llvm;
33 
34 static bool allocateStack(unsigned ValNo, MVT ValVT, MVT LocVT,
35                       CCValAssign::LocInfo LocInfo,
36                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
37   unsigned Offset = State.AllocateStack(ValVT.getStoreSize(),
38                                         ArgFlags.getOrigAlign());
39   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
40 
41   return true;
42 }
43 
44 #include "AMDGPUGenCallingConv.inc"
45 
46 // Find a larger type to do a load / store of a vector with.
47 EVT AMDGPUTargetLowering::getEquivalentMemType(LLVMContext &Ctx, EVT VT) {
48   unsigned StoreSize = VT.getStoreSizeInBits();
49   if (StoreSize <= 32)
50     return EVT::getIntegerVT(Ctx, StoreSize);
51 
52   assert(StoreSize % 32 == 0 && "Store size not a multiple of 32");
53   return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
54 }
55 
56 // Type for a vector that will be loaded to.
57 EVT AMDGPUTargetLowering::getEquivalentLoadRegType(LLVMContext &Ctx, EVT VT) {
58   unsigned StoreSize = VT.getStoreSizeInBits();
59   if (StoreSize <= 32)
60     return EVT::getIntegerVT(Ctx, 32);
61 
62   return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
63 }
64 
65 AMDGPUTargetLowering::AMDGPUTargetLowering(TargetMachine &TM,
66                                            const AMDGPUSubtarget &STI)
67     : TargetLowering(TM), Subtarget(&STI) {
68   setOperationAction(ISD::Constant, MVT::i32, Legal);
69   setOperationAction(ISD::Constant, MVT::i64, Legal);
70   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
71   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
72 
73   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
74   setOperationAction(ISD::BRIND, MVT::Other, Expand);
75 
76   // This is totally unsupported, just custom lower to produce an error.
77   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
78 
79   // We need to custom lower some of the intrinsics
80   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
81 
82   // Library functions.  These default to Expand, but we have instructions
83   // for them.
84   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
85   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
86   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
87   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
88   setOperationAction(ISD::FABS,   MVT::f32, Legal);
89   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
90   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
91   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
92   setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
93   setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
94 
95   setOperationAction(ISD::FROUND, MVT::f32, Custom);
96   setOperationAction(ISD::FROUND, MVT::f64, Custom);
97 
98   setOperationAction(ISD::FREM, MVT::f32, Custom);
99   setOperationAction(ISD::FREM, MVT::f64, Custom);
100 
101   // v_mad_f32 does not support denormals according to some sources.
102   if (!Subtarget->hasFP32Denormals())
103     setOperationAction(ISD::FMAD, MVT::f32, Legal);
104 
105   // Expand to fneg + fadd.
106   setOperationAction(ISD::FSUB, MVT::f64, Expand);
107 
108   // Lower floating point store/load to integer store/load to reduce the number
109   // of patterns in tablegen.
110   setOperationAction(ISD::STORE, MVT::f32, Promote);
111   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
112 
113   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
114   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
115 
116   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
117   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
118 
119   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
120   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
121 
122   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
123   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
124 
125   setOperationAction(ISD::STORE, MVT::f64, Promote);
126   AddPromotedToType(ISD::STORE, MVT::f64, MVT::i64);
127 
128   setOperationAction(ISD::STORE, MVT::v2f64, Promote);
129   AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v2i64);
130 
131   // Custom lowering of vector stores is required for local address space
132   // stores.
133   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
134 
135   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
136   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
137   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Custom);
138 
139   // XXX: This can be change to Custom, once ExpandVectorStores can
140   // handle 64-bit stores.
141   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
142 
143   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i8, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
146   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
147   setTruncStoreAction(MVT::v4i64, MVT::v4i1, Expand);
148 
149 
150   setOperationAction(ISD::LOAD, MVT::f32, Promote);
151   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
152 
153   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
154   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
155 
156   setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
157   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
158 
159   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
160   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
161 
162   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
163   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
164 
165   setOperationAction(ISD::LOAD, MVT::f64, Promote);
166   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::i64);
167 
168   setOperationAction(ISD::LOAD, MVT::v2f64, Promote);
169   AddPromotedToType(ISD::LOAD, MVT::v2f64, MVT::v2i64);
170 
171   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
172   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
173   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
174   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
175   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
176   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
177   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
178   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
179   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
180   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
181 
182   // There are no 64-bit extloads. These should be done as a 32-bit extload and
183   // an extension to 64-bit.
184   for (MVT VT : MVT::integer_valuetypes()) {
185     setLoadExtAction(ISD::EXTLOAD, MVT::i64, VT, Expand);
186     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, VT, Expand);
187     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, VT, Expand);
188   }
189 
190   for (MVT VT : MVT::integer_vector_valuetypes()) {
191     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Expand);
192     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Expand);
193     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i8, Expand);
194     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Expand);
195     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Expand);
196     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i8, Expand);
197     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Expand);
198     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Expand);
199     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i16, Expand);
200     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Expand);
201     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Expand);
202     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i16, Expand);
203   }
204 
205   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
206 
207   if (Subtarget->getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
208     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
209     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
210     setOperationAction(ISD::FRINT, MVT::f64, Custom);
211     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
212   }
213 
214   if (!Subtarget->hasBFI()) {
215     // fcopysign can be done in a single instruction with BFI.
216     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
217     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
218   }
219 
220   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
221 
222   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
223   setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, MVT::v2f16, Expand);
224   setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Expand);
225   setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Expand);
226 
227   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
228   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
229   setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Expand);
230   setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Expand);
231 
232   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
233   setTruncStoreAction(MVT::v2f32, MVT::v2f16, Expand);
234   setTruncStoreAction(MVT::v4f32, MVT::v4f16, Expand);
235   setTruncStoreAction(MVT::v8f32, MVT::v8f16, Expand);
236 
237   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
238   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
239 
240   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
241   for (MVT VT : ScalarIntVTs) {
242     setOperationAction(ISD::SREM, VT, Expand);
243     setOperationAction(ISD::SDIV, VT, Expand);
244 
245     // GPU does not have divrem function for signed or unsigned.
246     setOperationAction(ISD::SDIVREM, VT, Custom);
247     setOperationAction(ISD::UDIVREM, VT, Custom);
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   // The hardware supports 32-bit ROTR, but not ROTL.
265   setOperationAction(ISD::ROTL, MVT::i32, Expand);
266   setOperationAction(ISD::ROTL, MVT::i64, Expand);
267   setOperationAction(ISD::ROTR, MVT::i64, Expand);
268 
269   setOperationAction(ISD::MUL, MVT::i64, Expand);
270   setOperationAction(ISD::MULHU, MVT::i64, Expand);
271   setOperationAction(ISD::MULHS, MVT::i64, Expand);
272   setOperationAction(ISD::UDIV, MVT::i32, Expand);
273   setOperationAction(ISD::UREM, MVT::i32, Expand);
274   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
275   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
276   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
277   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
278   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
279 
280   setOperationAction(ISD::SMIN, MVT::i32, Legal);
281   setOperationAction(ISD::UMIN, MVT::i32, Legal);
282   setOperationAction(ISD::SMAX, MVT::i32, Legal);
283   setOperationAction(ISD::UMAX, MVT::i32, Legal);
284 
285   if (Subtarget->hasFFBH())
286     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
287   else
288     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
289 
290   if (!Subtarget->hasFFBL())
291     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
292 
293   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
294 
295   setOperationAction(ISD::CTLZ, MVT::i64, Custom);
296   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
297 
298   static const MVT::SimpleValueType VectorIntTypes[] = {
299     MVT::v2i32, MVT::v4i32
300   };
301 
302   for (MVT VT : VectorIntTypes) {
303     // Expand the following operations for the current type by default.
304     setOperationAction(ISD::ADD,  VT, Expand);
305     setOperationAction(ISD::AND,  VT, Expand);
306     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
307     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
308     setOperationAction(ISD::MUL,  VT, Expand);
309     setOperationAction(ISD::OR,   VT, Expand);
310     setOperationAction(ISD::SHL,  VT, Expand);
311     setOperationAction(ISD::SRA,  VT, Expand);
312     setOperationAction(ISD::SRL,  VT, Expand);
313     setOperationAction(ISD::ROTL, VT, Expand);
314     setOperationAction(ISD::ROTR, VT, Expand);
315     setOperationAction(ISD::SUB,  VT, Expand);
316     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
317     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
318     setOperationAction(ISD::SDIV, VT, Expand);
319     setOperationAction(ISD::UDIV, VT, Expand);
320     setOperationAction(ISD::SREM, VT, Expand);
321     setOperationAction(ISD::UREM, VT, Expand);
322     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
323     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
324     setOperationAction(ISD::SDIVREM, VT, Custom);
325     setOperationAction(ISD::UDIVREM, VT, Expand);
326     setOperationAction(ISD::ADDC, VT, Expand);
327     setOperationAction(ISD::SUBC, VT, Expand);
328     setOperationAction(ISD::ADDE, VT, Expand);
329     setOperationAction(ISD::SUBE, VT, Expand);
330     setOperationAction(ISD::SELECT, VT, Expand);
331     setOperationAction(ISD::VSELECT, VT, Expand);
332     setOperationAction(ISD::SELECT_CC, VT, Expand);
333     setOperationAction(ISD::XOR,  VT, Expand);
334     setOperationAction(ISD::BSWAP, VT, Expand);
335     setOperationAction(ISD::CTPOP, VT, Expand);
336     setOperationAction(ISD::CTTZ, VT, Expand);
337     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
338     setOperationAction(ISD::CTLZ, VT, Expand);
339     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
340     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
341   }
342 
343   static const MVT::SimpleValueType FloatVectorTypes[] = {
344     MVT::v2f32, MVT::v4f32
345   };
346 
347   for (MVT VT : FloatVectorTypes) {
348     setOperationAction(ISD::FABS, VT, Expand);
349     setOperationAction(ISD::FMINNUM, VT, Expand);
350     setOperationAction(ISD::FMAXNUM, VT, Expand);
351     setOperationAction(ISD::FADD, VT, Expand);
352     setOperationAction(ISD::FCEIL, VT, Expand);
353     setOperationAction(ISD::FCOS, VT, Expand);
354     setOperationAction(ISD::FDIV, VT, Expand);
355     setOperationAction(ISD::FEXP2, VT, Expand);
356     setOperationAction(ISD::FLOG2, VT, Expand);
357     setOperationAction(ISD::FREM, VT, Expand);
358     setOperationAction(ISD::FPOW, VT, Expand);
359     setOperationAction(ISD::FFLOOR, VT, Expand);
360     setOperationAction(ISD::FTRUNC, VT, Expand);
361     setOperationAction(ISD::FMUL, VT, Expand);
362     setOperationAction(ISD::FMA, VT, Expand);
363     setOperationAction(ISD::FRINT, VT, Expand);
364     setOperationAction(ISD::FNEARBYINT, VT, Expand);
365     setOperationAction(ISD::FSQRT, VT, Expand);
366     setOperationAction(ISD::FSIN, VT, Expand);
367     setOperationAction(ISD::FSUB, VT, Expand);
368     setOperationAction(ISD::FNEG, VT, Expand);
369     setOperationAction(ISD::SELECT, VT, Expand);
370     setOperationAction(ISD::VSELECT, VT, Expand);
371     setOperationAction(ISD::SELECT_CC, VT, Expand);
372     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
373     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
374   }
375 
376   setOperationAction(ISD::FNEARBYINT, MVT::f32, Custom);
377   setOperationAction(ISD::FNEARBYINT, MVT::f64, Custom);
378 
379   setTargetDAGCombine(ISD::AND);
380   setTargetDAGCombine(ISD::SHL);
381   setTargetDAGCombine(ISD::SRA);
382   setTargetDAGCombine(ISD::SRL);
383   setTargetDAGCombine(ISD::MUL);
384   setTargetDAGCombine(ISD::SELECT);
385   setTargetDAGCombine(ISD::SELECT_CC);
386   setTargetDAGCombine(ISD::STORE);
387 
388   setTargetDAGCombine(ISD::FADD);
389   setTargetDAGCombine(ISD::FSUB);
390 
391   setBooleanContents(ZeroOrNegativeOneBooleanContent);
392   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
393 
394   setSchedulingPreference(Sched::RegPressure);
395   setJumpIsExpensive(true);
396 
397   // SI at least has hardware support for floating point exceptions, but no way
398   // of using or handling them is implemented. They are also optional in OpenCL
399   // (Section 7.3)
400   setHasFloatingPointExceptions(Subtarget->hasFPExceptions());
401 
402   setSelectIsExpensive(false);
403   PredictableSelectIsExpensive = false;
404 
405   setFsqrtIsCheap(true);
406 
407   // We want to find all load dependencies for long chains of stores to enable
408   // merging into very wide vectors. The problem is with vectors with > 4
409   // elements. MergeConsecutiveStores will attempt to merge these because x8/x16
410   // vectors are a legal type, even though we have to split the loads
411   // usually. When we can more precisely specify load legality per address
412   // space, we should be able to make FindBetterChain/MergeConsecutiveStores
413   // smarter so that they can figure out what to do in 2 iterations without all
414   // N > 4 stores on the same chain.
415   GatherAllAliasesMaxDepth = 16;
416 
417   // FIXME: Need to really handle these.
418   MaxStoresPerMemcpy  = 4096;
419   MaxStoresPerMemmove = 4096;
420   MaxStoresPerMemset  = 4096;
421 }
422 
423 //===----------------------------------------------------------------------===//
424 // Target Information
425 //===----------------------------------------------------------------------===//
426 
427 MVT AMDGPUTargetLowering::getVectorIdxTy(const DataLayout &) const {
428   return MVT::i32;
429 }
430 
431 bool AMDGPUTargetLowering::isSelectSupported(SelectSupportKind SelType) const {
432   return true;
433 }
434 
435 // The backend supports 32 and 64 bit floating point immediates.
436 // FIXME: Why are we reporting vectors of FP immediates as legal?
437 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
438   EVT ScalarVT = VT.getScalarType();
439   return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64);
440 }
441 
442 // We don't want to shrink f64 / f32 constants.
443 bool AMDGPUTargetLowering::ShouldShrinkFPConstant(EVT VT) const {
444   EVT ScalarVT = VT.getScalarType();
445   return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
446 }
447 
448 bool AMDGPUTargetLowering::shouldReduceLoadWidth(SDNode *N,
449                                                  ISD::LoadExtType,
450                                                  EVT NewVT) const {
451 
452   unsigned NewSize = NewVT.getStoreSizeInBits();
453 
454   // If we are reducing to a 32-bit load, this is always better.
455   if (NewSize == 32)
456     return true;
457 
458   EVT OldVT = N->getValueType(0);
459   unsigned OldSize = OldVT.getStoreSizeInBits();
460 
461   // Don't produce extloads from sub 32-bit types. SI doesn't have scalar
462   // extloads, so doing one requires using a buffer_load. In cases where we
463   // still couldn't use a scalar load, using the wider load shouldn't really
464   // hurt anything.
465 
466   // If the old size already had to be an extload, there's no harm in continuing
467   // to reduce the width.
468   return (OldSize < 32);
469 }
470 
471 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy,
472                                                    EVT CastTy) const {
473   if (LoadTy.getSizeInBits() != CastTy.getSizeInBits())
474     return true;
475 
476   unsigned LScalarSize = LoadTy.getScalarType().getSizeInBits();
477   unsigned CastScalarSize = CastTy.getScalarType().getSizeInBits();
478 
479   return ((LScalarSize <= CastScalarSize) ||
480           (CastScalarSize >= 32) ||
481           (LScalarSize < 32));
482 }
483 
484 // SI+ has instructions for cttz / ctlz for 32-bit values. This is probably also
485 // profitable with the expansion for 64-bit since it's generally good to
486 // speculate things.
487 // FIXME: These should really have the size as a parameter.
488 bool AMDGPUTargetLowering::isCheapToSpeculateCttz() const {
489   return true;
490 }
491 
492 bool AMDGPUTargetLowering::isCheapToSpeculateCtlz() const {
493   return true;
494 }
495 
496 //===---------------------------------------------------------------------===//
497 // Target Properties
498 //===---------------------------------------------------------------------===//
499 
500 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
501   assert(VT.isFloatingPoint());
502   return VT == MVT::f32 || VT == MVT::f64;
503 }
504 
505 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
506   assert(VT.isFloatingPoint());
507   return VT == MVT::f32 || VT == MVT::f64;
508 }
509 
510 bool AMDGPUTargetLowering:: storeOfVectorConstantIsCheap(EVT MemVT,
511                                                          unsigned NumElem,
512                                                          unsigned AS) const {
513   return true;
514 }
515 
516 bool AMDGPUTargetLowering::aggressivelyPreferBuildVectorSources(EVT VecVT) const {
517   // There are few operations which truly have vector input operands. Any vector
518   // operation is going to involve operations on each component, and a
519   // build_vector will be a copy per element, so it always makes sense to use a
520   // build_vector input in place of the extracted element to avoid a copy into a
521   // super register.
522   //
523   // We should probably only do this if all users are extracts only, but this
524   // should be the common case.
525   return true;
526 }
527 
528 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
529   // Truncate is just accessing a subregister.
530   return Dest.bitsLT(Source) && (Dest.getSizeInBits() % 32 == 0);
531 }
532 
533 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
534   // Truncate is just accessing a subregister.
535   return Dest->getPrimitiveSizeInBits() < Source->getPrimitiveSizeInBits() &&
536          (Dest->getPrimitiveSizeInBits() % 32 == 0);
537 }
538 
539 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
540   unsigned SrcSize = Src->getScalarSizeInBits();
541   unsigned DestSize = Dest->getScalarSizeInBits();
542 
543   return SrcSize == 32 && DestSize == 64;
544 }
545 
546 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
547   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
548   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
549   // this will enable reducing 64-bit operations the 32-bit, which is always
550   // good.
551   return Src == MVT::i32 && Dest == MVT::i64;
552 }
553 
554 bool AMDGPUTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
555   return isZExtFree(Val.getValueType(), VT2);
556 }
557 
558 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
559   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
560   // limited number of native 64-bit operations. Shrinking an operation to fit
561   // in a single 32-bit register should always be helpful. As currently used,
562   // this is much less general than the name suggests, and is only used in
563   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
564   // not profitable, and may actually be harmful.
565   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
566 }
567 
568 //===---------------------------------------------------------------------===//
569 // TargetLowering Callbacks
570 //===---------------------------------------------------------------------===//
571 
572 void AMDGPUTargetLowering::AnalyzeFormalArguments(CCState &State,
573                              const SmallVectorImpl<ISD::InputArg> &Ins) const {
574 
575   State.AnalyzeFormalArguments(Ins, CC_AMDGPU);
576 }
577 
578 void AMDGPUTargetLowering::AnalyzeReturn(CCState &State,
579                            const SmallVectorImpl<ISD::OutputArg> &Outs) const {
580 
581   State.AnalyzeReturn(Outs, RetCC_SI);
582 }
583 
584 SDValue AMDGPUTargetLowering::LowerReturn(
585                                      SDValue Chain,
586                                      CallingConv::ID CallConv,
587                                      bool isVarArg,
588                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
589                                      const SmallVectorImpl<SDValue> &OutVals,
590                                      SDLoc DL, SelectionDAG &DAG) const {
591   return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, Chain);
592 }
593 
594 //===---------------------------------------------------------------------===//
595 // Target specific lowering
596 //===---------------------------------------------------------------------===//
597 
598 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
599                                         SmallVectorImpl<SDValue> &InVals) const {
600   SDValue Callee = CLI.Callee;
601   SelectionDAG &DAG = CLI.DAG;
602 
603   const Function &Fn = *DAG.getMachineFunction().getFunction();
604 
605   StringRef FuncName("<unknown>");
606 
607   if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
608     FuncName = G->getSymbol();
609   else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
610     FuncName = G->getGlobal()->getName();
611 
612   DiagnosticInfoUnsupported NoCalls(
613       Fn, "unsupported call to function " + FuncName, CLI.DL.getDebugLoc());
614   DAG.getContext()->diagnose(NoCalls);
615   return SDValue();
616 }
617 
618 SDValue AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
619                                                       SelectionDAG &DAG) const {
620   const Function &Fn = *DAG.getMachineFunction().getFunction();
621 
622   DiagnosticInfoUnsupported NoDynamicAlloca(Fn, "unsupported dynamic alloca",
623                                             SDLoc(Op).getDebugLoc());
624   DAG.getContext()->diagnose(NoDynamicAlloca);
625   return SDValue();
626 }
627 
628 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op,
629                                              SelectionDAG &DAG) const {
630   switch (Op.getOpcode()) {
631   default:
632     Op.getNode()->dump();
633     llvm_unreachable("Custom lowering code for this"
634                      "instruction is not implemented yet!");
635     break;
636   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
637   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
638   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
639   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
640   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
641   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
642   case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
643   case ISD::FREM: return LowerFREM(Op, DAG);
644   case ISD::FCEIL: return LowerFCEIL(Op, DAG);
645   case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
646   case ISD::FRINT: return LowerFRINT(Op, DAG);
647   case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
648   case ISD::FROUND: return LowerFROUND(Op, DAG);
649   case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
650   case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
651   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
652   case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
653   case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
654   case ISD::CTLZ:
655   case ISD::CTLZ_ZERO_UNDEF:
656     return LowerCTLZ(Op, DAG);
657   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
658   }
659   return Op;
660 }
661 
662 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
663                                               SmallVectorImpl<SDValue> &Results,
664                                               SelectionDAG &DAG) const {
665   switch (N->getOpcode()) {
666   case ISD::SIGN_EXTEND_INREG:
667     // Different parts of legalization seem to interpret which type of
668     // sign_extend_inreg is the one to check for custom lowering. The extended
669     // from type is what really matters, but some places check for custom
670     // lowering of the result type. This results in trying to use
671     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
672     // nothing here and let the illegal result integer be handled normally.
673     return;
674   default:
675     return;
676   }
677 }
678 
679 // FIXME: This implements accesses to initialized globals in the constant
680 // address space by copying them to private and accessing that. It does not
681 // properly handle illegal types or vectors. The private vector loads are not
682 // scalarized, and the illegal scalars hit an assertion. This technique will not
683 // work well with large initializers, and this should eventually be
684 // removed. Initialized globals should be placed into a data section that the
685 // runtime will load into a buffer before the kernel is executed. Uses of the
686 // global need to be replaced with a pointer loaded from an implicit kernel
687 // argument into this buffer holding the copy of the data, which will remove the
688 // need for any of this.
689 SDValue AMDGPUTargetLowering::LowerConstantInitializer(const Constant* Init,
690                                                        const GlobalValue *GV,
691                                                        const SDValue &InitPtr,
692                                                        SDValue Chain,
693                                                        SelectionDAG &DAG) const {
694   const DataLayout &TD = DAG.getDataLayout();
695   SDLoc DL(InitPtr);
696   Type *InitTy = Init->getType();
697 
698   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Init)) {
699     EVT VT = EVT::getEVT(InitTy);
700     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
701     return DAG.getStore(Chain, DL, DAG.getConstant(*CI, DL, VT), InitPtr,
702                         MachinePointerInfo(UndefValue::get(PtrTy)), false,
703                         false, TD.getPrefTypeAlignment(InitTy));
704   }
705 
706   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Init)) {
707     EVT VT = EVT::getEVT(CFP->getType());
708     PointerType *PtrTy = PointerType::get(CFP->getType(), 0);
709     return DAG.getStore(Chain, DL, DAG.getConstantFP(*CFP, DL, VT), InitPtr,
710                         MachinePointerInfo(UndefValue::get(PtrTy)), false,
711                         false, TD.getPrefTypeAlignment(CFP->getType()));
712   }
713 
714   if (StructType *ST = dyn_cast<StructType>(InitTy)) {
715     const StructLayout *SL = TD.getStructLayout(ST);
716 
717     EVT PtrVT = InitPtr.getValueType();
718     SmallVector<SDValue, 8> Chains;
719 
720     for (unsigned I = 0, N = ST->getNumElements(); I != N; ++I) {
721       SDValue Offset = DAG.getConstant(SL->getElementOffset(I), DL, PtrVT);
722       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
723 
724       Constant *Elt = Init->getAggregateElement(I);
725       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
726     }
727 
728     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
729   }
730 
731   if (SequentialType *SeqTy = dyn_cast<SequentialType>(InitTy)) {
732     EVT PtrVT = InitPtr.getValueType();
733 
734     unsigned NumElements;
735     if (ArrayType *AT = dyn_cast<ArrayType>(SeqTy))
736       NumElements = AT->getNumElements();
737     else if (VectorType *VT = dyn_cast<VectorType>(SeqTy))
738       NumElements = VT->getNumElements();
739     else
740       llvm_unreachable("Unexpected type");
741 
742     unsigned EltSize = TD.getTypeAllocSize(SeqTy->getElementType());
743     SmallVector<SDValue, 8> Chains;
744     for (unsigned i = 0; i < NumElements; ++i) {
745       SDValue Offset = DAG.getConstant(i * EltSize, DL, PtrVT);
746       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, InitPtr, Offset);
747 
748       Constant *Elt = Init->getAggregateElement(i);
749       Chains.push_back(LowerConstantInitializer(Elt, GV, Ptr, Chain, DAG));
750     }
751 
752     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
753   }
754 
755   if (isa<UndefValue>(Init)) {
756     EVT VT = EVT::getEVT(InitTy);
757     PointerType *PtrTy = PointerType::get(InitTy, AMDGPUAS::PRIVATE_ADDRESS);
758     return DAG.getStore(Chain, DL, DAG.getUNDEF(VT), InitPtr,
759                         MachinePointerInfo(UndefValue::get(PtrTy)), false,
760                         false, TD.getPrefTypeAlignment(InitTy));
761   }
762 
763   Init->dump();
764   llvm_unreachable("Unhandled constant initializer");
765 }
766 
767 static bool hasDefinedInitializer(const GlobalValue *GV) {
768   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
769   if (!GVar || !GVar->hasInitializer())
770     return false;
771 
772   if (isa<UndefValue>(GVar->getInitializer()))
773     return false;
774 
775   return true;
776 }
777 
778 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
779                                                  SDValue Op,
780                                                  SelectionDAG &DAG) const {
781 
782   const DataLayout &DL = DAG.getDataLayout();
783   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
784   const GlobalValue *GV = G->getGlobal();
785 
786   switch (G->getAddressSpace()) {
787   case AMDGPUAS::LOCAL_ADDRESS: {
788     // XXX: What does the value of G->getOffset() mean?
789     assert(G->getOffset() == 0 &&
790          "Do not know what to do with an non-zero offset");
791 
792     // TODO: We could emit code to handle the initialization somewhere.
793     if (hasDefinedInitializer(GV))
794       break;
795 
796     unsigned Offset;
797     if (MFI->LocalMemoryObjects.count(GV) == 0) {
798       unsigned Align = GV->getAlignment();
799       if (Align == 0)
800         Align = DL.getABITypeAlignment(GV->getValueType());
801 
802       /// TODO: We should sort these to minimize wasted space due to alignment
803       /// padding. Currently the padding is decided by the first encountered use
804       /// during lowering.
805       Offset = MFI->LDSSize = alignTo(MFI->LDSSize, Align);
806       MFI->LocalMemoryObjects[GV] = Offset;
807       MFI->LDSSize += DL.getTypeAllocSize(GV->getValueType());
808     } else {
809       Offset = MFI->LocalMemoryObjects[GV];
810     }
811 
812     return DAG.getConstant(Offset, SDLoc(Op),
813                            getPointerTy(DL, AMDGPUAS::LOCAL_ADDRESS));
814   }
815   case AMDGPUAS::CONSTANT_ADDRESS: {
816     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
817     Type *EltType = GV->getValueType();
818     unsigned Size = DL.getTypeAllocSize(EltType);
819     unsigned Alignment = DL.getPrefTypeAlignment(EltType);
820 
821     MVT PrivPtrVT = getPointerTy(DL, AMDGPUAS::PRIVATE_ADDRESS);
822     MVT ConstPtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
823 
824     int FI = FrameInfo->CreateStackObject(Size, Alignment, false);
825     SDValue InitPtr = DAG.getFrameIndex(FI, PrivPtrVT);
826 
827     const GlobalVariable *Var = cast<GlobalVariable>(GV);
828     if (!Var->hasInitializer()) {
829       // This has no use, but bugpoint will hit it.
830       return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
831     }
832 
833     const Constant *Init = Var->getInitializer();
834     SmallVector<SDNode*, 8> WorkList;
835 
836     for (SDNode::use_iterator I = DAG.getEntryNode()->use_begin(),
837                               E = DAG.getEntryNode()->use_end(); I != E; ++I) {
838       if (I->getOpcode() != AMDGPUISD::REGISTER_LOAD && I->getOpcode() != ISD::LOAD)
839         continue;
840       WorkList.push_back(*I);
841     }
842     SDValue Chain = LowerConstantInitializer(Init, GV, InitPtr, DAG.getEntryNode(), DAG);
843     for (SmallVector<SDNode*, 8>::iterator I = WorkList.begin(),
844                                            E = WorkList.end(); I != E; ++I) {
845       SmallVector<SDValue, 8> Ops;
846       Ops.push_back(Chain);
847       for (unsigned i = 1; i < (*I)->getNumOperands(); ++i) {
848         Ops.push_back((*I)->getOperand(i));
849       }
850       DAG.UpdateNodeOperands(*I, Ops);
851     }
852     return DAG.getZExtOrTrunc(InitPtr, SDLoc(Op), ConstPtrVT);
853   }
854   }
855 
856   const Function &Fn = *DAG.getMachineFunction().getFunction();
857   DiagnosticInfoUnsupported BadInit(
858       Fn, "unsupported initializer for address space", SDLoc(Op).getDebugLoc());
859   DAG.getContext()->diagnose(BadInit);
860   return SDValue();
861 }
862 
863 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
864                                                   SelectionDAG &DAG) const {
865   SmallVector<SDValue, 8> Args;
866 
867   for (const SDUse &U : Op->ops())
868     DAG.ExtractVectorElements(U.get(), Args);
869 
870   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
871 }
872 
873 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
874                                                      SelectionDAG &DAG) const {
875 
876   SmallVector<SDValue, 8> Args;
877   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
878   EVT VT = Op.getValueType();
879   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
880                             VT.getVectorNumElements());
881 
882   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op), Op.getValueType(), Args);
883 }
884 
885 SDValue AMDGPUTargetLowering::LowerFrameIndex(SDValue Op,
886                                               SelectionDAG &DAG) const {
887 
888   MachineFunction &MF = DAG.getMachineFunction();
889   const AMDGPUFrameLowering *TFL = Subtarget->getFrameLowering();
890 
891   FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(Op);
892 
893   unsigned FrameIndex = FIN->getIndex();
894   unsigned IgnoredFrameReg;
895   unsigned Offset =
896       TFL->getFrameIndexReference(MF, FrameIndex, IgnoredFrameReg);
897   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF), SDLoc(Op),
898                          Op.getValueType());
899 }
900 
901 SDValue AMDGPUTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
902     SelectionDAG &DAG) const {
903   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
904   SDLoc DL(Op);
905   EVT VT = Op.getValueType();
906 
907   switch (IntrinsicID) {
908     default: return Op;
909     case AMDGPUIntrinsic::AMDGPU_clamp:
910     case AMDGPUIntrinsic::AMDIL_clamp: // Legacy name.
911       return DAG.getNode(AMDGPUISD::CLAMP, DL, VT,
912                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
913 
914     case Intrinsic::AMDGPU_ldexp: // Legacy name
915       return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, Op.getOperand(1),
916                                                    Op.getOperand(2));
917 
918     case AMDGPUIntrinsic::AMDGPU_bfe_i32:
919       return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
920                          Op.getOperand(1),
921                          Op.getOperand(2),
922                          Op.getOperand(3));
923 
924     case AMDGPUIntrinsic::AMDGPU_bfe_u32:
925       return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
926                          Op.getOperand(1),
927                          Op.getOperand(2),
928                          Op.getOperand(3));
929 
930     case AMDGPUIntrinsic::AMDIL_exp: // Legacy name.
931       return DAG.getNode(ISD::FEXP2, DL, VT, Op.getOperand(1));
932 
933     case AMDGPUIntrinsic::AMDGPU_brev: // Legacy name
934       return DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(1));
935   }
936 }
937 
938 /// \brief Generate Min/Max node
939 SDValue AMDGPUTargetLowering::CombineFMinMaxLegacy(SDLoc DL,
940                                                    EVT VT,
941                                                    SDValue LHS,
942                                                    SDValue RHS,
943                                                    SDValue True,
944                                                    SDValue False,
945                                                    SDValue CC,
946                                                    DAGCombinerInfo &DCI) const {
947   if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
948     return SDValue();
949 
950   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
951     return SDValue();
952 
953   SelectionDAG &DAG = DCI.DAG;
954   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
955   switch (CCOpcode) {
956   case ISD::SETOEQ:
957   case ISD::SETONE:
958   case ISD::SETUNE:
959   case ISD::SETNE:
960   case ISD::SETUEQ:
961   case ISD::SETEQ:
962   case ISD::SETFALSE:
963   case ISD::SETFALSE2:
964   case ISD::SETTRUE:
965   case ISD::SETTRUE2:
966   case ISD::SETUO:
967   case ISD::SETO:
968     break;
969   case ISD::SETULE:
970   case ISD::SETULT: {
971     if (LHS == True)
972       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
973     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
974   }
975   case ISD::SETOLE:
976   case ISD::SETOLT:
977   case ISD::SETLE:
978   case ISD::SETLT: {
979     // Ordered. Assume ordered for undefined.
980 
981     // Only do this after legalization to avoid interfering with other combines
982     // which might occur.
983     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
984         !DCI.isCalledByLegalizer())
985       return SDValue();
986 
987     // We need to permute the operands to get the correct NaN behavior. The
988     // selected operand is the second one based on the failing compare with NaN,
989     // so permute it based on the compare type the hardware uses.
990     if (LHS == True)
991       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
992     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
993   }
994   case ISD::SETUGE:
995   case ISD::SETUGT: {
996     if (LHS == True)
997       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
998     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
999   }
1000   case ISD::SETGT:
1001   case ISD::SETGE:
1002   case ISD::SETOGE:
1003   case ISD::SETOGT: {
1004     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1005         !DCI.isCalledByLegalizer())
1006       return SDValue();
1007 
1008     if (LHS == True)
1009       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1010     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1011   }
1012   case ISD::SETCC_INVALID:
1013     llvm_unreachable("Invalid setcc condcode!");
1014   }
1015   return SDValue();
1016 }
1017 
1018 std::pair<SDValue, SDValue>
1019 AMDGPUTargetLowering::split64BitValue(SDValue Op, SelectionDAG &DAG) const {
1020   SDLoc SL(Op);
1021 
1022   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1023 
1024   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1025   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1026 
1027   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1028   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1029 
1030   return std::make_pair(Lo, Hi);
1031 }
1032 
1033 SDValue AMDGPUTargetLowering::getLoHalf64(SDValue Op, SelectionDAG &DAG) const {
1034   SDLoc SL(Op);
1035 
1036   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1037   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1038   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1039 }
1040 
1041 SDValue AMDGPUTargetLowering::getHiHalf64(SDValue Op, SelectionDAG &DAG) const {
1042   SDLoc SL(Op);
1043 
1044   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1045   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1046   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1047 }
1048 
1049 SDValue AMDGPUTargetLowering::ScalarizeVectorLoad(const SDValue Op,
1050                                                   SelectionDAG &DAG) const {
1051   LoadSDNode *Load = cast<LoadSDNode>(Op);
1052   EVT MemVT = Load->getMemoryVT();
1053   EVT MemEltVT = MemVT.getVectorElementType();
1054 
1055   EVT LoadVT = Op.getValueType();
1056   EVT EltVT = LoadVT.getVectorElementType();
1057   EVT PtrVT = Load->getBasePtr().getValueType();
1058 
1059   unsigned NumElts = Load->getMemoryVT().getVectorNumElements();
1060   SmallVector<SDValue, 8> Loads;
1061   SmallVector<SDValue, 8> Chains;
1062 
1063   SDLoc SL(Op);
1064   unsigned BaseAlign = Load->getAlignment();
1065   unsigned MemEltSize = MemEltVT.getStoreSize();
1066 
1067   MachinePointerInfo SrcValue(Load->getMemOperand()->getValue());
1068 
1069   for (unsigned i = 0; i < NumElts; ++i) {
1070     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Load->getBasePtr(),
1071                               DAG.getConstant(i * MemEltSize, SL, PtrVT));
1072 
1073     SDValue NewLoad
1074       = DAG.getExtLoad(Load->getExtensionType(), SL, EltVT,
1075                        Load->getChain(), Ptr,
1076                        SrcValue.getWithOffset(i * MemEltSize),
1077                        MemEltVT, Load->isVolatile(), Load->isNonTemporal(),
1078                        Load->isInvariant(), MinAlign(BaseAlign, i * MemEltSize));
1079     Loads.push_back(NewLoad.getValue(0));
1080     Chains.push_back(NewLoad.getValue(1));
1081   }
1082 
1083   SDValue Ops[] = {
1084     DAG.getNode(ISD::BUILD_VECTOR, SL, LoadVT, Loads),
1085     DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains)
1086   };
1087 
1088   return DAG.getMergeValues(Ops, SL);
1089 }
1090 
1091 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue Op,
1092                                               SelectionDAG &DAG) const {
1093   EVT VT = Op.getValueType();
1094 
1095   // If this is a 2 element vector, we really want to scalarize and not create
1096   // weird 1 element vectors.
1097   if (VT.getVectorNumElements() == 2)
1098     return ScalarizeVectorLoad(Op, DAG);
1099 
1100   LoadSDNode *Load = cast<LoadSDNode>(Op);
1101   SDValue BasePtr = Load->getBasePtr();
1102   EVT PtrVT = BasePtr.getValueType();
1103   EVT MemVT = Load->getMemoryVT();
1104   SDLoc SL(Op);
1105 
1106   const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1107 
1108   EVT LoVT, HiVT;
1109   EVT LoMemVT, HiMemVT;
1110   SDValue Lo, Hi;
1111 
1112   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1113   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1114   std::tie(Lo, Hi) = DAG.SplitVector(Op, SL, LoVT, HiVT);
1115 
1116   unsigned Size = LoMemVT.getStoreSize();
1117   unsigned BaseAlign = Load->getAlignment();
1118   unsigned HiAlign = MinAlign(BaseAlign, Size);
1119 
1120   SDValue LoLoad
1121     = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1122                      Load->getChain(), BasePtr,
1123                      SrcValue,
1124                      LoMemVT, Load->isVolatile(), Load->isNonTemporal(),
1125                      Load->isInvariant(), BaseAlign);
1126 
1127   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1128                               DAG.getConstant(Size, SL, PtrVT));
1129 
1130   SDValue HiLoad
1131     = DAG.getExtLoad(Load->getExtensionType(), SL, HiVT,
1132                      Load->getChain(), HiPtr,
1133                      SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1134                      HiMemVT, Load->isVolatile(), Load->isNonTemporal(),
1135                      Load->isInvariant(), HiAlign);
1136 
1137   SDValue Ops[] = {
1138     DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad),
1139     DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
1140                 LoLoad.getValue(1), HiLoad.getValue(1))
1141   };
1142 
1143   return DAG.getMergeValues(Ops, SL);
1144 }
1145 
1146 // FIXME: This isn't doing anything for SI. This should be used in a target
1147 // combine during type legalization.
1148 SDValue AMDGPUTargetLowering::MergeVectorStore(const SDValue &Op,
1149                                                SelectionDAG &DAG) const {
1150   StoreSDNode *Store = cast<StoreSDNode>(Op);
1151   EVT MemVT = Store->getMemoryVT();
1152   unsigned MemBits = MemVT.getSizeInBits();
1153 
1154   // Byte stores are really expensive, so if possible, try to pack 32-bit vector
1155   // truncating store into an i32 store.
1156   // XXX: We could also handle optimize other vector bitwidths.
1157   if (!MemVT.isVector() || MemBits > 32) {
1158     return SDValue();
1159   }
1160 
1161   SDLoc DL(Op);
1162   SDValue Value = Store->getValue();
1163   EVT VT = Value.getValueType();
1164   EVT ElemVT = VT.getVectorElementType();
1165   SDValue Ptr = Store->getBasePtr();
1166   EVT MemEltVT = MemVT.getVectorElementType();
1167   unsigned MemEltBits = MemEltVT.getSizeInBits();
1168   unsigned MemNumElements = MemVT.getVectorNumElements();
1169   unsigned PackedSize = MemVT.getStoreSizeInBits();
1170   SDValue Mask = DAG.getConstant((1 << MemEltBits) - 1, DL, MVT::i32);
1171 
1172   assert(Value.getValueType().getScalarSizeInBits() >= 32);
1173 
1174   SDValue PackedValue;
1175   for (unsigned i = 0; i < MemNumElements; ++i) {
1176     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT, Value,
1177                               DAG.getConstant(i, DL, MVT::i32));
1178     Elt = DAG.getZExtOrTrunc(Elt, DL, MVT::i32);
1179     Elt = DAG.getNode(ISD::AND, DL, MVT::i32, Elt, Mask); // getZeroExtendInReg
1180 
1181     SDValue Shift = DAG.getConstant(MemEltBits * i, DL, MVT::i32);
1182     Elt = DAG.getNode(ISD::SHL, DL, MVT::i32, Elt, Shift);
1183 
1184     if (i == 0) {
1185       PackedValue = Elt;
1186     } else {
1187       PackedValue = DAG.getNode(ISD::OR, DL, MVT::i32, PackedValue, Elt);
1188     }
1189   }
1190 
1191   if (PackedSize < 32) {
1192     EVT PackedVT = EVT::getIntegerVT(*DAG.getContext(), PackedSize);
1193     return DAG.getTruncStore(Store->getChain(), DL, PackedValue, Ptr,
1194                              Store->getMemOperand()->getPointerInfo(),
1195                              PackedVT,
1196                              Store->isNonTemporal(), Store->isVolatile(),
1197                              Store->getAlignment());
1198   }
1199 
1200   return DAG.getStore(Store->getChain(), DL, PackedValue, Ptr,
1201                       Store->getMemOperand()->getPointerInfo(),
1202                       Store->isVolatile(),  Store->isNonTemporal(),
1203                       Store->getAlignment());
1204 }
1205 
1206 SDValue AMDGPUTargetLowering::ScalarizeVectorStore(SDValue Op,
1207                                                    SelectionDAG &DAG) const {
1208   StoreSDNode *Store = cast<StoreSDNode>(Op);
1209   EVT MemEltVT = Store->getMemoryVT().getVectorElementType();
1210   EVT EltVT = Store->getValue().getValueType().getVectorElementType();
1211   EVT PtrVT = Store->getBasePtr().getValueType();
1212   unsigned NumElts = Store->getMemoryVT().getVectorNumElements();
1213   SDLoc SL(Op);
1214 
1215   SmallVector<SDValue, 8> Chains;
1216 
1217   unsigned BaseAlign = Store->getAlignment();
1218   unsigned EltSize = MemEltVT.getStoreSize();
1219   MachinePointerInfo SrcValue(Store->getMemOperand()->getValue());
1220 
1221   for (unsigned i = 0, e = NumElts; i != e; ++i) {
1222     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
1223                               Store->getValue(),
1224                               DAG.getConstant(i, SL, MVT::i32));
1225 
1226     SDValue Offset = DAG.getConstant(i * MemEltVT.getStoreSize(), SL, PtrVT);
1227     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, Store->getBasePtr(), Offset);
1228     SDValue NewStore =
1229       DAG.getTruncStore(Store->getChain(), SL, Val, Ptr,
1230                         SrcValue.getWithOffset(i * EltSize),
1231                         MemEltVT, Store->isNonTemporal(), Store->isVolatile(),
1232                         MinAlign(BaseAlign, i * EltSize));
1233     Chains.push_back(NewStore);
1234   }
1235 
1236   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Chains);
1237 }
1238 
1239 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1240                                                SelectionDAG &DAG) const {
1241   StoreSDNode *Store = cast<StoreSDNode>(Op);
1242   SDValue Val = Store->getValue();
1243   EVT VT = Val.getValueType();
1244 
1245   // If this is a 2 element vector, we really want to scalarize and not create
1246   // weird 1 element vectors.
1247   if (VT.getVectorNumElements() == 2)
1248     return ScalarizeVectorStore(Op, DAG);
1249 
1250   EVT MemVT = Store->getMemoryVT();
1251   SDValue Chain = Store->getChain();
1252   SDValue BasePtr = Store->getBasePtr();
1253   SDLoc SL(Op);
1254 
1255   EVT LoVT, HiVT;
1256   EVT LoMemVT, HiMemVT;
1257   SDValue Lo, Hi;
1258 
1259   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1260   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1261   std::tie(Lo, Hi) = DAG.SplitVector(Val, SL, LoVT, HiVT);
1262 
1263   EVT PtrVT = BasePtr.getValueType();
1264   SDValue HiPtr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1265                               DAG.getConstant(LoMemVT.getStoreSize(), SL,
1266                                               PtrVT));
1267 
1268   const MachinePointerInfo &SrcValue = Store->getMemOperand()->getPointerInfo();
1269   unsigned BaseAlign = Store->getAlignment();
1270   unsigned Size = LoMemVT.getStoreSize();
1271   unsigned HiAlign = MinAlign(BaseAlign, Size);
1272 
1273   SDValue LoStore
1274     = DAG.getTruncStore(Chain, SL, Lo,
1275                         BasePtr,
1276                         SrcValue,
1277                         LoMemVT,
1278                         Store->isNonTemporal(),
1279                         Store->isVolatile(),
1280                         BaseAlign);
1281   SDValue HiStore
1282     = DAG.getTruncStore(Chain, SL, Hi,
1283                         HiPtr,
1284                         SrcValue.getWithOffset(Size),
1285                         HiMemVT,
1286                         Store->isNonTemporal(),
1287                         Store->isVolatile(),
1288                         HiAlign);
1289 
1290   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1291 }
1292 
1293 // This is a shortcut for integer division because we have fast i32<->f32
1294 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1295 // float is enough to accurately represent up to a 24-bit integer.
1296 SDValue AMDGPUTargetLowering::LowerDIVREM24(SDValue Op, SelectionDAG &DAG, bool sign) const {
1297   SDLoc DL(Op);
1298   EVT VT = Op.getValueType();
1299   SDValue LHS = Op.getOperand(0);
1300   SDValue RHS = Op.getOperand(1);
1301   MVT IntVT = MVT::i32;
1302   MVT FltVT = MVT::f32;
1303 
1304   ISD::NodeType ToFp  = sign ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
1305   ISD::NodeType ToInt = sign ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
1306 
1307   if (VT.isVector()) {
1308     unsigned NElts = VT.getVectorNumElements();
1309     IntVT = MVT::getVectorVT(MVT::i32, NElts);
1310     FltVT = MVT::getVectorVT(MVT::f32, NElts);
1311   }
1312 
1313   unsigned BitSize = VT.getScalarType().getSizeInBits();
1314 
1315   SDValue jq = DAG.getConstant(1, DL, IntVT);
1316 
1317   if (sign) {
1318     // char|short jq = ia ^ ib;
1319     jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1320 
1321     // jq = jq >> (bitsize - 2)
1322     jq = DAG.getNode(ISD::SRA, DL, VT, jq,
1323                      DAG.getConstant(BitSize - 2, DL, VT));
1324 
1325     // jq = jq | 0x1
1326     jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, DL, VT));
1327 
1328     // jq = (int)jq
1329     jq = DAG.getSExtOrTrunc(jq, DL, IntVT);
1330   }
1331 
1332   // int ia = (int)LHS;
1333   SDValue ia = sign ?
1334     DAG.getSExtOrTrunc(LHS, DL, IntVT) : DAG.getZExtOrTrunc(LHS, DL, IntVT);
1335 
1336   // int ib, (int)RHS;
1337   SDValue ib = sign ?
1338     DAG.getSExtOrTrunc(RHS, DL, IntVT) : DAG.getZExtOrTrunc(RHS, DL, IntVT);
1339 
1340   // float fa = (float)ia;
1341   SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1342 
1343   // float fb = (float)ib;
1344   SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1345 
1346   // TODO: Should this propagate fast-math-flags?
1347   // float fq = native_divide(fa, fb);
1348   SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1349                            fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1350 
1351   // fq = trunc(fq);
1352   fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1353 
1354   // float fqneg = -fq;
1355   SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1356 
1357   // float fr = mad(fqneg, fb, fa);
1358   SDValue fr = DAG.getNode(ISD::FADD, DL, FltVT,
1359                            DAG.getNode(ISD::FMUL, DL, FltVT, fqneg, fb), fa);
1360 
1361   // int iq = (int)fq;
1362   SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1363 
1364   // fr = fabs(fr);
1365   fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1366 
1367   // fb = fabs(fb);
1368   fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1369 
1370   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
1371 
1372   // int cv = fr >= fb;
1373   SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1374 
1375   // jq = (cv ? jq : 0);
1376   jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, DL, VT));
1377 
1378   // dst = trunc/extend to legal type
1379   iq = sign ? DAG.getSExtOrTrunc(iq, DL, VT) : DAG.getZExtOrTrunc(iq, DL, VT);
1380 
1381   // dst = iq + jq;
1382   SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1383 
1384   // Rem needs compensation, it's easier to recompute it
1385   SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1386   Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1387 
1388   SDValue Res[2] = {
1389     Div,
1390     Rem
1391   };
1392   return DAG.getMergeValues(Res, DL);
1393 }
1394 
1395 void AMDGPUTargetLowering::LowerUDIVREM64(SDValue Op,
1396                                       SelectionDAG &DAG,
1397                                       SmallVectorImpl<SDValue> &Results) const {
1398   assert(Op.getValueType() == MVT::i64);
1399 
1400   SDLoc DL(Op);
1401   EVT VT = Op.getValueType();
1402   EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1403 
1404   SDValue one = DAG.getConstant(1, DL, HalfVT);
1405   SDValue zero = DAG.getConstant(0, DL, HalfVT);
1406 
1407   //HiLo split
1408   SDValue LHS = Op.getOperand(0);
1409   SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, zero);
1410   SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, one);
1411 
1412   SDValue RHS = Op.getOperand(1);
1413   SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, zero);
1414   SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, one);
1415 
1416   if (VT == MVT::i64 &&
1417     DAG.MaskedValueIsZero(RHS, APInt::getHighBitsSet(64, 32)) &&
1418     DAG.MaskedValueIsZero(LHS, APInt::getHighBitsSet(64, 32))) {
1419 
1420     SDValue Res = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1421                               LHS_Lo, RHS_Lo);
1422 
1423     SDValue DIV = DAG.getNode(ISD::BUILD_PAIR, DL, VT, Res.getValue(0), zero);
1424     SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, Res.getValue(1), zero);
1425     Results.push_back(DIV);
1426     Results.push_back(REM);
1427     return;
1428   }
1429 
1430   // Get Speculative values
1431   SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
1432   SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
1433 
1434   SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, zero, REM_Part, LHS_Hi, ISD::SETEQ);
1435   SDValue REM = DAG.getNode(ISD::BUILD_PAIR, DL, VT, REM_Lo, zero);
1436 
1437   SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, zero, DIV_Part, zero, ISD::SETEQ);
1438   SDValue DIV_Lo = zero;
1439 
1440   const unsigned halfBitWidth = HalfVT.getSizeInBits();
1441 
1442   for (unsigned i = 0; i < halfBitWidth; ++i) {
1443     const unsigned bitPos = halfBitWidth - i - 1;
1444     SDValue POS = DAG.getConstant(bitPos, DL, HalfVT);
1445     // Get value of high bit
1446     SDValue HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
1447     HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, one);
1448     HBit = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, HBit);
1449 
1450     // Shift
1451     REM = DAG.getNode(ISD::SHL, DL, VT, REM, DAG.getConstant(1, DL, VT));
1452     // Add LHS high bit
1453     REM = DAG.getNode(ISD::OR, DL, VT, REM, HBit);
1454 
1455     SDValue BIT = DAG.getConstant(1 << bitPos, DL, HalfVT);
1456     SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, zero, ISD::SETUGE);
1457 
1458     DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
1459 
1460     // Update REM
1461     SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
1462     REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETUGE);
1463   }
1464 
1465   SDValue DIV = DAG.getNode(ISD::BUILD_PAIR, DL, VT, DIV_Lo, DIV_Hi);
1466   Results.push_back(DIV);
1467   Results.push_back(REM);
1468 }
1469 
1470 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1471                                            SelectionDAG &DAG) const {
1472   SDLoc DL(Op);
1473   EVT VT = Op.getValueType();
1474 
1475   if (VT == MVT::i64) {
1476     SmallVector<SDValue, 2> Results;
1477     LowerUDIVREM64(Op, DAG, Results);
1478     return DAG.getMergeValues(Results, DL);
1479   }
1480 
1481   SDValue Num = Op.getOperand(0);
1482   SDValue Den = Op.getOperand(1);
1483 
1484   if (VT == MVT::i32) {
1485     if (DAG.MaskedValueIsZero(Num, APInt::getHighBitsSet(32, 8)) &&
1486         DAG.MaskedValueIsZero(Den, APInt::getHighBitsSet(32, 8))) {
1487       // TODO: We technically could do this for i64, but shouldn't that just be
1488       // handled by something generally reducing 64-bit division on 32-bit
1489       // values to 32-bit?
1490       return LowerDIVREM24(Op, DAG, false);
1491     }
1492   }
1493 
1494   // RCP =  URECIP(Den) = 2^32 / Den + e
1495   // e is rounding error.
1496   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1497 
1498   // RCP_LO = mul(RCP, Den) */
1499   SDValue RCP_LO = DAG.getNode(ISD::MUL, DL, VT, RCP, Den);
1500 
1501   // RCP_HI = mulhu (RCP, Den) */
1502   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1503 
1504   // NEG_RCP_LO = -RCP_LO
1505   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
1506                                                      RCP_LO);
1507 
1508   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1509   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1510                                            NEG_RCP_LO, RCP_LO,
1511                                            ISD::SETEQ);
1512   // Calculate the rounding error from the URECIP instruction
1513   // E = mulhu(ABS_RCP_LO, RCP)
1514   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1515 
1516   // RCP_A_E = RCP + E
1517   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1518 
1519   // RCP_S_E = RCP - E
1520   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1521 
1522   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1523   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1524                                      RCP_A_E, RCP_S_E,
1525                                      ISD::SETEQ);
1526   // Quotient = mulhu(Tmp0, Num)
1527   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1528 
1529   // Num_S_Remainder = Quotient * Den
1530   SDValue Num_S_Remainder = DAG.getNode(ISD::MUL, DL, VT, Quotient, Den);
1531 
1532   // Remainder = Num - Num_S_Remainder
1533   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1534 
1535   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1536   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1537                                                  DAG.getConstant(-1, DL, VT),
1538                                                  DAG.getConstant(0, DL, VT),
1539                                                  ISD::SETUGE);
1540   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1541   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1542                                                   Num_S_Remainder,
1543                                                   DAG.getConstant(-1, DL, VT),
1544                                                   DAG.getConstant(0, DL, VT),
1545                                                   ISD::SETUGE);
1546   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1547   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1548                                                Remainder_GE_Zero);
1549 
1550   // Calculate Division result:
1551 
1552   // Quotient_A_One = Quotient + 1
1553   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1554                                        DAG.getConstant(1, DL, VT));
1555 
1556   // Quotient_S_One = Quotient - 1
1557   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1558                                        DAG.getConstant(1, DL, VT));
1559 
1560   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1561   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1562                                      Quotient, Quotient_A_One, ISD::SETEQ);
1563 
1564   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1565   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1566                             Quotient_S_One, Div, ISD::SETEQ);
1567 
1568   // Calculate Rem result:
1569 
1570   // Remainder_S_Den = Remainder - Den
1571   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1572 
1573   // Remainder_A_Den = Remainder + Den
1574   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1575 
1576   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1577   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1578                                     Remainder, Remainder_S_Den, ISD::SETEQ);
1579 
1580   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1581   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1582                             Remainder_A_Den, Rem, ISD::SETEQ);
1583   SDValue Ops[2] = {
1584     Div,
1585     Rem
1586   };
1587   return DAG.getMergeValues(Ops, DL);
1588 }
1589 
1590 SDValue AMDGPUTargetLowering::LowerSDIVREM(SDValue Op,
1591                                            SelectionDAG &DAG) const {
1592   SDLoc DL(Op);
1593   EVT VT = Op.getValueType();
1594 
1595   SDValue LHS = Op.getOperand(0);
1596   SDValue RHS = Op.getOperand(1);
1597 
1598   SDValue Zero = DAG.getConstant(0, DL, VT);
1599   SDValue NegOne = DAG.getConstant(-1, DL, VT);
1600 
1601   if (VT == MVT::i32 &&
1602       DAG.ComputeNumSignBits(LHS) > 8 &&
1603       DAG.ComputeNumSignBits(RHS) > 8) {
1604     return LowerDIVREM24(Op, DAG, true);
1605   }
1606   if (VT == MVT::i64 &&
1607       DAG.ComputeNumSignBits(LHS) > 32 &&
1608       DAG.ComputeNumSignBits(RHS) > 32) {
1609     EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1610 
1611     //HiLo split
1612     SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1613     SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1614     SDValue DIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1615                                  LHS_Lo, RHS_Lo);
1616     SDValue Res[2] = {
1617       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(0)),
1618       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(1))
1619     };
1620     return DAG.getMergeValues(Res, DL);
1621   }
1622 
1623   SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
1624   SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
1625   SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
1626   SDValue RSign = LHSign; // Remainder sign is the same as LHS
1627 
1628   LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
1629   RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
1630 
1631   LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
1632   RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
1633 
1634   SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
1635   SDValue Rem = Div.getValue(1);
1636 
1637   Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
1638   Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
1639 
1640   Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
1641   Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
1642 
1643   SDValue Res[2] = {
1644     Div,
1645     Rem
1646   };
1647   return DAG.getMergeValues(Res, DL);
1648 }
1649 
1650 // (frem x, y) -> (fsub x, (fmul (ftrunc (fdiv x, y)), y))
1651 SDValue AMDGPUTargetLowering::LowerFREM(SDValue Op, SelectionDAG &DAG) const {
1652   SDLoc SL(Op);
1653   EVT VT = Op.getValueType();
1654   SDValue X = Op.getOperand(0);
1655   SDValue Y = Op.getOperand(1);
1656 
1657   // TODO: Should this propagate fast-math-flags?
1658 
1659   SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y);
1660   SDValue Floor = DAG.getNode(ISD::FTRUNC, SL, VT, Div);
1661   SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Floor, Y);
1662 
1663   return DAG.getNode(ISD::FSUB, SL, VT, X, Mul);
1664 }
1665 
1666 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
1667   SDLoc SL(Op);
1668   SDValue Src = Op.getOperand(0);
1669 
1670   // result = trunc(src)
1671   // if (src > 0.0 && src != result)
1672   //   result += 1.0
1673 
1674   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1675 
1676   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
1677   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1678 
1679   EVT SetCCVT =
1680       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
1681 
1682   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
1683   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1684   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1685 
1686   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
1687   // TODO: Should this propagate fast-math-flags?
1688   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1689 }
1690 
1691 static SDValue extractF64Exponent(SDValue Hi, SDLoc SL, SelectionDAG &DAG) {
1692   const unsigned FractBits = 52;
1693   const unsigned ExpBits = 11;
1694 
1695   SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
1696                                 Hi,
1697                                 DAG.getConstant(FractBits - 32, SL, MVT::i32),
1698                                 DAG.getConstant(ExpBits, SL, MVT::i32));
1699   SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
1700                             DAG.getConstant(1023, SL, MVT::i32));
1701 
1702   return Exp;
1703 }
1704 
1705 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
1706   SDLoc SL(Op);
1707   SDValue Src = Op.getOperand(0);
1708 
1709   assert(Op.getValueType() == MVT::f64);
1710 
1711   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1712   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1713 
1714   SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1715 
1716   // Extract the upper half, since this is where we will find the sign and
1717   // exponent.
1718   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
1719 
1720   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
1721 
1722   const unsigned FractBits = 52;
1723 
1724   // Extract the sign bit.
1725   const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, SL, MVT::i32);
1726   SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
1727 
1728   // Extend back to to 64-bits.
1729   SDValue SignBit64 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
1730                                   Zero, SignBit);
1731   SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
1732 
1733   SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
1734   const SDValue FractMask
1735     = DAG.getConstant((UINT64_C(1) << FractBits) - 1, SL, MVT::i64);
1736 
1737   SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
1738   SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
1739   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
1740 
1741   EVT SetCCVT =
1742       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
1743 
1744   const SDValue FiftyOne = DAG.getConstant(FractBits - 1, SL, MVT::i32);
1745 
1746   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1747   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1748 
1749   SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
1750   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
1751 
1752   return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
1753 }
1754 
1755 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
1756   SDLoc SL(Op);
1757   SDValue Src = Op.getOperand(0);
1758 
1759   assert(Op.getValueType() == MVT::f64);
1760 
1761   APFloat C1Val(APFloat::IEEEdouble, "0x1.0p+52");
1762   SDValue C1 = DAG.getConstantFP(C1Val, SL, MVT::f64);
1763   SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
1764 
1765   // TODO: Should this propagate fast-math-flags?
1766 
1767   SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
1768   SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
1769 
1770   SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
1771 
1772   APFloat C2Val(APFloat::IEEEdouble, "0x1.fffffffffffffp+51");
1773   SDValue C2 = DAG.getConstantFP(C2Val, SL, MVT::f64);
1774 
1775   EVT SetCCVT =
1776       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
1777   SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
1778 
1779   return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
1780 }
1781 
1782 SDValue AMDGPUTargetLowering::LowerFNEARBYINT(SDValue Op, SelectionDAG &DAG) const {
1783   // FNEARBYINT and FRINT are the same, except in their handling of FP
1784   // exceptions. Those aren't really meaningful for us, and OpenCL only has
1785   // rint, so just treat them as equivalent.
1786   return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
1787 }
1788 
1789 // XXX - May require not supporting f32 denormals?
1790 SDValue AMDGPUTargetLowering::LowerFROUND32(SDValue Op, SelectionDAG &DAG) const {
1791   SDLoc SL(Op);
1792   SDValue X = Op.getOperand(0);
1793 
1794   SDValue T = DAG.getNode(ISD::FTRUNC, SL, MVT::f32, X);
1795 
1796   // TODO: Should this propagate fast-math-flags?
1797 
1798   SDValue Diff = DAG.getNode(ISD::FSUB, SL, MVT::f32, X, T);
1799 
1800   SDValue AbsDiff = DAG.getNode(ISD::FABS, SL, MVT::f32, Diff);
1801 
1802   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f32);
1803   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1804   const SDValue Half = DAG.getConstantFP(0.5, SL, MVT::f32);
1805 
1806   SDValue SignOne = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f32, One, X);
1807 
1808   EVT SetCCVT =
1809       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1810 
1811   SDValue Cmp = DAG.getSetCC(SL, SetCCVT, AbsDiff, Half, ISD::SETOGE);
1812 
1813   SDValue Sel = DAG.getNode(ISD::SELECT, SL, MVT::f32, Cmp, SignOne, Zero);
1814 
1815   return DAG.getNode(ISD::FADD, SL, MVT::f32, T, Sel);
1816 }
1817 
1818 SDValue AMDGPUTargetLowering::LowerFROUND64(SDValue Op, SelectionDAG &DAG) const {
1819   SDLoc SL(Op);
1820   SDValue X = Op.getOperand(0);
1821 
1822   SDValue L = DAG.getNode(ISD::BITCAST, SL, MVT::i64, X);
1823 
1824   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1825   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1826   const SDValue NegOne = DAG.getConstant(-1, SL, MVT::i32);
1827   const SDValue FiftyOne = DAG.getConstant(51, SL, MVT::i32);
1828   EVT SetCCVT =
1829       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
1830 
1831   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1832 
1833   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC, One);
1834 
1835   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
1836 
1837   const SDValue Mask = DAG.getConstant(INT64_C(0x000fffffffffffff), SL,
1838                                        MVT::i64);
1839 
1840   SDValue M = DAG.getNode(ISD::SRA, SL, MVT::i64, Mask, Exp);
1841   SDValue D = DAG.getNode(ISD::SRA, SL, MVT::i64,
1842                           DAG.getConstant(INT64_C(0x0008000000000000), SL,
1843                                           MVT::i64),
1844                           Exp);
1845 
1846   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, L, M);
1847   SDValue Tmp1 = DAG.getSetCC(SL, SetCCVT,
1848                               DAG.getConstant(0, SL, MVT::i64), Tmp0,
1849                               ISD::SETNE);
1850 
1851   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, Tmp1,
1852                              D, DAG.getConstant(0, SL, MVT::i64));
1853   SDValue K = DAG.getNode(ISD::ADD, SL, MVT::i64, L, Tmp2);
1854 
1855   K = DAG.getNode(ISD::AND, SL, MVT::i64, K, DAG.getNOT(SL, M, MVT::i64));
1856   K = DAG.getNode(ISD::BITCAST, SL, MVT::f64, K);
1857 
1858   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
1859   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
1860   SDValue ExpEqNegOne = DAG.getSetCC(SL, SetCCVT, NegOne, Exp, ISD::SETEQ);
1861 
1862   SDValue Mag = DAG.getNode(ISD::SELECT, SL, MVT::f64,
1863                             ExpEqNegOne,
1864                             DAG.getConstantFP(1.0, SL, MVT::f64),
1865                             DAG.getConstantFP(0.0, SL, MVT::f64));
1866 
1867   SDValue S = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, Mag, X);
1868 
1869   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpLt0, S, K);
1870   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpGt51, X, K);
1871 
1872   return K;
1873 }
1874 
1875 SDValue AMDGPUTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
1876   EVT VT = Op.getValueType();
1877 
1878   if (VT == MVT::f32)
1879     return LowerFROUND32(Op, DAG);
1880 
1881   if (VT == MVT::f64)
1882     return LowerFROUND64(Op, DAG);
1883 
1884   llvm_unreachable("unhandled type");
1885 }
1886 
1887 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
1888   SDLoc SL(Op);
1889   SDValue Src = Op.getOperand(0);
1890 
1891   // result = trunc(src);
1892   // if (src < 0.0 && src != result)
1893   //   result += -1.0.
1894 
1895   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1896 
1897   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
1898   const SDValue NegOne = DAG.getConstantFP(-1.0, SL, MVT::f64);
1899 
1900   EVT SetCCVT =
1901       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
1902 
1903   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
1904   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1905   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1906 
1907   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
1908   // TODO: Should this propagate fast-math-flags?
1909   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1910 }
1911 
1912 SDValue AMDGPUTargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
1913   SDLoc SL(Op);
1914   SDValue Src = Op.getOperand(0);
1915   bool ZeroUndef = Op.getOpcode() == ISD::CTLZ_ZERO_UNDEF;
1916 
1917   if (ZeroUndef && Src.getValueType() == MVT::i32)
1918     return DAG.getNode(AMDGPUISD::FFBH_U32, SL, MVT::i32, Src);
1919 
1920   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
1921 
1922   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1923   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1924 
1925   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1926   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1927 
1928   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
1929                                    *DAG.getContext(), MVT::i32);
1930 
1931   SDValue Hi0 = DAG.getSetCC(SL, SetCCVT, Hi, Zero, ISD::SETEQ);
1932 
1933   SDValue CtlzLo = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i32, Lo);
1934   SDValue CtlzHi = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i32, Hi);
1935 
1936   const SDValue Bits32 = DAG.getConstant(32, SL, MVT::i32);
1937   SDValue Add = DAG.getNode(ISD::ADD, SL, MVT::i32, CtlzLo, Bits32);
1938 
1939   // ctlz(x) = hi_32(x) == 0 ? ctlz(lo_32(x)) + 32 : ctlz(hi_32(x))
1940   SDValue NewCtlz = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0, Add, CtlzHi);
1941 
1942   if (!ZeroUndef) {
1943     // Test if the full 64-bit input is zero.
1944 
1945     // FIXME: DAG combines turn what should be an s_and_b64 into a v_or_b32,
1946     // which we probably don't want.
1947     SDValue Lo0 = DAG.getSetCC(SL, SetCCVT, Lo, Zero, ISD::SETEQ);
1948     SDValue SrcIsZero = DAG.getNode(ISD::AND, SL, SetCCVT, Lo0, Hi0);
1949 
1950     // TODO: If i64 setcc is half rate, it can result in 1 fewer instruction
1951     // with the same cycles, otherwise it is slower.
1952     // SDValue SrcIsZero = DAG.getSetCC(SL, SetCCVT, Src,
1953     // DAG.getConstant(0, SL, MVT::i64), ISD::SETEQ);
1954 
1955     const SDValue Bits32 = DAG.getConstant(64, SL, MVT::i32);
1956 
1957     // The instruction returns -1 for 0 input, but the defined intrinsic
1958     // behavior is to return the number of bits.
1959     NewCtlz = DAG.getNode(ISD::SELECT, SL, MVT::i32,
1960                           SrcIsZero, Bits32, NewCtlz);
1961   }
1962 
1963   return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, NewCtlz);
1964 }
1965 
1966 SDValue AMDGPUTargetLowering::LowerINT_TO_FP32(SDValue Op, SelectionDAG &DAG,
1967                                                bool Signed) const {
1968   // Unsigned
1969   // cul2f(ulong u)
1970   //{
1971   //  uint lz = clz(u);
1972   //  uint e = (u != 0) ? 127U + 63U - lz : 0;
1973   //  u = (u << lz) & 0x7fffffffffffffffUL;
1974   //  ulong t = u & 0xffffffffffUL;
1975   //  uint v = (e << 23) | (uint)(u >> 40);
1976   //  uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
1977   //  return as_float(v + r);
1978   //}
1979   // Signed
1980   // cl2f(long l)
1981   //{
1982   //  long s = l >> 63;
1983   //  float r = cul2f((l + s) ^ s);
1984   //  return s ? -r : r;
1985   //}
1986 
1987   SDLoc SL(Op);
1988   SDValue Src = Op.getOperand(0);
1989   SDValue L = Src;
1990 
1991   SDValue S;
1992   if (Signed) {
1993     const SDValue SignBit = DAG.getConstant(63, SL, MVT::i64);
1994     S = DAG.getNode(ISD::SRA, SL, MVT::i64, L, SignBit);
1995 
1996     SDValue LPlusS = DAG.getNode(ISD::ADD, SL, MVT::i64, L, S);
1997     L = DAG.getNode(ISD::XOR, SL, MVT::i64, LPlusS, S);
1998   }
1999 
2000   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2001                                    *DAG.getContext(), MVT::f32);
2002 
2003 
2004   SDValue ZeroI32 = DAG.getConstant(0, SL, MVT::i32);
2005   SDValue ZeroI64 = DAG.getConstant(0, SL, MVT::i64);
2006   SDValue LZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i64, L);
2007   LZ = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LZ);
2008 
2009   SDValue K = DAG.getConstant(127U + 63U, SL, MVT::i32);
2010   SDValue E = DAG.getSelect(SL, MVT::i32,
2011     DAG.getSetCC(SL, SetCCVT, L, ZeroI64, ISD::SETNE),
2012     DAG.getNode(ISD::SUB, SL, MVT::i32, K, LZ),
2013     ZeroI32);
2014 
2015   SDValue U = DAG.getNode(ISD::AND, SL, MVT::i64,
2016     DAG.getNode(ISD::SHL, SL, MVT::i64, L, LZ),
2017     DAG.getConstant((-1ULL) >> 1, SL, MVT::i64));
2018 
2019   SDValue T = DAG.getNode(ISD::AND, SL, MVT::i64, U,
2020                           DAG.getConstant(0xffffffffffULL, SL, MVT::i64));
2021 
2022   SDValue UShl = DAG.getNode(ISD::SRL, SL, MVT::i64,
2023                              U, DAG.getConstant(40, SL, MVT::i64));
2024 
2025   SDValue V = DAG.getNode(ISD::OR, SL, MVT::i32,
2026     DAG.getNode(ISD::SHL, SL, MVT::i32, E, DAG.getConstant(23, SL, MVT::i32)),
2027     DAG.getNode(ISD::TRUNCATE, SL, MVT::i32,  UShl));
2028 
2029   SDValue C = DAG.getConstant(0x8000000000ULL, SL, MVT::i64);
2030   SDValue RCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETUGT);
2031   SDValue TCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETEQ);
2032 
2033   SDValue One = DAG.getConstant(1, SL, MVT::i32);
2034 
2035   SDValue VTrunc1 = DAG.getNode(ISD::AND, SL, MVT::i32, V, One);
2036 
2037   SDValue R = DAG.getSelect(SL, MVT::i32,
2038     RCmp,
2039     One,
2040     DAG.getSelect(SL, MVT::i32, TCmp, VTrunc1, ZeroI32));
2041   R = DAG.getNode(ISD::ADD, SL, MVT::i32, V, R);
2042   R = DAG.getNode(ISD::BITCAST, SL, MVT::f32, R);
2043 
2044   if (!Signed)
2045     return R;
2046 
2047   SDValue RNeg = DAG.getNode(ISD::FNEG, SL, MVT::f32, R);
2048   return DAG.getSelect(SL, MVT::f32, DAG.getSExtOrTrunc(S, SL, SetCCVT), RNeg, R);
2049 }
2050 
2051 SDValue AMDGPUTargetLowering::LowerINT_TO_FP64(SDValue Op, SelectionDAG &DAG,
2052                                                bool Signed) const {
2053   SDLoc SL(Op);
2054   SDValue Src = Op.getOperand(0);
2055 
2056   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2057 
2058   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2059                            DAG.getConstant(0, SL, MVT::i32));
2060   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2061                            DAG.getConstant(1, SL, MVT::i32));
2062 
2063   SDValue CvtHi = DAG.getNode(Signed ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
2064                               SL, MVT::f64, Hi);
2065 
2066   SDValue CvtLo = DAG.getNode(ISD::UINT_TO_FP, SL, MVT::f64, Lo);
2067 
2068   SDValue LdExp = DAG.getNode(AMDGPUISD::LDEXP, SL, MVT::f64, CvtHi,
2069                               DAG.getConstant(32, SL, MVT::i32));
2070   // TODO: Should this propagate fast-math-flags?
2071   return DAG.getNode(ISD::FADD, SL, MVT::f64, LdExp, CvtLo);
2072 }
2073 
2074 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
2075                                                SelectionDAG &DAG) const {
2076   assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2077          "operation should be legal");
2078 
2079   EVT DestVT = Op.getValueType();
2080   if (DestVT == MVT::f64)
2081     return LowerINT_TO_FP64(Op, DAG, false);
2082 
2083   if (DestVT == MVT::f32)
2084     return LowerINT_TO_FP32(Op, DAG, false);
2085 
2086   return SDValue();
2087 }
2088 
2089 SDValue AMDGPUTargetLowering::LowerSINT_TO_FP(SDValue Op,
2090                                               SelectionDAG &DAG) const {
2091   assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2092          "operation should be legal");
2093 
2094   EVT DestVT = Op.getValueType();
2095   if (DestVT == MVT::f32)
2096     return LowerINT_TO_FP32(Op, DAG, true);
2097 
2098   if (DestVT == MVT::f64)
2099     return LowerINT_TO_FP64(Op, DAG, true);
2100 
2101   return SDValue();
2102 }
2103 
2104 SDValue AMDGPUTargetLowering::LowerFP64_TO_INT(SDValue Op, SelectionDAG &DAG,
2105                                                bool Signed) const {
2106   SDLoc SL(Op);
2107 
2108   SDValue Src = Op.getOperand(0);
2109 
2110   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2111 
2112   SDValue K0 = DAG.getConstantFP(BitsToDouble(UINT64_C(0x3df0000000000000)), SL,
2113                                  MVT::f64);
2114   SDValue K1 = DAG.getConstantFP(BitsToDouble(UINT64_C(0xc1f0000000000000)), SL,
2115                                  MVT::f64);
2116   // TODO: Should this propagate fast-math-flags?
2117   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, Trunc, K0);
2118 
2119   SDValue FloorMul = DAG.getNode(ISD::FFLOOR, SL, MVT::f64, Mul);
2120 
2121 
2122   SDValue Fma = DAG.getNode(ISD::FMA, SL, MVT::f64, FloorMul, K1, Trunc);
2123 
2124   SDValue Hi = DAG.getNode(Signed ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, SL,
2125                            MVT::i32, FloorMul);
2126   SDValue Lo = DAG.getNode(ISD::FP_TO_UINT, SL, MVT::i32, Fma);
2127 
2128   SDValue Result = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Lo, Hi);
2129 
2130   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Result);
2131 }
2132 
2133 SDValue AMDGPUTargetLowering::LowerFP_TO_SINT(SDValue Op,
2134                                               SelectionDAG &DAG) const {
2135   SDValue Src = Op.getOperand(0);
2136 
2137   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2138     return LowerFP64_TO_INT(Op, DAG, true);
2139 
2140   return SDValue();
2141 }
2142 
2143 SDValue AMDGPUTargetLowering::LowerFP_TO_UINT(SDValue Op,
2144                                               SelectionDAG &DAG) const {
2145   SDValue Src = Op.getOperand(0);
2146 
2147   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2148     return LowerFP64_TO_INT(Op, DAG, false);
2149 
2150   return SDValue();
2151 }
2152 
2153 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
2154                                                      SelectionDAG &DAG) const {
2155   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2156   MVT VT = Op.getSimpleValueType();
2157   MVT ScalarVT = VT.getScalarType();
2158 
2159   if (!VT.isVector())
2160     return SDValue();
2161 
2162   SDValue Src = Op.getOperand(0);
2163   SDLoc DL(Op);
2164 
2165   // TODO: Don't scalarize on Evergreen?
2166   unsigned NElts = VT.getVectorNumElements();
2167   SmallVector<SDValue, 8> Args;
2168   DAG.ExtractVectorElements(Src, Args, 0, NElts);
2169 
2170   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
2171   for (unsigned I = 0; I < NElts; ++I)
2172     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
2173 
2174   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args);
2175 }
2176 
2177 //===----------------------------------------------------------------------===//
2178 // Custom DAG optimizations
2179 //===----------------------------------------------------------------------===//
2180 
2181 static bool isU24(SDValue Op, SelectionDAG &DAG) {
2182   APInt KnownZero, KnownOne;
2183   EVT VT = Op.getValueType();
2184   DAG.computeKnownBits(Op, KnownZero, KnownOne);
2185 
2186   return (VT.getSizeInBits() - KnownZero.countLeadingOnes()) <= 24;
2187 }
2188 
2189 static bool isI24(SDValue Op, SelectionDAG &DAG) {
2190   EVT VT = Op.getValueType();
2191 
2192   // In order for this to be a signed 24-bit value, bit 23, must
2193   // be a sign bit.
2194   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
2195                                      // as unsigned 24-bit values.
2196          (VT.getSizeInBits() - DAG.ComputeNumSignBits(Op)) < 24;
2197 }
2198 
2199 static void simplifyI24(SDValue Op, TargetLowering::DAGCombinerInfo &DCI) {
2200 
2201   SelectionDAG &DAG = DCI.DAG;
2202   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2203   EVT VT = Op.getValueType();
2204 
2205   APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
2206   APInt KnownZero, KnownOne;
2207   TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
2208   if (TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
2209     DCI.CommitTargetLoweringOpt(TLO);
2210 }
2211 
2212 template <typename IntTy>
2213 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0,
2214                                uint32_t Offset, uint32_t Width, SDLoc DL) {
2215   if (Width + Offset < 32) {
2216     uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
2217     IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
2218     return DAG.getConstant(Result, DL, MVT::i32);
2219   }
2220 
2221   return DAG.getConstant(Src0 >> Offset, DL, MVT::i32);
2222 }
2223 
2224 static bool usesAllNormalStores(SDNode *LoadVal) {
2225   for (SDNode::use_iterator I = LoadVal->use_begin(); !I.atEnd(); ++I) {
2226     if (!ISD::isNormalStore(*I))
2227       return false;
2228   }
2229 
2230   return true;
2231 }
2232 
2233 // If we have a copy of an illegal type, replace it with a load / store of an
2234 // equivalently sized legal type. This avoids intermediate bit pack / unpack
2235 // instructions emitted when handling extloads and truncstores. Ideally we could
2236 // recognize the pack / unpack pattern to eliminate it.
2237 SDValue AMDGPUTargetLowering::performStoreCombine(SDNode *N,
2238                                                   DAGCombinerInfo &DCI) const {
2239   if (!DCI.isBeforeLegalize())
2240     return SDValue();
2241 
2242   StoreSDNode *SN = cast<StoreSDNode>(N);
2243   SDValue Value = SN->getValue();
2244   EVT VT = Value.getValueType();
2245 
2246   if (isTypeLegal(VT) || SN->isVolatile() ||
2247       !ISD::isNormalLoad(Value.getNode()) || VT.getSizeInBits() < 8)
2248     return SDValue();
2249 
2250   LoadSDNode *LoadVal = cast<LoadSDNode>(Value);
2251   if (LoadVal->isVolatile() || !usesAllNormalStores(LoadVal))
2252     return SDValue();
2253 
2254   EVT MemVT = LoadVal->getMemoryVT();
2255 
2256   SDLoc SL(N);
2257   SelectionDAG &DAG = DCI.DAG;
2258   EVT LoadVT = getEquivalentMemType(*DAG.getContext(), MemVT);
2259 
2260   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
2261                                 LoadVT, SL,
2262                                 LoadVal->getChain(),
2263                                 LoadVal->getBasePtr(),
2264                                 LoadVal->getOffset(),
2265                                 LoadVT,
2266                                 LoadVal->getMemOperand());
2267 
2268   SDValue CastLoad = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad.getValue(0));
2269   DCI.CombineTo(LoadVal, CastLoad, NewLoad.getValue(1), false);
2270 
2271   return DAG.getStore(SN->getChain(), SL, NewLoad,
2272                       SN->getBasePtr(), SN->getMemOperand());
2273 }
2274 
2275 // TODO: Should repeat for other bit ops.
2276 SDValue AMDGPUTargetLowering::performAndCombine(SDNode *N,
2277                                                 DAGCombinerInfo &DCI) const {
2278   if (N->getValueType(0) != MVT::i64)
2279     return SDValue();
2280 
2281   // Break up 64-bit and of a constant into two 32-bit ands. This will typically
2282   // happen anyway for a VALU 64-bit and. This exposes other 32-bit integer
2283   // combine opportunities since most 64-bit operations are decomposed this way.
2284   // TODO: We won't want this for SALU especially if it is an inline immediate.
2285   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2286   if (!RHS)
2287     return SDValue();
2288 
2289   uint64_t Val = RHS->getZExtValue();
2290   if (Lo_32(Val) != 0 && Hi_32(Val) != 0 && !RHS->hasOneUse()) {
2291     // If either half of the constant is 0, this is really a 32-bit and, so
2292     // split it. If we can re-use the full materialized constant, keep it.
2293     return SDValue();
2294   }
2295 
2296   SDLoc SL(N);
2297   SelectionDAG &DAG = DCI.DAG;
2298 
2299   SDValue Lo, Hi;
2300   std::tie(Lo, Hi) = split64BitValue(N->getOperand(0), DAG);
2301 
2302   SDValue LoRHS = DAG.getConstant(Lo_32(Val), SL, MVT::i32);
2303   SDValue HiRHS = DAG.getConstant(Hi_32(Val), SL, MVT::i32);
2304 
2305   SDValue LoAnd = DAG.getNode(ISD::AND, SL, MVT::i32, Lo, LoRHS);
2306   SDValue HiAnd = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, HiRHS);
2307 
2308   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, LoAnd, HiAnd);
2309   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2310 }
2311 
2312 SDValue AMDGPUTargetLowering::performShlCombine(SDNode *N,
2313                                                 DAGCombinerInfo &DCI) const {
2314   if (N->getValueType(0) != MVT::i64)
2315     return SDValue();
2316 
2317   // i64 (shl x, C) -> (build_pair 0, (shl x, C -32))
2318 
2319   // On some subtargets, 64-bit shift is a quarter rate instruction. In the
2320   // common case, splitting this into a move and a 32-bit shift is faster and
2321   // the same code size.
2322   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2323   if (!RHS)
2324     return SDValue();
2325 
2326   unsigned RHSVal = RHS->getZExtValue();
2327   if (RHSVal < 32)
2328     return SDValue();
2329 
2330   SDValue LHS = N->getOperand(0);
2331 
2332   SDLoc SL(N);
2333   SelectionDAG &DAG = DCI.DAG;
2334 
2335   SDValue ShiftAmt = DAG.getConstant(RHSVal - 32, SL, MVT::i32);
2336 
2337   SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
2338   SDValue NewShift = DAG.getNode(ISD::SHL, SL, MVT::i32, Lo, ShiftAmt);
2339 
2340   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2341 
2342   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Zero, NewShift);
2343   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2344 }
2345 
2346 SDValue AMDGPUTargetLowering::performSraCombine(SDNode *N,
2347                                                 DAGCombinerInfo &DCI) const {
2348   if (N->getValueType(0) != MVT::i64)
2349     return SDValue();
2350 
2351   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2352   if (!RHS)
2353     return SDValue();
2354 
2355   SelectionDAG &DAG = DCI.DAG;
2356   SDLoc SL(N);
2357   unsigned RHSVal = RHS->getZExtValue();
2358 
2359   // (sra i64:x, 32) -> build_pair x, (sra hi_32(x), 31)
2360   if (RHSVal == 32) {
2361     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
2362     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
2363                                    DAG.getConstant(31, SL, MVT::i32));
2364 
2365     SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
2366                                    Hi, NewShift);
2367     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
2368   }
2369 
2370   // (sra i64:x, 63) -> build_pair (sra hi_32(x), 31), (sra hi_32(x), 31)
2371   if (RHSVal == 63) {
2372     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
2373     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
2374                                    DAG.getConstant(31, SL, MVT::i32));
2375     SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
2376                                    NewShift, NewShift);
2377     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
2378   }
2379 
2380   return SDValue();
2381 }
2382 
2383 SDValue AMDGPUTargetLowering::performSrlCombine(SDNode *N,
2384                                                 DAGCombinerInfo &DCI) const {
2385   if (N->getValueType(0) != MVT::i64)
2386     return SDValue();
2387 
2388   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2389   if (!RHS)
2390     return SDValue();
2391 
2392   unsigned ShiftAmt = RHS->getZExtValue();
2393   if (ShiftAmt < 32)
2394     return SDValue();
2395 
2396   // srl i64:x, C for C >= 32
2397   // =>
2398   //   build_pair (srl hi_32(x), C - 32), 0
2399 
2400   SelectionDAG &DAG = DCI.DAG;
2401   SDLoc SL(N);
2402 
2403   SDValue One = DAG.getConstant(1, SL, MVT::i32);
2404   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2405 
2406   SDValue VecOp = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, N->getOperand(0));
2407   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32,
2408                            VecOp, One);
2409 
2410   SDValue NewConst = DAG.getConstant(ShiftAmt - 32, SL, MVT::i32);
2411   SDValue NewShift = DAG.getNode(ISD::SRL, SL, MVT::i32, Hi, NewConst);
2412 
2413   SDValue BuildPair = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
2414                                   NewShift, Zero);
2415 
2416   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildPair);
2417 }
2418 
2419 SDValue AMDGPUTargetLowering::performMulCombine(SDNode *N,
2420                                                 DAGCombinerInfo &DCI) const {
2421   EVT VT = N->getValueType(0);
2422 
2423   if (VT.isVector() || VT.getSizeInBits() > 32)
2424     return SDValue();
2425 
2426   SelectionDAG &DAG = DCI.DAG;
2427   SDLoc DL(N);
2428 
2429   SDValue N0 = N->getOperand(0);
2430   SDValue N1 = N->getOperand(1);
2431   SDValue Mul;
2432 
2433   if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
2434     N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
2435     N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
2436     Mul = DAG.getNode(AMDGPUISD::MUL_U24, DL, MVT::i32, N0, N1);
2437   } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
2438     N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
2439     N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
2440     Mul = DAG.getNode(AMDGPUISD::MUL_I24, DL, MVT::i32, N0, N1);
2441   } else {
2442     return SDValue();
2443   }
2444 
2445   // We need to use sext even for MUL_U24, because MUL_U24 is used
2446   // for signed multiply of 8 and 16-bit types.
2447   return DAG.getSExtOrTrunc(Mul, DL, VT);
2448 }
2449 
2450 static bool isNegativeOne(SDValue Val) {
2451   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val))
2452     return C->isAllOnesValue();
2453   return false;
2454 }
2455 
2456 static bool isCtlzOpc(unsigned Opc) {
2457   return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_UNDEF;
2458 }
2459 
2460 // Get FFBH node if the incoming op may have been type legalized from a smaller
2461 // type VT.
2462 // Need to match pre-legalized type because the generic legalization inserts the
2463 // add/sub between the select and compare.
2464 static SDValue getFFBH_U32(const TargetLowering &TLI,
2465                            SelectionDAG &DAG, SDLoc SL, SDValue Op) {
2466   EVT VT = Op.getValueType();
2467   EVT LegalVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2468   if (LegalVT != MVT::i32)
2469     return SDValue();
2470 
2471   if (VT != MVT::i32)
2472     Op = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Op);
2473 
2474   SDValue FFBH = DAG.getNode(AMDGPUISD::FFBH_U32, SL, MVT::i32, Op);
2475   if (VT != MVT::i32)
2476     FFBH = DAG.getNode(ISD::TRUNCATE, SL, VT, FFBH);
2477 
2478   return FFBH;
2479 }
2480 
2481 // The native instructions return -1 on 0 input. Optimize out a select that
2482 // produces -1 on 0.
2483 //
2484 // TODO: If zero is not undef, we could also do this if the output is compared
2485 // against the bitwidth.
2486 //
2487 // TODO: Should probably combine against FFBH_U32 instead of ctlz directly.
2488 SDValue AMDGPUTargetLowering::performCtlzCombine(SDLoc SL,
2489                                                  SDValue Cond,
2490                                                  SDValue LHS,
2491                                                  SDValue RHS,
2492                                                  DAGCombinerInfo &DCI) const {
2493   ConstantSDNode *CmpRhs = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2494   if (!CmpRhs || !CmpRhs->isNullValue())
2495     return SDValue();
2496 
2497   SelectionDAG &DAG = DCI.DAG;
2498   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
2499   SDValue CmpLHS = Cond.getOperand(0);
2500 
2501   // select (setcc x, 0, eq), -1, (ctlz_zero_undef x) -> ffbh_u32 x
2502   if (CCOpcode == ISD::SETEQ &&
2503       isCtlzOpc(RHS.getOpcode()) &&
2504       RHS.getOperand(0) == CmpLHS &&
2505       isNegativeOne(LHS)) {
2506     return getFFBH_U32(*this, DAG, SL, CmpLHS);
2507   }
2508 
2509   // select (setcc x, 0, ne), (ctlz_zero_undef x), -1 -> ffbh_u32 x
2510   if (CCOpcode == ISD::SETNE &&
2511       isCtlzOpc(LHS.getOpcode()) &&
2512       LHS.getOperand(0) == CmpLHS &&
2513       isNegativeOne(RHS)) {
2514     return getFFBH_U32(*this, DAG, SL, CmpLHS);
2515   }
2516 
2517   return SDValue();
2518 }
2519 
2520 SDValue AMDGPUTargetLowering::performSelectCombine(SDNode *N,
2521                                                    DAGCombinerInfo &DCI) const {
2522   SDValue Cond = N->getOperand(0);
2523   if (Cond.getOpcode() != ISD::SETCC)
2524     return SDValue();
2525 
2526   EVT VT = N->getValueType(0);
2527   SDValue LHS = Cond.getOperand(0);
2528   SDValue RHS = Cond.getOperand(1);
2529   SDValue CC = Cond.getOperand(2);
2530 
2531   SDValue True = N->getOperand(1);
2532   SDValue False = N->getOperand(2);
2533 
2534   if (VT == MVT::f32 && Cond.hasOneUse()) {
2535     SDValue MinMax
2536       = CombineFMinMaxLegacy(SDLoc(N), VT, LHS, RHS, True, False, CC, DCI);
2537     // Revisit this node so we can catch min3/max3/med3 patterns.
2538     //DCI.AddToWorklist(MinMax.getNode());
2539     return MinMax;
2540   }
2541 
2542   // There's no reason to not do this if the condition has other uses.
2543   return performCtlzCombine(SDLoc(N), Cond, True, False, DCI);
2544 }
2545 
2546 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
2547                                                 DAGCombinerInfo &DCI) const {
2548   SelectionDAG &DAG = DCI.DAG;
2549   SDLoc DL(N);
2550 
2551   switch(N->getOpcode()) {
2552   default:
2553     break;
2554   case ISD::SHL: {
2555     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2556       break;
2557 
2558     return performShlCombine(N, DCI);
2559   }
2560   case ISD::SRL: {
2561     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2562       break;
2563 
2564     return performSrlCombine(N, DCI);
2565   }
2566   case ISD::SRA: {
2567     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2568       break;
2569 
2570     return performSraCombine(N, DCI);
2571   }
2572   case ISD::AND: {
2573     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2574       break;
2575 
2576     return performAndCombine(N, DCI);
2577   }
2578   case ISD::MUL:
2579     return performMulCombine(N, DCI);
2580   case AMDGPUISD::MUL_I24:
2581   case AMDGPUISD::MUL_U24: {
2582     SDValue N0 = N->getOperand(0);
2583     SDValue N1 = N->getOperand(1);
2584     simplifyI24(N0, DCI);
2585     simplifyI24(N1, DCI);
2586     return SDValue();
2587   }
2588   case ISD::SELECT:
2589     return performSelectCombine(N, DCI);
2590   case AMDGPUISD::BFE_I32:
2591   case AMDGPUISD::BFE_U32: {
2592     assert(!N->getValueType(0).isVector() &&
2593            "Vector handling of BFE not implemented");
2594     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
2595     if (!Width)
2596       break;
2597 
2598     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
2599     if (WidthVal == 0)
2600       return DAG.getConstant(0, DL, MVT::i32);
2601 
2602     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
2603     if (!Offset)
2604       break;
2605 
2606     SDValue BitsFrom = N->getOperand(0);
2607     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
2608 
2609     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
2610 
2611     if (OffsetVal == 0) {
2612       // This is already sign / zero extended, so try to fold away extra BFEs.
2613       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
2614 
2615       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
2616       if (OpSignBits >= SignBits)
2617         return BitsFrom;
2618 
2619       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
2620       if (Signed) {
2621         // This is a sign_extend_inreg. Replace it to take advantage of existing
2622         // DAG Combines. If not eliminated, we will match back to BFE during
2623         // selection.
2624 
2625         // TODO: The sext_inreg of extended types ends, although we can could
2626         // handle them in a single BFE.
2627         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
2628                            DAG.getValueType(SmallVT));
2629       }
2630 
2631       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
2632     }
2633 
2634     if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(BitsFrom)) {
2635       if (Signed) {
2636         return constantFoldBFE<int32_t>(DAG,
2637                                         CVal->getSExtValue(),
2638                                         OffsetVal,
2639                                         WidthVal,
2640                                         DL);
2641       }
2642 
2643       return constantFoldBFE<uint32_t>(DAG,
2644                                        CVal->getZExtValue(),
2645                                        OffsetVal,
2646                                        WidthVal,
2647                                        DL);
2648     }
2649 
2650     if ((OffsetVal + WidthVal) >= 32) {
2651       SDValue ShiftVal = DAG.getConstant(OffsetVal, DL, MVT::i32);
2652       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2653                          BitsFrom, ShiftVal);
2654     }
2655 
2656     if (BitsFrom.hasOneUse()) {
2657       APInt Demanded = APInt::getBitsSet(32,
2658                                          OffsetVal,
2659                                          OffsetVal + WidthVal);
2660 
2661       APInt KnownZero, KnownOne;
2662       TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2663                                             !DCI.isBeforeLegalizeOps());
2664       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2665       if (TLO.ShrinkDemandedConstant(BitsFrom, Demanded) ||
2666           TLI.SimplifyDemandedBits(BitsFrom, Demanded,
2667                                    KnownZero, KnownOne, TLO)) {
2668         DCI.CommitTargetLoweringOpt(TLO);
2669       }
2670     }
2671 
2672     break;
2673   }
2674 
2675   case ISD::STORE:
2676     return performStoreCombine(N, DCI);
2677   }
2678   return SDValue();
2679 }
2680 
2681 //===----------------------------------------------------------------------===//
2682 // Helper functions
2683 //===----------------------------------------------------------------------===//
2684 
2685 void AMDGPUTargetLowering::getOriginalFunctionArgs(
2686                                SelectionDAG &DAG,
2687                                const Function *F,
2688                                const SmallVectorImpl<ISD::InputArg> &Ins,
2689                                SmallVectorImpl<ISD::InputArg> &OrigIns) const {
2690 
2691   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
2692     if (Ins[i].ArgVT == Ins[i].VT) {
2693       OrigIns.push_back(Ins[i]);
2694       continue;
2695     }
2696 
2697     EVT VT;
2698     if (Ins[i].ArgVT.isVector() && !Ins[i].VT.isVector()) {
2699       // Vector has been split into scalars.
2700       VT = Ins[i].ArgVT.getVectorElementType();
2701     } else if (Ins[i].VT.isVector() && Ins[i].ArgVT.isVector() &&
2702                Ins[i].ArgVT.getVectorElementType() !=
2703                Ins[i].VT.getVectorElementType()) {
2704       // Vector elements have been promoted
2705       VT = Ins[i].ArgVT;
2706     } else {
2707       // Vector has been spilt into smaller vectors.
2708       VT = Ins[i].VT;
2709     }
2710 
2711     ISD::InputArg Arg(Ins[i].Flags, VT, VT, Ins[i].Used,
2712                       Ins[i].OrigArgIndex, Ins[i].PartOffset);
2713     OrigIns.push_back(Arg);
2714   }
2715 }
2716 
2717 bool AMDGPUTargetLowering::isHWTrueValue(SDValue Op) const {
2718   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
2719     return CFP->isExactlyValue(1.0);
2720   }
2721   return isAllOnesConstant(Op);
2722 }
2723 
2724 bool AMDGPUTargetLowering::isHWFalseValue(SDValue Op) const {
2725   if (ConstantFPSDNode * CFP = dyn_cast<ConstantFPSDNode>(Op)) {
2726     return CFP->getValueAPF().isZero();
2727   }
2728   return isNullConstant(Op);
2729 }
2730 
2731 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2732                                                   const TargetRegisterClass *RC,
2733                                                    unsigned Reg, EVT VT) const {
2734   MachineFunction &MF = DAG.getMachineFunction();
2735   MachineRegisterInfo &MRI = MF.getRegInfo();
2736   unsigned VirtualRegister;
2737   if (!MRI.isLiveIn(Reg)) {
2738     VirtualRegister = MRI.createVirtualRegister(RC);
2739     MRI.addLiveIn(Reg, VirtualRegister);
2740   } else {
2741     VirtualRegister = MRI.getLiveInVirtReg(Reg);
2742   }
2743   return DAG.getRegister(VirtualRegister, VT);
2744 }
2745 
2746 uint32_t AMDGPUTargetLowering::getImplicitParameterOffset(
2747     const AMDGPUMachineFunction *MFI, const ImplicitParameter Param) const {
2748   uint64_t ArgOffset = MFI->ABIArgOffset;
2749   switch (Param) {
2750   case GRID_DIM:
2751     return ArgOffset;
2752   case GRID_OFFSET:
2753     return ArgOffset + 4;
2754   }
2755   llvm_unreachable("unexpected implicit parameter type");
2756 }
2757 
2758 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
2759 
2760 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
2761   switch ((AMDGPUISD::NodeType)Opcode) {
2762   case AMDGPUISD::FIRST_NUMBER: break;
2763   // AMDIL DAG nodes
2764   NODE_NAME_CASE(CALL);
2765   NODE_NAME_CASE(UMUL);
2766   NODE_NAME_CASE(RET_FLAG);
2767   NODE_NAME_CASE(BRANCH_COND);
2768 
2769   // AMDGPU DAG nodes
2770   NODE_NAME_CASE(DWORDADDR)
2771   NODE_NAME_CASE(FRACT)
2772   NODE_NAME_CASE(CLAMP)
2773   NODE_NAME_CASE(COS_HW)
2774   NODE_NAME_CASE(SIN_HW)
2775   NODE_NAME_CASE(FMAX_LEGACY)
2776   NODE_NAME_CASE(FMIN_LEGACY)
2777   NODE_NAME_CASE(FMAX3)
2778   NODE_NAME_CASE(SMAX3)
2779   NODE_NAME_CASE(UMAX3)
2780   NODE_NAME_CASE(FMIN3)
2781   NODE_NAME_CASE(SMIN3)
2782   NODE_NAME_CASE(UMIN3)
2783   NODE_NAME_CASE(FMED3)
2784   NODE_NAME_CASE(SMED3)
2785   NODE_NAME_CASE(UMED3)
2786   NODE_NAME_CASE(URECIP)
2787   NODE_NAME_CASE(DIV_SCALE)
2788   NODE_NAME_CASE(DIV_FMAS)
2789   NODE_NAME_CASE(DIV_FIXUP)
2790   NODE_NAME_CASE(TRIG_PREOP)
2791   NODE_NAME_CASE(RCP)
2792   NODE_NAME_CASE(RSQ)
2793   NODE_NAME_CASE(RSQ_LEGACY)
2794   NODE_NAME_CASE(RSQ_CLAMP)
2795   NODE_NAME_CASE(LDEXP)
2796   NODE_NAME_CASE(FP_CLASS)
2797   NODE_NAME_CASE(DOT4)
2798   NODE_NAME_CASE(CARRY)
2799   NODE_NAME_CASE(BORROW)
2800   NODE_NAME_CASE(BFE_U32)
2801   NODE_NAME_CASE(BFE_I32)
2802   NODE_NAME_CASE(BFI)
2803   NODE_NAME_CASE(BFM)
2804   NODE_NAME_CASE(FFBH_U32)
2805   NODE_NAME_CASE(MUL_U24)
2806   NODE_NAME_CASE(MUL_I24)
2807   NODE_NAME_CASE(MAD_U24)
2808   NODE_NAME_CASE(MAD_I24)
2809   NODE_NAME_CASE(TEXTURE_FETCH)
2810   NODE_NAME_CASE(EXPORT)
2811   NODE_NAME_CASE(CONST_ADDRESS)
2812   NODE_NAME_CASE(REGISTER_LOAD)
2813   NODE_NAME_CASE(REGISTER_STORE)
2814   NODE_NAME_CASE(LOAD_CONSTANT)
2815   NODE_NAME_CASE(LOAD_INPUT)
2816   NODE_NAME_CASE(SAMPLE)
2817   NODE_NAME_CASE(SAMPLEB)
2818   NODE_NAME_CASE(SAMPLED)
2819   NODE_NAME_CASE(SAMPLEL)
2820   NODE_NAME_CASE(CVT_F32_UBYTE0)
2821   NODE_NAME_CASE(CVT_F32_UBYTE1)
2822   NODE_NAME_CASE(CVT_F32_UBYTE2)
2823   NODE_NAME_CASE(CVT_F32_UBYTE3)
2824   NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
2825   NODE_NAME_CASE(CONST_DATA_PTR)
2826   case AMDGPUISD::FIRST_MEM_OPCODE_NUMBER: break;
2827   NODE_NAME_CASE(SENDMSG)
2828   NODE_NAME_CASE(INTERP_MOV)
2829   NODE_NAME_CASE(INTERP_P1)
2830   NODE_NAME_CASE(INTERP_P2)
2831   NODE_NAME_CASE(STORE_MSKOR)
2832   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
2833   case AMDGPUISD::LAST_AMDGPU_ISD_NUMBER: break;
2834   }
2835   return nullptr;
2836 }
2837 
2838 SDValue AMDGPUTargetLowering::getRsqrtEstimate(SDValue Operand,
2839                                                DAGCombinerInfo &DCI,
2840                                                unsigned &RefinementSteps,
2841                                                bool &UseOneConstNR) const {
2842   SelectionDAG &DAG = DCI.DAG;
2843   EVT VT = Operand.getValueType();
2844 
2845   if (VT == MVT::f32) {
2846     RefinementSteps = 0;
2847     return DAG.getNode(AMDGPUISD::RSQ, SDLoc(Operand), VT, Operand);
2848   }
2849 
2850   // TODO: There is also f64 rsq instruction, but the documentation is less
2851   // clear on its precision.
2852 
2853   return SDValue();
2854 }
2855 
2856 SDValue AMDGPUTargetLowering::getRecipEstimate(SDValue Operand,
2857                                                DAGCombinerInfo &DCI,
2858                                                unsigned &RefinementSteps) const {
2859   SelectionDAG &DAG = DCI.DAG;
2860   EVT VT = Operand.getValueType();
2861 
2862   if (VT == MVT::f32) {
2863     // Reciprocal, < 1 ulp error.
2864     //
2865     // This reciprocal approximation converges to < 0.5 ulp error with one
2866     // newton rhapson performed with two fused multiple adds (FMAs).
2867 
2868     RefinementSteps = 0;
2869     return DAG.getNode(AMDGPUISD::RCP, SDLoc(Operand), VT, Operand);
2870   }
2871 
2872   // TODO: There is also f64 rcp instruction, but the documentation is less
2873   // clear on its precision.
2874 
2875   return SDValue();
2876 }
2877 
2878 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
2879   const SDValue Op,
2880   APInt &KnownZero,
2881   APInt &KnownOne,
2882   const SelectionDAG &DAG,
2883   unsigned Depth) const {
2884 
2885   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); // Don't know anything.
2886 
2887   APInt KnownZero2;
2888   APInt KnownOne2;
2889   unsigned Opc = Op.getOpcode();
2890 
2891   switch (Opc) {
2892   default:
2893     break;
2894   case AMDGPUISD::CARRY:
2895   case AMDGPUISD::BORROW: {
2896     KnownZero = APInt::getHighBitsSet(32, 31);
2897     break;
2898   }
2899 
2900   case AMDGPUISD::BFE_I32:
2901   case AMDGPUISD::BFE_U32: {
2902     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2903     if (!CWidth)
2904       return;
2905 
2906     unsigned BitWidth = 32;
2907     uint32_t Width = CWidth->getZExtValue() & 0x1f;
2908 
2909     if (Opc == AMDGPUISD::BFE_U32)
2910       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - Width);
2911 
2912     break;
2913   }
2914   }
2915 }
2916 
2917 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
2918   SDValue Op,
2919   const SelectionDAG &DAG,
2920   unsigned Depth) const {
2921   switch (Op.getOpcode()) {
2922   case AMDGPUISD::BFE_I32: {
2923     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2924     if (!Width)
2925       return 1;
2926 
2927     unsigned SignBits = 32 - Width->getZExtValue() + 1;
2928     if (!isNullConstant(Op.getOperand(1)))
2929       return SignBits;
2930 
2931     // TODO: Could probably figure something out with non-0 offsets.
2932     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
2933     return std::max(SignBits, Op0SignBits);
2934   }
2935 
2936   case AMDGPUISD::BFE_U32: {
2937     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2938     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
2939   }
2940 
2941   case AMDGPUISD::CARRY:
2942   case AMDGPUISD::BORROW:
2943     return 31;
2944 
2945   default:
2946     return 1;
2947   }
2948 }
2949