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