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