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