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