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