1 //===-- AMDGPUISelLowering.cpp - AMDGPU Common DAG lowering functions -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This is the parent TargetLowering class for hardware code gen
11 /// targets.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPUISelLowering.h"
16 #include "AMDGPU.h"
17 #include "AMDGPUCallLowering.h"
18 #include "AMDGPUFrameLowering.h"
19 #include "AMDGPURegisterInfo.h"
20 #include "AMDGPUSubtarget.h"
21 #include "AMDGPUTargetMachine.h"
22 #include "Utils/AMDGPUBaseInfo.h"
23 #include "R600MachineFunctionInfo.h"
24 #include "SIInstrInfo.h"
25 #include "SIMachineFunctionInfo.h"
26 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAG.h"
32 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/MathExtras.h"
37 using namespace llvm;
38 
39 #include "AMDGPUGenCallingConv.inc"
40 
41 // Find a larger type to do a load / store of a vector with.
42 EVT AMDGPUTargetLowering::getEquivalentMemType(LLVMContext &Ctx, EVT VT) {
43   unsigned StoreSize = VT.getStoreSizeInBits();
44   if (StoreSize <= 32)
45     return EVT::getIntegerVT(Ctx, StoreSize);
46 
47   assert(StoreSize % 32 == 0 && "Store size not a multiple of 32");
48   return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
49 }
50 
51 unsigned AMDGPUTargetLowering::numBitsUnsigned(SDValue Op, SelectionDAG &DAG) {
52   EVT VT = Op.getValueType();
53   KnownBits Known = DAG.computeKnownBits(Op);
54   return VT.getSizeInBits() - Known.countMinLeadingZeros();
55 }
56 
57 unsigned AMDGPUTargetLowering::numBitsSigned(SDValue Op, SelectionDAG &DAG) {
58   EVT VT = Op.getValueType();
59 
60   // In order for this to be a signed 24-bit value, bit 23, must
61   // be a sign bit.
62   return VT.getSizeInBits() - DAG.ComputeNumSignBits(Op);
63 }
64 
65 AMDGPUTargetLowering::AMDGPUTargetLowering(const TargetMachine &TM,
66                                            const AMDGPUSubtarget &STI)
67     : TargetLowering(TM), Subtarget(&STI) {
68   // Lower floating point store/load to integer store/load to reduce the number
69   // of patterns in tablegen.
70   setOperationAction(ISD::LOAD, MVT::f32, Promote);
71   AddPromotedToType(ISD::LOAD, MVT::f32, MVT::i32);
72 
73   setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
74   AddPromotedToType(ISD::LOAD, MVT::v2f32, MVT::v2i32);
75 
76   setOperationAction(ISD::LOAD, MVT::v3f32, Promote);
77   AddPromotedToType(ISD::LOAD, MVT::v3f32, MVT::v3i32);
78 
79   setOperationAction(ISD::LOAD, MVT::v4f32, Promote);
80   AddPromotedToType(ISD::LOAD, MVT::v4f32, MVT::v4i32);
81 
82   setOperationAction(ISD::LOAD, MVT::v5f32, Promote);
83   AddPromotedToType(ISD::LOAD, MVT::v5f32, MVT::v5i32);
84 
85   setOperationAction(ISD::LOAD, MVT::v8f32, Promote);
86   AddPromotedToType(ISD::LOAD, MVT::v8f32, MVT::v8i32);
87 
88   setOperationAction(ISD::LOAD, MVT::v16f32, Promote);
89   AddPromotedToType(ISD::LOAD, MVT::v16f32, MVT::v16i32);
90 
91   setOperationAction(ISD::LOAD, MVT::v32f32, Promote);
92   AddPromotedToType(ISD::LOAD, MVT::v32f32, MVT::v32i32);
93 
94   setOperationAction(ISD::LOAD, MVT::i64, Promote);
95   AddPromotedToType(ISD::LOAD, MVT::i64, MVT::v2i32);
96 
97   setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
98   AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32);
99 
100   setOperationAction(ISD::LOAD, MVT::f64, Promote);
101   AddPromotedToType(ISD::LOAD, MVT::f64, MVT::v2i32);
102 
103   setOperationAction(ISD::LOAD, MVT::v2f64, Promote);
104   AddPromotedToType(ISD::LOAD, MVT::v2f64, MVT::v4i32);
105 
106   // There are no 64-bit extloads. These should be done as a 32-bit extload and
107   // an extension to 64-bit.
108   for (MVT VT : MVT::integer_valuetypes()) {
109     setLoadExtAction(ISD::EXTLOAD, MVT::i64, VT, Expand);
110     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, VT, Expand);
111     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, VT, Expand);
112   }
113 
114   for (MVT VT : MVT::integer_valuetypes()) {
115     if (VT == MVT::i64)
116       continue;
117 
118     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
119     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
120     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
121     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
122 
123     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
124     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
125     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
126     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
127 
128     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
129     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
130     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
131     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
132   }
133 
134   for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
135     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Expand);
136     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Expand);
137     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i8, Expand);
138     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Expand);
139     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Expand);
140     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i8, Expand);
141     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Expand);
142     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Expand);
143     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i16, Expand);
144     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v3i16, Expand);
145     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v3i16, Expand);
146     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v3i16, Expand);
147     setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Expand);
148     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Expand);
149     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v4i16, Expand);
150   }
151 
152   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
153   setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, MVT::v2f16, Expand);
154   setLoadExtAction(ISD::EXTLOAD, MVT::v3f32, MVT::v3f16, Expand);
155   setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Expand);
156   setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Expand);
157   setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Expand);
158   setLoadExtAction(ISD::EXTLOAD, MVT::v32f32, MVT::v32f16, Expand);
159 
160   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
161   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
162   setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Expand);
163   setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f32, Expand);
164 
165   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
166   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
167   setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Expand);
168   setLoadExtAction(ISD::EXTLOAD, MVT::v8f64, MVT::v8f16, Expand);
169 
170   setOperationAction(ISD::STORE, MVT::f32, Promote);
171   AddPromotedToType(ISD::STORE, MVT::f32, MVT::i32);
172 
173   setOperationAction(ISD::STORE, MVT::v2f32, Promote);
174   AddPromotedToType(ISD::STORE, MVT::v2f32, MVT::v2i32);
175 
176   setOperationAction(ISD::STORE, MVT::v3f32, Promote);
177   AddPromotedToType(ISD::STORE, MVT::v3f32, MVT::v3i32);
178 
179   setOperationAction(ISD::STORE, MVT::v4f32, Promote);
180   AddPromotedToType(ISD::STORE, MVT::v4f32, MVT::v4i32);
181 
182   setOperationAction(ISD::STORE, MVT::v5f32, Promote);
183   AddPromotedToType(ISD::STORE, MVT::v5f32, MVT::v5i32);
184 
185   setOperationAction(ISD::STORE, MVT::v8f32, Promote);
186   AddPromotedToType(ISD::STORE, MVT::v8f32, MVT::v8i32);
187 
188   setOperationAction(ISD::STORE, MVT::v16f32, Promote);
189   AddPromotedToType(ISD::STORE, MVT::v16f32, MVT::v16i32);
190 
191   setOperationAction(ISD::STORE, MVT::v32f32, Promote);
192   AddPromotedToType(ISD::STORE, MVT::v32f32, MVT::v32i32);
193 
194   setOperationAction(ISD::STORE, MVT::i64, Promote);
195   AddPromotedToType(ISD::STORE, MVT::i64, MVT::v2i32);
196 
197   setOperationAction(ISD::STORE, MVT::v2i64, Promote);
198   AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32);
199 
200   setOperationAction(ISD::STORE, MVT::f64, Promote);
201   AddPromotedToType(ISD::STORE, MVT::f64, MVT::v2i32);
202 
203   setOperationAction(ISD::STORE, MVT::v2f64, Promote);
204   AddPromotedToType(ISD::STORE, MVT::v2f64, MVT::v4i32);
205 
206   setTruncStoreAction(MVT::i64, MVT::i1, Expand);
207   setTruncStoreAction(MVT::i64, MVT::i8, Expand);
208   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
209   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
210 
211   setTruncStoreAction(MVT::v2i64, MVT::v2i1, Expand);
212   setTruncStoreAction(MVT::v2i64, MVT::v2i8, Expand);
213   setTruncStoreAction(MVT::v2i64, MVT::v2i16, Expand);
214   setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand);
215 
216   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
217   setTruncStoreAction(MVT::v2f32, MVT::v2f16, Expand);
218   setTruncStoreAction(MVT::v3f32, MVT::v3f16, Expand);
219   setTruncStoreAction(MVT::v4f32, MVT::v4f16, Expand);
220   setTruncStoreAction(MVT::v8f32, MVT::v8f16, Expand);
221   setTruncStoreAction(MVT::v16f32, MVT::v16f16, Expand);
222   setTruncStoreAction(MVT::v32f32, MVT::v32f16, Expand);
223 
224   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
225   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
226 
227   setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
228   setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand);
229 
230   setTruncStoreAction(MVT::v4f64, MVT::v4f32, Expand);
231   setTruncStoreAction(MVT::v4f64, MVT::v4f16, Expand);
232 
233   setTruncStoreAction(MVT::v8f64, MVT::v8f32, Expand);
234   setTruncStoreAction(MVT::v8f64, MVT::v8f16, Expand);
235 
236 
237   setOperationAction(ISD::Constant, MVT::i32, Legal);
238   setOperationAction(ISD::Constant, MVT::i64, Legal);
239   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
240   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
241 
242   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
243   setOperationAction(ISD::BRIND, MVT::Other, Expand);
244 
245   // This is totally unsupported, just custom lower to produce an error.
246   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
247 
248   // Library functions.  These default to Expand, but we have instructions
249   // for them.
250   setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
251   setOperationAction(ISD::FEXP2,  MVT::f32, Legal);
252   setOperationAction(ISD::FPOW,   MVT::f32, Legal);
253   setOperationAction(ISD::FLOG2,  MVT::f32, Legal);
254   setOperationAction(ISD::FABS,   MVT::f32, Legal);
255   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
256   setOperationAction(ISD::FRINT,  MVT::f32, Legal);
257   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
258   setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
259   setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
260 
261   setOperationAction(ISD::FROUND, MVT::f32, Custom);
262   setOperationAction(ISD::FROUND, MVT::f64, Custom);
263 
264   setOperationAction(ISD::FLOG, MVT::f32, Custom);
265   setOperationAction(ISD::FLOG10, MVT::f32, Custom);
266   setOperationAction(ISD::FEXP, MVT::f32, Custom);
267 
268 
269   setOperationAction(ISD::FNEARBYINT, MVT::f32, Custom);
270   setOperationAction(ISD::FNEARBYINT, MVT::f64, Custom);
271 
272   setOperationAction(ISD::FREM, MVT::f32, Custom);
273   setOperationAction(ISD::FREM, MVT::f64, Custom);
274 
275   // Expand to fneg + fadd.
276   setOperationAction(ISD::FSUB, MVT::f64, Expand);
277 
278   setOperationAction(ISD::CONCAT_VECTORS, MVT::v3i32, Custom);
279   setOperationAction(ISD::CONCAT_VECTORS, MVT::v3f32, Custom);
280   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
281   setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Custom);
282   setOperationAction(ISD::CONCAT_VECTORS, MVT::v5i32, Custom);
283   setOperationAction(ISD::CONCAT_VECTORS, MVT::v5f32, Custom);
284   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
285   setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
286   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2f32, Custom);
287   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v2i32, Custom);
288   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v3f32, Custom);
289   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v3i32, Custom);
290   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4f32, Custom);
291   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
292   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v5f32, Custom);
293   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v5i32, Custom);
294   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8f32, Custom);
295   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v8i32, Custom);
296   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16f32, Custom);
297   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16i32, Custom);
298   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v32f32, Custom);
299   setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v32i32, Custom);
300 
301   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
302   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Custom);
303   setOperationAction(ISD::FP_TO_FP16, MVT::f32, Custom);
304 
305   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
306   for (MVT VT : ScalarIntVTs) {
307     // These should use [SU]DIVREM, so set them to expand
308     setOperationAction(ISD::SDIV, VT, Expand);
309     setOperationAction(ISD::UDIV, VT, Expand);
310     setOperationAction(ISD::SREM, VT, Expand);
311     setOperationAction(ISD::UREM, VT, Expand);
312 
313     // GPU does not have divrem function for signed or unsigned.
314     setOperationAction(ISD::SDIVREM, VT, Custom);
315     setOperationAction(ISD::UDIVREM, VT, Custom);
316 
317     // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
318     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
319     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
320 
321     setOperationAction(ISD::BSWAP, VT, Expand);
322     setOperationAction(ISD::CTTZ, VT, Expand);
323     setOperationAction(ISD::CTLZ, VT, Expand);
324 
325     // AMDGPU uses ADDC/SUBC/ADDE/SUBE
326     setOperationAction(ISD::ADDC, VT, Legal);
327     setOperationAction(ISD::SUBC, VT, Legal);
328     setOperationAction(ISD::ADDE, VT, Legal);
329     setOperationAction(ISD::SUBE, VT, Legal);
330   }
331 
332   // The hardware supports 32-bit ROTR, but not ROTL.
333   setOperationAction(ISD::ROTL, MVT::i32, Expand);
334   setOperationAction(ISD::ROTL, MVT::i64, Expand);
335   setOperationAction(ISD::ROTR, MVT::i64, Expand);
336 
337   setOperationAction(ISD::MUL, MVT::i64, Expand);
338   setOperationAction(ISD::MULHU, MVT::i64, Expand);
339   setOperationAction(ISD::MULHS, MVT::i64, Expand);
340   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
341   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
342   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
343   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
344   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
345 
346   setOperationAction(ISD::SMIN, MVT::i32, Legal);
347   setOperationAction(ISD::UMIN, MVT::i32, Legal);
348   setOperationAction(ISD::SMAX, MVT::i32, Legal);
349   setOperationAction(ISD::UMAX, MVT::i32, Legal);
350 
351   setOperationAction(ISD::CTTZ, MVT::i64, Custom);
352   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Custom);
353   setOperationAction(ISD::CTLZ, MVT::i64, Custom);
354   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
355 
356   static const MVT::SimpleValueType VectorIntTypes[] = {
357     MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32
358   };
359 
360   for (MVT VT : VectorIntTypes) {
361     // Expand the following operations for the current type by default.
362     setOperationAction(ISD::ADD,  VT, Expand);
363     setOperationAction(ISD::AND,  VT, Expand);
364     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
365     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
366     setOperationAction(ISD::MUL,  VT, Expand);
367     setOperationAction(ISD::MULHU, VT, Expand);
368     setOperationAction(ISD::MULHS, VT, Expand);
369     setOperationAction(ISD::OR,   VT, Expand);
370     setOperationAction(ISD::SHL,  VT, Expand);
371     setOperationAction(ISD::SRA,  VT, Expand);
372     setOperationAction(ISD::SRL,  VT, Expand);
373     setOperationAction(ISD::ROTL, VT, Expand);
374     setOperationAction(ISD::ROTR, VT, Expand);
375     setOperationAction(ISD::SUB,  VT, Expand);
376     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
377     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
378     setOperationAction(ISD::SDIV, VT, Expand);
379     setOperationAction(ISD::UDIV, VT, Expand);
380     setOperationAction(ISD::SREM, VT, Expand);
381     setOperationAction(ISD::UREM, VT, Expand);
382     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
383     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
384     setOperationAction(ISD::SDIVREM, VT, Custom);
385     setOperationAction(ISD::UDIVREM, VT, Expand);
386     setOperationAction(ISD::SELECT, VT, Expand);
387     setOperationAction(ISD::VSELECT, VT, Expand);
388     setOperationAction(ISD::SELECT_CC, VT, Expand);
389     setOperationAction(ISD::XOR,  VT, Expand);
390     setOperationAction(ISD::BSWAP, VT, Expand);
391     setOperationAction(ISD::CTPOP, VT, Expand);
392     setOperationAction(ISD::CTTZ, VT, Expand);
393     setOperationAction(ISD::CTLZ, VT, Expand);
394     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
395     setOperationAction(ISD::SETCC, VT, Expand);
396   }
397 
398   static const MVT::SimpleValueType FloatVectorTypes[] = {
399      MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32
400   };
401 
402   for (MVT VT : FloatVectorTypes) {
403     setOperationAction(ISD::FABS, VT, Expand);
404     setOperationAction(ISD::FMINNUM, VT, Expand);
405     setOperationAction(ISD::FMAXNUM, VT, Expand);
406     setOperationAction(ISD::FADD, VT, Expand);
407     setOperationAction(ISD::FCEIL, VT, Expand);
408     setOperationAction(ISD::FCOS, VT, Expand);
409     setOperationAction(ISD::FDIV, VT, Expand);
410     setOperationAction(ISD::FEXP2, VT, Expand);
411     setOperationAction(ISD::FEXP, VT, Expand);
412     setOperationAction(ISD::FLOG2, VT, Expand);
413     setOperationAction(ISD::FREM, VT, Expand);
414     setOperationAction(ISD::FLOG, VT, Expand);
415     setOperationAction(ISD::FLOG10, VT, Expand);
416     setOperationAction(ISD::FPOW, VT, Expand);
417     setOperationAction(ISD::FFLOOR, VT, Expand);
418     setOperationAction(ISD::FTRUNC, VT, Expand);
419     setOperationAction(ISD::FMUL, VT, Expand);
420     setOperationAction(ISD::FMA, VT, Expand);
421     setOperationAction(ISD::FRINT, VT, Expand);
422     setOperationAction(ISD::FNEARBYINT, VT, Expand);
423     setOperationAction(ISD::FSQRT, VT, Expand);
424     setOperationAction(ISD::FSIN, VT, Expand);
425     setOperationAction(ISD::FSUB, VT, Expand);
426     setOperationAction(ISD::FNEG, VT, Expand);
427     setOperationAction(ISD::VSELECT, VT, Expand);
428     setOperationAction(ISD::SELECT_CC, VT, Expand);
429     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
430     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
431     setOperationAction(ISD::SETCC, VT, Expand);
432     setOperationAction(ISD::FCANONICALIZE, VT, Expand);
433   }
434 
435   // This causes using an unrolled select operation rather than expansion with
436   // bit operations. This is in general better, but the alternative using BFI
437   // instructions may be better if the select sources are SGPRs.
438   setOperationAction(ISD::SELECT, MVT::v2f32, Promote);
439   AddPromotedToType(ISD::SELECT, MVT::v2f32, MVT::v2i32);
440 
441   setOperationAction(ISD::SELECT, MVT::v3f32, Promote);
442   AddPromotedToType(ISD::SELECT, MVT::v3f32, MVT::v3i32);
443 
444   setOperationAction(ISD::SELECT, MVT::v4f32, Promote);
445   AddPromotedToType(ISD::SELECT, MVT::v4f32, MVT::v4i32);
446 
447   setOperationAction(ISD::SELECT, MVT::v5f32, Promote);
448   AddPromotedToType(ISD::SELECT, MVT::v5f32, MVT::v5i32);
449 
450   // There are no libcalls of any kind.
451   for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I)
452     setLibcallName(static_cast<RTLIB::Libcall>(I), nullptr);
453 
454   setSchedulingPreference(Sched::RegPressure);
455   setJumpIsExpensive(true);
456 
457   // FIXME: This is only partially true. If we have to do vector compares, any
458   // SGPR pair can be a condition register. If we have a uniform condition, we
459   // are better off doing SALU operations, where there is only one SCC. For now,
460   // we don't have a way of knowing during instruction selection if a condition
461   // will be uniform and we always use vector compares. Assume we are using
462   // vector compares until that is fixed.
463   setHasMultipleConditionRegisters(true);
464 
465   setMinCmpXchgSizeInBits(32);
466   setSupportsUnalignedAtomics(false);
467 
468   PredictableSelectIsExpensive = false;
469 
470   // We want to find all load dependencies for long chains of stores to enable
471   // merging into very wide vectors. The problem is with vectors with > 4
472   // elements. MergeConsecutiveStores will attempt to merge these because x8/x16
473   // vectors are a legal type, even though we have to split the loads
474   // usually. When we can more precisely specify load legality per address
475   // space, we should be able to make FindBetterChain/MergeConsecutiveStores
476   // smarter so that they can figure out what to do in 2 iterations without all
477   // N > 4 stores on the same chain.
478   GatherAllAliasesMaxDepth = 16;
479 
480   // memcpy/memmove/memset are expanded in the IR, so we shouldn't need to worry
481   // about these during lowering.
482   MaxStoresPerMemcpy  = 0xffffffff;
483   MaxStoresPerMemmove = 0xffffffff;
484   MaxStoresPerMemset  = 0xffffffff;
485 
486   setTargetDAGCombine(ISD::BITCAST);
487   setTargetDAGCombine(ISD::SHL);
488   setTargetDAGCombine(ISD::SRA);
489   setTargetDAGCombine(ISD::SRL);
490   setTargetDAGCombine(ISD::TRUNCATE);
491   setTargetDAGCombine(ISD::MUL);
492   setTargetDAGCombine(ISD::MULHU);
493   setTargetDAGCombine(ISD::MULHS);
494   setTargetDAGCombine(ISD::SELECT);
495   setTargetDAGCombine(ISD::SELECT_CC);
496   setTargetDAGCombine(ISD::STORE);
497   setTargetDAGCombine(ISD::FADD);
498   setTargetDAGCombine(ISD::FSUB);
499   setTargetDAGCombine(ISD::FNEG);
500   setTargetDAGCombine(ISD::FABS);
501   setTargetDAGCombine(ISD::AssertZext);
502   setTargetDAGCombine(ISD::AssertSext);
503   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
504 }
505 
506 //===----------------------------------------------------------------------===//
507 // Target Information
508 //===----------------------------------------------------------------------===//
509 
510 LLVM_READNONE
511 static bool fnegFoldsIntoOp(unsigned Opc) {
512   switch (Opc) {
513   case ISD::FADD:
514   case ISD::FSUB:
515   case ISD::FMUL:
516   case ISD::FMA:
517   case ISD::FMAD:
518   case ISD::FMINNUM:
519   case ISD::FMAXNUM:
520   case ISD::FMINNUM_IEEE:
521   case ISD::FMAXNUM_IEEE:
522   case ISD::FSIN:
523   case ISD::FTRUNC:
524   case ISD::FRINT:
525   case ISD::FNEARBYINT:
526   case ISD::FCANONICALIZE:
527   case AMDGPUISD::RCP:
528   case AMDGPUISD::RCP_LEGACY:
529   case AMDGPUISD::RCP_IFLAG:
530   case AMDGPUISD::SIN_HW:
531   case AMDGPUISD::FMUL_LEGACY:
532   case AMDGPUISD::FMIN_LEGACY:
533   case AMDGPUISD::FMAX_LEGACY:
534   case AMDGPUISD::FMED3:
535     return true;
536   default:
537     return false;
538   }
539 }
540 
541 /// \p returns true if the operation will definitely need to use a 64-bit
542 /// encoding, and thus will use a VOP3 encoding regardless of the source
543 /// modifiers.
544 LLVM_READONLY
545 static bool opMustUseVOP3Encoding(const SDNode *N, MVT VT) {
546   return N->getNumOperands() > 2 || VT == MVT::f64;
547 }
548 
549 // Most FP instructions support source modifiers, but this could be refined
550 // slightly.
551 LLVM_READONLY
552 static bool hasSourceMods(const SDNode *N) {
553   if (isa<MemSDNode>(N))
554     return false;
555 
556   switch (N->getOpcode()) {
557   case ISD::CopyToReg:
558   case ISD::SELECT:
559   case ISD::FDIV:
560   case ISD::FREM:
561   case ISD::INLINEASM:
562   case ISD::INLINEASM_BR:
563   case AMDGPUISD::DIV_SCALE:
564   case ISD::INTRINSIC_W_CHAIN:
565 
566   // TODO: Should really be looking at the users of the bitcast. These are
567   // problematic because bitcasts are used to legalize all stores to integer
568   // types.
569   case ISD::BITCAST:
570     return false;
571   case ISD::INTRINSIC_WO_CHAIN: {
572     switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
573     case Intrinsic::amdgcn_interp_p1:
574     case Intrinsic::amdgcn_interp_p2:
575     case Intrinsic::amdgcn_interp_mov:
576     case Intrinsic::amdgcn_interp_p1_f16:
577     case Intrinsic::amdgcn_interp_p2_f16:
578       return false;
579     default:
580       return true;
581     }
582   }
583   default:
584     return true;
585   }
586 }
587 
588 bool AMDGPUTargetLowering::allUsesHaveSourceMods(const SDNode *N,
589                                                  unsigned CostThreshold) {
590   // Some users (such as 3-operand FMA/MAD) must use a VOP3 encoding, and thus
591   // it is truly free to use a source modifier in all cases. If there are
592   // multiple users but for each one will necessitate using VOP3, there will be
593   // a code size increase. Try to avoid increasing code size unless we know it
594   // will save on the instruction count.
595   unsigned NumMayIncreaseSize = 0;
596   MVT VT = N->getValueType(0).getScalarType().getSimpleVT();
597 
598   // XXX - Should this limit number of uses to check?
599   for (const SDNode *U : N->uses()) {
600     if (!hasSourceMods(U))
601       return false;
602 
603     if (!opMustUseVOP3Encoding(U, VT)) {
604       if (++NumMayIncreaseSize > CostThreshold)
605         return false;
606     }
607   }
608 
609   return true;
610 }
611 
612 MVT AMDGPUTargetLowering::getVectorIdxTy(const DataLayout &) const {
613   return MVT::i32;
614 }
615 
616 bool AMDGPUTargetLowering::isSelectSupported(SelectSupportKind SelType) const {
617   return true;
618 }
619 
620 // The backend supports 32 and 64 bit floating point immediates.
621 // FIXME: Why are we reporting vectors of FP immediates as legal?
622 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
623                                         bool ForCodeSize) const {
624   EVT ScalarVT = VT.getScalarType();
625   return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64 ||
626          (ScalarVT == MVT::f16 && Subtarget->has16BitInsts()));
627 }
628 
629 // We don't want to shrink f64 / f32 constants.
630 bool AMDGPUTargetLowering::ShouldShrinkFPConstant(EVT VT) const {
631   EVT ScalarVT = VT.getScalarType();
632   return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
633 }
634 
635 bool AMDGPUTargetLowering::shouldReduceLoadWidth(SDNode *N,
636                                                  ISD::LoadExtType ExtTy,
637                                                  EVT NewVT) const {
638   // TODO: This may be worth removing. Check regression tests for diffs.
639   if (!TargetLoweringBase::shouldReduceLoadWidth(N, ExtTy, NewVT))
640     return false;
641 
642   unsigned NewSize = NewVT.getStoreSizeInBits();
643 
644   // If we are reducing to a 32-bit load or a smaller multi-dword load,
645   // this is always better.
646   if (NewSize >= 32)
647     return true;
648 
649   EVT OldVT = N->getValueType(0);
650   unsigned OldSize = OldVT.getStoreSizeInBits();
651 
652   MemSDNode *MN = cast<MemSDNode>(N);
653   unsigned AS = MN->getAddressSpace();
654   // Do not shrink an aligned scalar load to sub-dword.
655   // Scalar engine cannot do sub-dword loads.
656   if (OldSize >= 32 && NewSize < 32 && MN->getAlignment() >= 4 &&
657       (AS == AMDGPUAS::CONSTANT_ADDRESS ||
658        AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
659        (isa<LoadSDNode>(N) &&
660         AS == AMDGPUAS::GLOBAL_ADDRESS && MN->isInvariant())) &&
661       AMDGPUInstrInfo::isUniformMMO(MN->getMemOperand()))
662     return false;
663 
664   // Don't produce extloads from sub 32-bit types. SI doesn't have scalar
665   // extloads, so doing one requires using a buffer_load. In cases where we
666   // still couldn't use a scalar load, using the wider load shouldn't really
667   // hurt anything.
668 
669   // If the old size already had to be an extload, there's no harm in continuing
670   // to reduce the width.
671   return (OldSize < 32);
672 }
673 
674 bool AMDGPUTargetLowering::isLoadBitCastBeneficial(EVT LoadTy, EVT CastTy,
675                                                    const SelectionDAG &DAG,
676                                                    const MachineMemOperand &MMO) const {
677 
678   assert(LoadTy.getSizeInBits() == CastTy.getSizeInBits());
679 
680   if (LoadTy.getScalarType() == MVT::i32)
681     return false;
682 
683   unsigned LScalarSize = LoadTy.getScalarSizeInBits();
684   unsigned CastScalarSize = CastTy.getScalarSizeInBits();
685 
686   if ((LScalarSize >= CastScalarSize) && (CastScalarSize < 32))
687     return false;
688 
689   bool Fast = false;
690   return allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
691                                         CastTy, MMO, &Fast) &&
692          Fast;
693 }
694 
695 // SI+ has instructions for cttz / ctlz for 32-bit values. This is probably also
696 // profitable with the expansion for 64-bit since it's generally good to
697 // speculate things.
698 // FIXME: These should really have the size as a parameter.
699 bool AMDGPUTargetLowering::isCheapToSpeculateCttz() const {
700   return true;
701 }
702 
703 bool AMDGPUTargetLowering::isCheapToSpeculateCtlz() const {
704   return true;
705 }
706 
707 bool AMDGPUTargetLowering::isSDNodeAlwaysUniform(const SDNode * N) const {
708   switch (N->getOpcode()) {
709     default:
710     return false;
711     case ISD::EntryToken:
712     case ISD::TokenFactor:
713       return true;
714     case ISD::INTRINSIC_WO_CHAIN:
715     {
716       unsigned IntrID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
717       switch (IntrID) {
718         default:
719         return false;
720         case Intrinsic::amdgcn_readfirstlane:
721         case Intrinsic::amdgcn_readlane:
722           return true;
723       }
724     }
725     break;
726     case ISD::LOAD:
727     {
728       if (cast<LoadSDNode>(N)->getMemOperand()->getAddrSpace() ==
729           AMDGPUAS::CONSTANT_ADDRESS_32BIT)
730         return true;
731       return false;
732     }
733     break;
734   }
735 }
736 
737 //===---------------------------------------------------------------------===//
738 // Target Properties
739 //===---------------------------------------------------------------------===//
740 
741 bool AMDGPUTargetLowering::isFAbsFree(EVT VT) const {
742   assert(VT.isFloatingPoint());
743 
744   // Packed operations do not have a fabs modifier.
745   return VT == MVT::f32 || VT == MVT::f64 ||
746          (Subtarget->has16BitInsts() && VT == MVT::f16);
747 }
748 
749 bool AMDGPUTargetLowering::isFNegFree(EVT VT) const {
750   assert(VT.isFloatingPoint());
751   return VT == MVT::f32 || VT == MVT::f64 ||
752          (Subtarget->has16BitInsts() && VT == MVT::f16) ||
753          (Subtarget->hasVOP3PInsts() && VT == MVT::v2f16);
754 }
755 
756 bool AMDGPUTargetLowering:: storeOfVectorConstantIsCheap(EVT MemVT,
757                                                          unsigned NumElem,
758                                                          unsigned AS) const {
759   return true;
760 }
761 
762 bool AMDGPUTargetLowering::aggressivelyPreferBuildVectorSources(EVT VecVT) const {
763   // There are few operations which truly have vector input operands. Any vector
764   // operation is going to involve operations on each component, and a
765   // build_vector will be a copy per element, so it always makes sense to use a
766   // build_vector input in place of the extracted element to avoid a copy into a
767   // super register.
768   //
769   // We should probably only do this if all users are extracts only, but this
770   // should be the common case.
771   return true;
772 }
773 
774 bool AMDGPUTargetLowering::isTruncateFree(EVT Source, EVT Dest) const {
775   // Truncate is just accessing a subregister.
776 
777   unsigned SrcSize = Source.getSizeInBits();
778   unsigned DestSize = Dest.getSizeInBits();
779 
780   return DestSize < SrcSize && DestSize % 32 == 0 ;
781 }
782 
783 bool AMDGPUTargetLowering::isTruncateFree(Type *Source, Type *Dest) const {
784   // Truncate is just accessing a subregister.
785 
786   unsigned SrcSize = Source->getScalarSizeInBits();
787   unsigned DestSize = Dest->getScalarSizeInBits();
788 
789   if (DestSize== 16 && Subtarget->has16BitInsts())
790     return SrcSize >= 32;
791 
792   return DestSize < SrcSize && DestSize % 32 == 0;
793 }
794 
795 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
796   unsigned SrcSize = Src->getScalarSizeInBits();
797   unsigned DestSize = Dest->getScalarSizeInBits();
798 
799   if (SrcSize == 16 && Subtarget->has16BitInsts())
800     return DestSize >= 32;
801 
802   return SrcSize == 32 && DestSize == 64;
803 }
804 
805 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
806   // Any register load of a 64-bit value really requires 2 32-bit moves. For all
807   // practical purposes, the extra mov 0 to load a 64-bit is free.  As used,
808   // this will enable reducing 64-bit operations the 32-bit, which is always
809   // good.
810 
811   if (Src == MVT::i16)
812     return Dest == MVT::i32 ||Dest == MVT::i64 ;
813 
814   return Src == MVT::i32 && Dest == MVT::i64;
815 }
816 
817 bool AMDGPUTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
818   return isZExtFree(Val.getValueType(), VT2);
819 }
820 
821 bool AMDGPUTargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
822   // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
823   // limited number of native 64-bit operations. Shrinking an operation to fit
824   // in a single 32-bit register should always be helpful. As currently used,
825   // this is much less general than the name suggests, and is only used in
826   // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
827   // not profitable, and may actually be harmful.
828   return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
829 }
830 
831 //===---------------------------------------------------------------------===//
832 // TargetLowering Callbacks
833 //===---------------------------------------------------------------------===//
834 
835 CCAssignFn *AMDGPUCallLowering::CCAssignFnForCall(CallingConv::ID CC,
836                                                   bool IsVarArg) {
837   switch (CC) {
838   case CallingConv::AMDGPU_VS:
839   case CallingConv::AMDGPU_GS:
840   case CallingConv::AMDGPU_PS:
841   case CallingConv::AMDGPU_CS:
842   case CallingConv::AMDGPU_HS:
843   case CallingConv::AMDGPU_ES:
844   case CallingConv::AMDGPU_LS:
845     return CC_AMDGPU;
846   case CallingConv::C:
847   case CallingConv::Fast:
848   case CallingConv::Cold:
849     return CC_AMDGPU_Func;
850   case CallingConv::AMDGPU_KERNEL:
851   case CallingConv::SPIR_KERNEL:
852   default:
853     report_fatal_error("Unsupported calling convention for call");
854   }
855 }
856 
857 CCAssignFn *AMDGPUCallLowering::CCAssignFnForReturn(CallingConv::ID CC,
858                                                     bool IsVarArg) {
859   switch (CC) {
860   case CallingConv::AMDGPU_KERNEL:
861   case CallingConv::SPIR_KERNEL:
862     llvm_unreachable("kernels should not be handled here");
863   case CallingConv::AMDGPU_VS:
864   case CallingConv::AMDGPU_GS:
865   case CallingConv::AMDGPU_PS:
866   case CallingConv::AMDGPU_CS:
867   case CallingConv::AMDGPU_HS:
868   case CallingConv::AMDGPU_ES:
869   case CallingConv::AMDGPU_LS:
870     return RetCC_SI_Shader;
871   case CallingConv::C:
872   case CallingConv::Fast:
873   case CallingConv::Cold:
874     return RetCC_AMDGPU_Func;
875   default:
876     report_fatal_error("Unsupported calling convention.");
877   }
878 }
879 
880 /// The SelectionDAGBuilder will automatically promote function arguments
881 /// with illegal types.  However, this does not work for the AMDGPU targets
882 /// since the function arguments are stored in memory as these illegal types.
883 /// In order to handle this properly we need to get the original types sizes
884 /// from the LLVM IR Function and fixup the ISD:InputArg values before
885 /// passing them to AnalyzeFormalArguments()
886 
887 /// When the SelectionDAGBuilder computes the Ins, it takes care of splitting
888 /// input values across multiple registers.  Each item in the Ins array
889 /// represents a single value that will be stored in registers.  Ins[x].VT is
890 /// the value type of the value that will be stored in the register, so
891 /// whatever SDNode we lower the argument to needs to be this type.
892 ///
893 /// In order to correctly lower the arguments we need to know the size of each
894 /// argument.  Since Ins[x].VT gives us the size of the register that will
895 /// hold the value, we need to look at Ins[x].ArgVT to see the 'real' type
896 /// for the orignal function argument so that we can deduce the correct memory
897 /// type to use for Ins[x].  In most cases the correct memory type will be
898 /// Ins[x].ArgVT.  However, this will not always be the case.  If, for example,
899 /// we have a kernel argument of type v8i8, this argument will be split into
900 /// 8 parts and each part will be represented by its own item in the Ins array.
901 /// For each part the Ins[x].ArgVT will be the v8i8, which is the full type of
902 /// the argument before it was split.  From this, we deduce that the memory type
903 /// for each individual part is i8.  We pass the memory type as LocVT to the
904 /// calling convention analysis function and the register type (Ins[x].VT) as
905 /// the ValVT.
906 void AMDGPUTargetLowering::analyzeFormalArgumentsCompute(
907   CCState &State,
908   const SmallVectorImpl<ISD::InputArg> &Ins) const {
909   const MachineFunction &MF = State.getMachineFunction();
910   const Function &Fn = MF.getFunction();
911   LLVMContext &Ctx = Fn.getParent()->getContext();
912   const AMDGPUSubtarget &ST = AMDGPUSubtarget::get(MF);
913   const unsigned ExplicitOffset = ST.getExplicitKernelArgOffset(Fn);
914   CallingConv::ID CC = Fn.getCallingConv();
915 
916   unsigned MaxAlign = 1;
917   uint64_t ExplicitArgOffset = 0;
918   const DataLayout &DL = Fn.getParent()->getDataLayout();
919 
920   unsigned InIndex = 0;
921 
922   for (const Argument &Arg : Fn.args()) {
923     Type *BaseArgTy = Arg.getType();
924     unsigned Align = DL.getABITypeAlignment(BaseArgTy);
925     MaxAlign = std::max(Align, MaxAlign);
926     unsigned AllocSize = DL.getTypeAllocSize(BaseArgTy);
927 
928     uint64_t ArgOffset = alignTo(ExplicitArgOffset, Align) + ExplicitOffset;
929     ExplicitArgOffset = alignTo(ExplicitArgOffset, Align) + AllocSize;
930 
931     // We're basically throwing away everything passed into us and starting over
932     // to get accurate in-memory offsets. The "PartOffset" is completely useless
933     // to us as computed in Ins.
934     //
935     // We also need to figure out what type legalization is trying to do to get
936     // the correct memory offsets.
937 
938     SmallVector<EVT, 16> ValueVTs;
939     SmallVector<uint64_t, 16> Offsets;
940     ComputeValueVTs(*this, DL, BaseArgTy, ValueVTs, &Offsets, ArgOffset);
941 
942     for (unsigned Value = 0, NumValues = ValueVTs.size();
943          Value != NumValues; ++Value) {
944       uint64_t BasePartOffset = Offsets[Value];
945 
946       EVT ArgVT = ValueVTs[Value];
947       EVT MemVT = ArgVT;
948       MVT RegisterVT = getRegisterTypeForCallingConv(Ctx, CC, ArgVT);
949       unsigned NumRegs = getNumRegistersForCallingConv(Ctx, CC, ArgVT);
950 
951       if (NumRegs == 1) {
952         // This argument is not split, so the IR type is the memory type.
953         if (ArgVT.isExtended()) {
954           // We have an extended type, like i24, so we should just use the
955           // register type.
956           MemVT = RegisterVT;
957         } else {
958           MemVT = ArgVT;
959         }
960       } else if (ArgVT.isVector() && RegisterVT.isVector() &&
961                  ArgVT.getScalarType() == RegisterVT.getScalarType()) {
962         assert(ArgVT.getVectorNumElements() > RegisterVT.getVectorNumElements());
963         // We have a vector value which has been split into a vector with
964         // the same scalar type, but fewer elements.  This should handle
965         // all the floating-point vector types.
966         MemVT = RegisterVT;
967       } else if (ArgVT.isVector() &&
968                  ArgVT.getVectorNumElements() == NumRegs) {
969         // This arg has been split so that each element is stored in a separate
970         // register.
971         MemVT = ArgVT.getScalarType();
972       } else if (ArgVT.isExtended()) {
973         // We have an extended type, like i65.
974         MemVT = RegisterVT;
975       } else {
976         unsigned MemoryBits = ArgVT.getStoreSizeInBits() / NumRegs;
977         assert(ArgVT.getStoreSizeInBits() % NumRegs == 0);
978         if (RegisterVT.isInteger()) {
979           MemVT = EVT::getIntegerVT(State.getContext(), MemoryBits);
980         } else if (RegisterVT.isVector()) {
981           assert(!RegisterVT.getScalarType().isFloatingPoint());
982           unsigned NumElements = RegisterVT.getVectorNumElements();
983           assert(MemoryBits % NumElements == 0);
984           // This vector type has been split into another vector type with
985           // a different elements size.
986           EVT ScalarVT = EVT::getIntegerVT(State.getContext(),
987                                            MemoryBits / NumElements);
988           MemVT = EVT::getVectorVT(State.getContext(), ScalarVT, NumElements);
989         } else {
990           llvm_unreachable("cannot deduce memory type.");
991         }
992       }
993 
994       // Convert one element vectors to scalar.
995       if (MemVT.isVector() && MemVT.getVectorNumElements() == 1)
996         MemVT = MemVT.getScalarType();
997 
998       // Round up vec3/vec5 argument.
999       if (MemVT.isVector() && !MemVT.isPow2VectorType()) {
1000         assert(MemVT.getVectorNumElements() == 3 ||
1001                MemVT.getVectorNumElements() == 5);
1002         MemVT = MemVT.getPow2VectorType(State.getContext());
1003       }
1004 
1005       unsigned PartOffset = 0;
1006       for (unsigned i = 0; i != NumRegs; ++i) {
1007         State.addLoc(CCValAssign::getCustomMem(InIndex++, RegisterVT,
1008                                                BasePartOffset + PartOffset,
1009                                                MemVT.getSimpleVT(),
1010                                                CCValAssign::Full));
1011         PartOffset += MemVT.getStoreSize();
1012       }
1013     }
1014   }
1015 }
1016 
1017 SDValue AMDGPUTargetLowering::LowerReturn(
1018   SDValue Chain, CallingConv::ID CallConv,
1019   bool isVarArg,
1020   const SmallVectorImpl<ISD::OutputArg> &Outs,
1021   const SmallVectorImpl<SDValue> &OutVals,
1022   const SDLoc &DL, SelectionDAG &DAG) const {
1023   // FIXME: Fails for r600 tests
1024   //assert(!isVarArg && Outs.empty() && OutVals.empty() &&
1025   // "wave terminate should not have return values");
1026   return DAG.getNode(AMDGPUISD::ENDPGM, DL, MVT::Other, Chain);
1027 }
1028 
1029 //===---------------------------------------------------------------------===//
1030 // Target specific lowering
1031 //===---------------------------------------------------------------------===//
1032 
1033 /// Selects the correct CCAssignFn for a given CallingConvention value.
1034 CCAssignFn *AMDGPUTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1035                                                     bool IsVarArg) {
1036   return AMDGPUCallLowering::CCAssignFnForCall(CC, IsVarArg);
1037 }
1038 
1039 CCAssignFn *AMDGPUTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1040                                                       bool IsVarArg) {
1041   return AMDGPUCallLowering::CCAssignFnForReturn(CC, IsVarArg);
1042 }
1043 
1044 SDValue AMDGPUTargetLowering::addTokenForArgument(SDValue Chain,
1045                                                   SelectionDAG &DAG,
1046                                                   MachineFrameInfo &MFI,
1047                                                   int ClobberedFI) const {
1048   SmallVector<SDValue, 8> ArgChains;
1049   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
1050   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
1051 
1052   // Include the original chain at the beginning of the list. When this is
1053   // used by target LowerCall hooks, this helps legalize find the
1054   // CALLSEQ_BEGIN node.
1055   ArgChains.push_back(Chain);
1056 
1057   // Add a chain value for each stack argument corresponding
1058   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1059                             UE = DAG.getEntryNode().getNode()->use_end();
1060        U != UE; ++U) {
1061     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) {
1062       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) {
1063         if (FI->getIndex() < 0) {
1064           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
1065           int64_t InLastByte = InFirstByte;
1066           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
1067 
1068           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1069               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1070             ArgChains.push_back(SDValue(L, 1));
1071         }
1072       }
1073     }
1074   }
1075 
1076   // Build a tokenfactor for all the chains.
1077   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
1078 }
1079 
1080 SDValue AMDGPUTargetLowering::lowerUnhandledCall(CallLoweringInfo &CLI,
1081                                                  SmallVectorImpl<SDValue> &InVals,
1082                                                  StringRef Reason) const {
1083   SDValue Callee = CLI.Callee;
1084   SelectionDAG &DAG = CLI.DAG;
1085 
1086   const Function &Fn = DAG.getMachineFunction().getFunction();
1087 
1088   StringRef FuncName("<unknown>");
1089 
1090   if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
1091     FuncName = G->getSymbol();
1092   else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1093     FuncName = G->getGlobal()->getName();
1094 
1095   DiagnosticInfoUnsupported NoCalls(
1096     Fn, Reason + FuncName, CLI.DL.getDebugLoc());
1097   DAG.getContext()->diagnose(NoCalls);
1098 
1099   if (!CLI.IsTailCall) {
1100     for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
1101       InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
1102   }
1103 
1104   return DAG.getEntryNode();
1105 }
1106 
1107 SDValue AMDGPUTargetLowering::LowerCall(CallLoweringInfo &CLI,
1108                                         SmallVectorImpl<SDValue> &InVals) const {
1109   return lowerUnhandledCall(CLI, InVals, "unsupported call to function ");
1110 }
1111 
1112 SDValue AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
1113                                                       SelectionDAG &DAG) const {
1114   const Function &Fn = DAG.getMachineFunction().getFunction();
1115 
1116   DiagnosticInfoUnsupported NoDynamicAlloca(Fn, "unsupported dynamic alloca",
1117                                             SDLoc(Op).getDebugLoc());
1118   DAG.getContext()->diagnose(NoDynamicAlloca);
1119   auto Ops = {DAG.getConstant(0, SDLoc(), Op.getValueType()), Op.getOperand(0)};
1120   return DAG.getMergeValues(Ops, SDLoc());
1121 }
1122 
1123 SDValue AMDGPUTargetLowering::LowerOperation(SDValue Op,
1124                                              SelectionDAG &DAG) const {
1125   switch (Op.getOpcode()) {
1126   default:
1127     Op->print(errs(), &DAG);
1128     llvm_unreachable("Custom lowering code for this"
1129                      "instruction is not implemented yet!");
1130     break;
1131   case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
1132   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
1133   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
1134   case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
1135   case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
1136   case ISD::FREM: return LowerFREM(Op, DAG);
1137   case ISD::FCEIL: return LowerFCEIL(Op, DAG);
1138   case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
1139   case ISD::FRINT: return LowerFRINT(Op, DAG);
1140   case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
1141   case ISD::FROUND: return LowerFROUND(Op, DAG);
1142   case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
1143   case ISD::FLOG:
1144     return LowerFLOG(Op, DAG, 1.0F / numbers::log2ef);
1145   case ISD::FLOG10:
1146     return LowerFLOG(Op, DAG, numbers::ln2f / numbers::ln10f);
1147   case ISD::FEXP:
1148     return lowerFEXP(Op, DAG);
1149   case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
1150   case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
1151   case ISD::FP_TO_FP16: return LowerFP_TO_FP16(Op, DAG);
1152   case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
1153   case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
1154   case ISD::CTTZ:
1155   case ISD::CTTZ_ZERO_UNDEF:
1156   case ISD::CTLZ:
1157   case ISD::CTLZ_ZERO_UNDEF:
1158     return LowerCTLZ_CTTZ(Op, DAG);
1159   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1160   }
1161   return Op;
1162 }
1163 
1164 void AMDGPUTargetLowering::ReplaceNodeResults(SDNode *N,
1165                                               SmallVectorImpl<SDValue> &Results,
1166                                               SelectionDAG &DAG) const {
1167   switch (N->getOpcode()) {
1168   case ISD::SIGN_EXTEND_INREG:
1169     // Different parts of legalization seem to interpret which type of
1170     // sign_extend_inreg is the one to check for custom lowering. The extended
1171     // from type is what really matters, but some places check for custom
1172     // lowering of the result type. This results in trying to use
1173     // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
1174     // nothing here and let the illegal result integer be handled normally.
1175     return;
1176   default:
1177     return;
1178   }
1179 }
1180 
1181 bool AMDGPUTargetLowering::hasDefinedInitializer(const GlobalValue *GV) {
1182   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1183   if (!GVar || !GVar->hasInitializer())
1184     return false;
1185 
1186   return !isa<UndefValue>(GVar->getInitializer());
1187 }
1188 
1189 SDValue AMDGPUTargetLowering::LowerGlobalAddress(AMDGPUMachineFunction* MFI,
1190                                                  SDValue Op,
1191                                                  SelectionDAG &DAG) const {
1192 
1193   const DataLayout &DL = DAG.getDataLayout();
1194   GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
1195   const GlobalValue *GV = G->getGlobal();
1196 
1197   if (G->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1198       G->getAddressSpace() == AMDGPUAS::REGION_ADDRESS) {
1199     if (!MFI->isEntryFunction()) {
1200       const Function &Fn = DAG.getMachineFunction().getFunction();
1201       DiagnosticInfoUnsupported BadLDSDecl(
1202         Fn, "local memory global used by non-kernel function", SDLoc(Op).getDebugLoc());
1203       DAG.getContext()->diagnose(BadLDSDecl);
1204     }
1205 
1206     // XXX: What does the value of G->getOffset() mean?
1207     assert(G->getOffset() == 0 &&
1208          "Do not know what to do with an non-zero offset");
1209 
1210     // TODO: We could emit code to handle the initialization somewhere.
1211     if (!hasDefinedInitializer(GV)) {
1212       unsigned Offset = MFI->allocateLDSGlobal(DL, *GV);
1213       return DAG.getConstant(Offset, SDLoc(Op), Op.getValueType());
1214     }
1215   }
1216 
1217   const Function &Fn = DAG.getMachineFunction().getFunction();
1218   DiagnosticInfoUnsupported BadInit(
1219       Fn, "unsupported initializer for address space", SDLoc(Op).getDebugLoc());
1220   DAG.getContext()->diagnose(BadInit);
1221   return SDValue();
1222 }
1223 
1224 SDValue AMDGPUTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
1225                                                   SelectionDAG &DAG) const {
1226   SmallVector<SDValue, 8> Args;
1227 
1228   EVT VT = Op.getValueType();
1229   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
1230     SDLoc SL(Op);
1231     SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(0));
1232     SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(1));
1233 
1234     SDValue BV = DAG.getBuildVector(MVT::v2i32, SL, { Lo, Hi });
1235     return DAG.getNode(ISD::BITCAST, SL, VT, BV);
1236   }
1237 
1238   for (const SDUse &U : Op->ops())
1239     DAG.ExtractVectorElements(U.get(), Args);
1240 
1241   return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1242 }
1243 
1244 SDValue AMDGPUTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
1245                                                      SelectionDAG &DAG) const {
1246 
1247   SmallVector<SDValue, 8> Args;
1248   unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1249   EVT VT = Op.getValueType();
1250   DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
1251                             VT.getVectorNumElements());
1252 
1253   return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1254 }
1255 
1256 /// Generate Min/Max node
1257 SDValue AMDGPUTargetLowering::combineFMinMaxLegacy(const SDLoc &DL, EVT VT,
1258                                                    SDValue LHS, SDValue RHS,
1259                                                    SDValue True, SDValue False,
1260                                                    SDValue CC,
1261                                                    DAGCombinerInfo &DCI) const {
1262   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
1263     return SDValue();
1264 
1265   SelectionDAG &DAG = DCI.DAG;
1266   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1267   switch (CCOpcode) {
1268   case ISD::SETOEQ:
1269   case ISD::SETONE:
1270   case ISD::SETUNE:
1271   case ISD::SETNE:
1272   case ISD::SETUEQ:
1273   case ISD::SETEQ:
1274   case ISD::SETFALSE:
1275   case ISD::SETFALSE2:
1276   case ISD::SETTRUE:
1277   case ISD::SETTRUE2:
1278   case ISD::SETUO:
1279   case ISD::SETO:
1280     break;
1281   case ISD::SETULE:
1282   case ISD::SETULT: {
1283     if (LHS == True)
1284       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1285     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1286   }
1287   case ISD::SETOLE:
1288   case ISD::SETOLT:
1289   case ISD::SETLE:
1290   case ISD::SETLT: {
1291     // Ordered. Assume ordered for undefined.
1292 
1293     // Only do this after legalization to avoid interfering with other combines
1294     // which might occur.
1295     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1296         !DCI.isCalledByLegalizer())
1297       return SDValue();
1298 
1299     // We need to permute the operands to get the correct NaN behavior. The
1300     // selected operand is the second one based on the failing compare with NaN,
1301     // so permute it based on the compare type the hardware uses.
1302     if (LHS == True)
1303       return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1304     return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1305   }
1306   case ISD::SETUGE:
1307   case ISD::SETUGT: {
1308     if (LHS == True)
1309       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1310     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1311   }
1312   case ISD::SETGT:
1313   case ISD::SETGE:
1314   case ISD::SETOGE:
1315   case ISD::SETOGT: {
1316     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1317         !DCI.isCalledByLegalizer())
1318       return SDValue();
1319 
1320     if (LHS == True)
1321       return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1322     return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1323   }
1324   case ISD::SETCC_INVALID:
1325     llvm_unreachable("Invalid setcc condcode!");
1326   }
1327   return SDValue();
1328 }
1329 
1330 std::pair<SDValue, SDValue>
1331 AMDGPUTargetLowering::split64BitValue(SDValue Op, SelectionDAG &DAG) const {
1332   SDLoc SL(Op);
1333 
1334   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1335 
1336   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1337   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1338 
1339   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1340   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1341 
1342   return std::make_pair(Lo, Hi);
1343 }
1344 
1345 SDValue AMDGPUTargetLowering::getLoHalf64(SDValue Op, SelectionDAG &DAG) const {
1346   SDLoc SL(Op);
1347 
1348   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1349   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1350   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1351 }
1352 
1353 SDValue AMDGPUTargetLowering::getHiHalf64(SDValue Op, SelectionDAG &DAG) const {
1354   SDLoc SL(Op);
1355 
1356   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1357   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1358   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1359 }
1360 
1361 // Split a vector type into two parts. The first part is a power of two vector.
1362 // The second part is whatever is left over, and is a scalar if it would
1363 // otherwise be a 1-vector.
1364 std::pair<EVT, EVT>
1365 AMDGPUTargetLowering::getSplitDestVTs(const EVT &VT, SelectionDAG &DAG) const {
1366   EVT LoVT, HiVT;
1367   EVT EltVT = VT.getVectorElementType();
1368   unsigned NumElts = VT.getVectorNumElements();
1369   unsigned LoNumElts = PowerOf2Ceil((NumElts + 1) / 2);
1370   LoVT = EVT::getVectorVT(*DAG.getContext(), EltVT, LoNumElts);
1371   HiVT = NumElts - LoNumElts == 1
1372              ? EltVT
1373              : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts - LoNumElts);
1374   return std::make_pair(LoVT, HiVT);
1375 }
1376 
1377 // Split a vector value into two parts of types LoVT and HiVT. HiVT could be
1378 // scalar.
1379 std::pair<SDValue, SDValue>
1380 AMDGPUTargetLowering::splitVector(const SDValue &N, const SDLoc &DL,
1381                                   const EVT &LoVT, const EVT &HiVT,
1382                                   SelectionDAG &DAG) const {
1383   assert(LoVT.getVectorNumElements() +
1384                  (HiVT.isVector() ? HiVT.getVectorNumElements() : 1) <=
1385              N.getValueType().getVectorNumElements() &&
1386          "More vector elements requested than available!");
1387   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
1388                            DAG.getVectorIdxConstant(0, DL));
1389   SDValue Hi = DAG.getNode(
1390       HiVT.isVector() ? ISD::EXTRACT_SUBVECTOR : ISD::EXTRACT_VECTOR_ELT, DL,
1391       HiVT, N, DAG.getVectorIdxConstant(LoVT.getVectorNumElements(), DL));
1392   return std::make_pair(Lo, Hi);
1393 }
1394 
1395 SDValue AMDGPUTargetLowering::SplitVectorLoad(const SDValue Op,
1396                                               SelectionDAG &DAG) const {
1397   LoadSDNode *Load = cast<LoadSDNode>(Op);
1398   EVT VT = Op.getValueType();
1399   SDLoc SL(Op);
1400 
1401 
1402   // If this is a 2 element vector, we really want to scalarize and not create
1403   // weird 1 element vectors.
1404   if (VT.getVectorNumElements() == 2) {
1405     SDValue Ops[2];
1406     std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
1407     return DAG.getMergeValues(Ops, SL);
1408   }
1409 
1410   SDValue BasePtr = Load->getBasePtr();
1411   EVT MemVT = Load->getMemoryVT();
1412 
1413   const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1414 
1415   EVT LoVT, HiVT;
1416   EVT LoMemVT, HiMemVT;
1417   SDValue Lo, Hi;
1418 
1419   std::tie(LoVT, HiVT) = getSplitDestVTs(VT, DAG);
1420   std::tie(LoMemVT, HiMemVT) = getSplitDestVTs(MemVT, DAG);
1421   std::tie(Lo, Hi) = splitVector(Op, SL, LoVT, HiVT, DAG);
1422 
1423   unsigned Size = LoMemVT.getStoreSize();
1424   unsigned BaseAlign = Load->getAlignment();
1425   unsigned HiAlign = MinAlign(BaseAlign, Size);
1426 
1427   SDValue LoLoad = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1428                                   Load->getChain(), BasePtr, SrcValue, LoMemVT,
1429                                   BaseAlign, Load->getMemOperand()->getFlags());
1430   SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, Size);
1431   SDValue HiLoad =
1432       DAG.getExtLoad(Load->getExtensionType(), SL, HiVT, Load->getChain(),
1433                      HiPtr, SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1434                      HiMemVT, HiAlign, Load->getMemOperand()->getFlags());
1435 
1436   SDValue Join;
1437   if (LoVT == HiVT) {
1438     // This is the case that the vector is power of two so was evenly split.
1439     Join = DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad);
1440   } else {
1441     Join = DAG.getNode(ISD::INSERT_SUBVECTOR, SL, VT, DAG.getUNDEF(VT), LoLoad,
1442                        DAG.getVectorIdxConstant(0, SL));
1443     Join = DAG.getNode(
1444         HiVT.isVector() ? ISD::INSERT_SUBVECTOR : ISD::INSERT_VECTOR_ELT, SL,
1445         VT, Join, HiLoad,
1446         DAG.getVectorIdxConstant(LoVT.getVectorNumElements(), SL));
1447   }
1448 
1449   SDValue Ops[] = {Join, DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
1450                                      LoLoad.getValue(1), HiLoad.getValue(1))};
1451 
1452   return DAG.getMergeValues(Ops, SL);
1453 }
1454 
1455 // Widen a vector load from vec3 to vec4.
1456 SDValue AMDGPUTargetLowering::WidenVectorLoad(SDValue Op,
1457                                               SelectionDAG &DAG) const {
1458   LoadSDNode *Load = cast<LoadSDNode>(Op);
1459   EVT VT = Op.getValueType();
1460   assert(VT.getVectorNumElements() == 3);
1461   SDValue BasePtr = Load->getBasePtr();
1462   EVT MemVT = Load->getMemoryVT();
1463   SDLoc SL(Op);
1464   const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1465   unsigned BaseAlign = Load->getAlignment();
1466 
1467   EVT WideVT =
1468       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
1469   EVT WideMemVT =
1470       EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 4);
1471   SDValue WideLoad = DAG.getExtLoad(
1472       Load->getExtensionType(), SL, WideVT, Load->getChain(), BasePtr, SrcValue,
1473       WideMemVT, BaseAlign, Load->getMemOperand()->getFlags());
1474   return DAG.getMergeValues(
1475       {DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, VT, WideLoad,
1476                    DAG.getVectorIdxConstant(0, SL)),
1477        WideLoad.getValue(1)},
1478       SL);
1479 }
1480 
1481 SDValue AMDGPUTargetLowering::SplitVectorStore(SDValue Op,
1482                                                SelectionDAG &DAG) const {
1483   StoreSDNode *Store = cast<StoreSDNode>(Op);
1484   SDValue Val = Store->getValue();
1485   EVT VT = Val.getValueType();
1486 
1487   // If this is a 2 element vector, we really want to scalarize and not create
1488   // weird 1 element vectors.
1489   if (VT.getVectorNumElements() == 2)
1490     return scalarizeVectorStore(Store, DAG);
1491 
1492   EVT MemVT = Store->getMemoryVT();
1493   SDValue Chain = Store->getChain();
1494   SDValue BasePtr = Store->getBasePtr();
1495   SDLoc SL(Op);
1496 
1497   EVT LoVT, HiVT;
1498   EVT LoMemVT, HiMemVT;
1499   SDValue Lo, Hi;
1500 
1501   std::tie(LoVT, HiVT) = getSplitDestVTs(VT, DAG);
1502   std::tie(LoMemVT, HiMemVT) = getSplitDestVTs(MemVT, DAG);
1503   std::tie(Lo, Hi) = splitVector(Val, SL, LoVT, HiVT, DAG);
1504 
1505   SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, LoMemVT.getStoreSize());
1506 
1507   const MachinePointerInfo &SrcValue = Store->getMemOperand()->getPointerInfo();
1508   unsigned BaseAlign = Store->getAlignment();
1509   unsigned Size = LoMemVT.getStoreSize();
1510   unsigned HiAlign = MinAlign(BaseAlign, Size);
1511 
1512   SDValue LoStore =
1513       DAG.getTruncStore(Chain, SL, Lo, BasePtr, SrcValue, LoMemVT, BaseAlign,
1514                         Store->getMemOperand()->getFlags());
1515   SDValue HiStore =
1516       DAG.getTruncStore(Chain, SL, Hi, HiPtr, SrcValue.getWithOffset(Size),
1517                         HiMemVT, HiAlign, Store->getMemOperand()->getFlags());
1518 
1519   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1520 }
1521 
1522 // This is a shortcut for integer division because we have fast i32<->f32
1523 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1524 // float is enough to accurately represent up to a 24-bit signed integer.
1525 SDValue AMDGPUTargetLowering::LowerDIVREM24(SDValue Op, SelectionDAG &DAG,
1526                                             bool Sign) const {
1527   SDLoc DL(Op);
1528   EVT VT = Op.getValueType();
1529   SDValue LHS = Op.getOperand(0);
1530   SDValue RHS = Op.getOperand(1);
1531   MVT IntVT = MVT::i32;
1532   MVT FltVT = MVT::f32;
1533 
1534   unsigned LHSSignBits = DAG.ComputeNumSignBits(LHS);
1535   if (LHSSignBits < 9)
1536     return SDValue();
1537 
1538   unsigned RHSSignBits = DAG.ComputeNumSignBits(RHS);
1539   if (RHSSignBits < 9)
1540     return SDValue();
1541 
1542   unsigned BitSize = VT.getSizeInBits();
1543   unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1544   unsigned DivBits = BitSize - SignBits;
1545   if (Sign)
1546     ++DivBits;
1547 
1548   ISD::NodeType ToFp = Sign ? ISD::SINT_TO_FP : ISD::UINT_TO_FP;
1549   ISD::NodeType ToInt = Sign ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
1550 
1551   SDValue jq = DAG.getConstant(1, DL, IntVT);
1552 
1553   if (Sign) {
1554     // char|short jq = ia ^ ib;
1555     jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1556 
1557     // jq = jq >> (bitsize - 2)
1558     jq = DAG.getNode(ISD::SRA, DL, VT, jq,
1559                      DAG.getConstant(BitSize - 2, DL, VT));
1560 
1561     // jq = jq | 0x1
1562     jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, DL, VT));
1563   }
1564 
1565   // int ia = (int)LHS;
1566   SDValue ia = LHS;
1567 
1568   // int ib, (int)RHS;
1569   SDValue ib = RHS;
1570 
1571   // float fa = (float)ia;
1572   SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1573 
1574   // float fb = (float)ib;
1575   SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1576 
1577   SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1578                            fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1579 
1580   // fq = trunc(fq);
1581   fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1582 
1583   // float fqneg = -fq;
1584   SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1585 
1586   MachineFunction &MF = DAG.getMachineFunction();
1587   const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
1588 
1589   // float fr = mad(fqneg, fb, fa);
1590   unsigned OpCode = MFI->getMode().FP32Denormals ?
1591                     (unsigned)AMDGPUISD::FMAD_FTZ :
1592                     (unsigned)ISD::FMAD;
1593   SDValue fr = DAG.getNode(OpCode, DL, FltVT, fqneg, fb, fa);
1594 
1595   // int iq = (int)fq;
1596   SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1597 
1598   // fr = fabs(fr);
1599   fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1600 
1601   // fb = fabs(fb);
1602   fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1603 
1604   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
1605 
1606   // int cv = fr >= fb;
1607   SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1608 
1609   // jq = (cv ? jq : 0);
1610   jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, DL, VT));
1611 
1612   // dst = iq + jq;
1613   SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1614 
1615   // Rem needs compensation, it's easier to recompute it
1616   SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1617   Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1618 
1619   // Truncate to number of bits this divide really is.
1620   if (Sign) {
1621     SDValue InRegSize
1622       = DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), DivBits));
1623     Div = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Div, InRegSize);
1624     Rem = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Rem, InRegSize);
1625   } else {
1626     SDValue TruncMask = DAG.getConstant((UINT64_C(1) << DivBits) - 1, DL, VT);
1627     Div = DAG.getNode(ISD::AND, DL, VT, Div, TruncMask);
1628     Rem = DAG.getNode(ISD::AND, DL, VT, Rem, TruncMask);
1629   }
1630 
1631   return DAG.getMergeValues({ Div, Rem }, DL);
1632 }
1633 
1634 void AMDGPUTargetLowering::LowerUDIVREM64(SDValue Op,
1635                                       SelectionDAG &DAG,
1636                                       SmallVectorImpl<SDValue> &Results) const {
1637   SDLoc DL(Op);
1638   EVT VT = Op.getValueType();
1639 
1640   assert(VT == MVT::i64 && "LowerUDIVREM64 expects an i64");
1641 
1642   EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1643 
1644   SDValue One = DAG.getConstant(1, DL, HalfVT);
1645   SDValue Zero = DAG.getConstant(0, DL, HalfVT);
1646 
1647   //HiLo split
1648   SDValue LHS = Op.getOperand(0);
1649   SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1650   SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, One);
1651 
1652   SDValue RHS = Op.getOperand(1);
1653   SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1654   SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, One);
1655 
1656   if (DAG.MaskedValueIsZero(RHS, APInt::getHighBitsSet(64, 32)) &&
1657       DAG.MaskedValueIsZero(LHS, APInt::getHighBitsSet(64, 32))) {
1658 
1659     SDValue Res = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1660                               LHS_Lo, RHS_Lo);
1661 
1662     SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(0), Zero});
1663     SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(1), Zero});
1664 
1665     Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV));
1666     Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM));
1667     return;
1668   }
1669 
1670   if (isTypeLegal(MVT::i64)) {
1671     MachineFunction &MF = DAG.getMachineFunction();
1672     const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1673 
1674     // Compute denominator reciprocal.
1675     unsigned FMAD = MFI->getMode().FP32Denormals ?
1676                     (unsigned)AMDGPUISD::FMAD_FTZ :
1677                     (unsigned)ISD::FMAD;
1678 
1679     SDValue Cvt_Lo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Lo);
1680     SDValue Cvt_Hi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Hi);
1681     SDValue Mad1 = DAG.getNode(FMAD, DL, MVT::f32, Cvt_Hi,
1682       DAG.getConstantFP(APInt(32, 0x4f800000).bitsToFloat(), DL, MVT::f32),
1683       Cvt_Lo);
1684     SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, DL, MVT::f32, Mad1);
1685     SDValue Mul1 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Rcp,
1686       DAG.getConstantFP(APInt(32, 0x5f7ffffc).bitsToFloat(), DL, MVT::f32));
1687     SDValue Mul2 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Mul1,
1688       DAG.getConstantFP(APInt(32, 0x2f800000).bitsToFloat(), DL, MVT::f32));
1689     SDValue Trunc = DAG.getNode(ISD::FTRUNC, DL, MVT::f32, Mul2);
1690     SDValue Mad2 = DAG.getNode(FMAD, DL, MVT::f32, Trunc,
1691       DAG.getConstantFP(APInt(32, 0xcf800000).bitsToFloat(), DL, MVT::f32),
1692       Mul1);
1693     SDValue Rcp_Lo = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Mad2);
1694     SDValue Rcp_Hi = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Trunc);
1695     SDValue Rcp64 = DAG.getBitcast(VT,
1696                         DAG.getBuildVector(MVT::v2i32, DL, {Rcp_Lo, Rcp_Hi}));
1697 
1698     SDValue Zero64 = DAG.getConstant(0, DL, VT);
1699     SDValue One64  = DAG.getConstant(1, DL, VT);
1700     SDValue Zero1 = DAG.getConstant(0, DL, MVT::i1);
1701     SDVTList HalfCarryVT = DAG.getVTList(HalfVT, MVT::i1);
1702 
1703     SDValue Neg_RHS = DAG.getNode(ISD::SUB, DL, VT, Zero64, RHS);
1704     SDValue Mullo1 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Rcp64);
1705     SDValue Mulhi1 = DAG.getNode(ISD::MULHU, DL, VT, Rcp64, Mullo1);
1706     SDValue Mulhi1_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1707                                     Zero);
1708     SDValue Mulhi1_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1709                                     One);
1710 
1711     SDValue Add1_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Lo,
1712                                   Mulhi1_Lo, Zero1);
1713     SDValue Add1_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Hi,
1714                                   Mulhi1_Hi, Add1_Lo.getValue(1));
1715     SDValue Add1_HiNc = DAG.getNode(ISD::ADD, DL, HalfVT, Rcp_Hi, Mulhi1_Hi);
1716     SDValue Add1 = DAG.getBitcast(VT,
1717                         DAG.getBuildVector(MVT::v2i32, DL, {Add1_Lo, Add1_Hi}));
1718 
1719     SDValue Mullo2 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Add1);
1720     SDValue Mulhi2 = DAG.getNode(ISD::MULHU, DL, VT, Add1, Mullo2);
1721     SDValue Mulhi2_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1722                                     Zero);
1723     SDValue Mulhi2_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1724                                     One);
1725 
1726     SDValue Add2_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_Lo,
1727                                   Mulhi2_Lo, Zero1);
1728     SDValue Add2_HiC = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_HiNc,
1729                                    Mulhi2_Hi, Add1_Lo.getValue(1));
1730     SDValue Add2_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add2_HiC,
1731                                   Zero, Add2_Lo.getValue(1));
1732     SDValue Add2 = DAG.getBitcast(VT,
1733                         DAG.getBuildVector(MVT::v2i32, DL, {Add2_Lo, Add2_Hi}));
1734     SDValue Mulhi3 = DAG.getNode(ISD::MULHU, DL, VT, LHS, Add2);
1735 
1736     SDValue Mul3 = DAG.getNode(ISD::MUL, DL, VT, RHS, Mulhi3);
1737 
1738     SDValue Mul3_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, Zero);
1739     SDValue Mul3_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, One);
1740     SDValue Sub1_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Lo,
1741                                   Mul3_Lo, Zero1);
1742     SDValue Sub1_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Hi,
1743                                   Mul3_Hi, Sub1_Lo.getValue(1));
1744     SDValue Sub1_Mi = DAG.getNode(ISD::SUB, DL, HalfVT, LHS_Hi, Mul3_Hi);
1745     SDValue Sub1 = DAG.getBitcast(VT,
1746                         DAG.getBuildVector(MVT::v2i32, DL, {Sub1_Lo, Sub1_Hi}));
1747 
1748     SDValue MinusOne = DAG.getConstant(0xffffffffu, DL, HalfVT);
1749     SDValue C1 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, MinusOne, Zero,
1750                                  ISD::SETUGE);
1751     SDValue C2 = DAG.getSelectCC(DL, Sub1_Lo, RHS_Lo, MinusOne, Zero,
1752                                  ISD::SETUGE);
1753     SDValue C3 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, C2, C1, ISD::SETEQ);
1754 
1755     // TODO: Here and below portions of the code can be enclosed into if/endif.
1756     // Currently control flow is unconditional and we have 4 selects after
1757     // potential endif to substitute PHIs.
1758 
1759     // if C3 != 0 ...
1760     SDValue Sub2_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Lo,
1761                                   RHS_Lo, Zero1);
1762     SDValue Sub2_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Mi,
1763                                   RHS_Hi, Sub1_Lo.getValue(1));
1764     SDValue Sub2_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1765                                   Zero, Sub2_Lo.getValue(1));
1766     SDValue Sub2 = DAG.getBitcast(VT,
1767                         DAG.getBuildVector(MVT::v2i32, DL, {Sub2_Lo, Sub2_Hi}));
1768 
1769     SDValue Add3 = DAG.getNode(ISD::ADD, DL, VT, Mulhi3, One64);
1770 
1771     SDValue C4 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, MinusOne, Zero,
1772                                  ISD::SETUGE);
1773     SDValue C5 = DAG.getSelectCC(DL, Sub2_Lo, RHS_Lo, MinusOne, Zero,
1774                                  ISD::SETUGE);
1775     SDValue C6 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, C5, C4, ISD::SETEQ);
1776 
1777     // if (C6 != 0)
1778     SDValue Add4 = DAG.getNode(ISD::ADD, DL, VT, Add3, One64);
1779 
1780     SDValue Sub3_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Lo,
1781                                   RHS_Lo, Zero1);
1782     SDValue Sub3_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1783                                   RHS_Hi, Sub2_Lo.getValue(1));
1784     SDValue Sub3_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub3_Mi,
1785                                   Zero, Sub3_Lo.getValue(1));
1786     SDValue Sub3 = DAG.getBitcast(VT,
1787                         DAG.getBuildVector(MVT::v2i32, DL, {Sub3_Lo, Sub3_Hi}));
1788 
1789     // endif C6
1790     // endif C3
1791 
1792     SDValue Sel1 = DAG.getSelectCC(DL, C6, Zero, Add4, Add3, ISD::SETNE);
1793     SDValue Div  = DAG.getSelectCC(DL, C3, Zero, Sel1, Mulhi3, ISD::SETNE);
1794 
1795     SDValue Sel2 = DAG.getSelectCC(DL, C6, Zero, Sub3, Sub2, ISD::SETNE);
1796     SDValue Rem  = DAG.getSelectCC(DL, C3, Zero, Sel2, Sub1, ISD::SETNE);
1797 
1798     Results.push_back(Div);
1799     Results.push_back(Rem);
1800 
1801     return;
1802   }
1803 
1804   // r600 expandion.
1805   // Get Speculative values
1806   SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
1807   SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
1808 
1809   SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, Zero, REM_Part, LHS_Hi, ISD::SETEQ);
1810   SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {REM_Lo, Zero});
1811   REM = DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM);
1812 
1813   SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, Zero, DIV_Part, Zero, ISD::SETEQ);
1814   SDValue DIV_Lo = Zero;
1815 
1816   const unsigned halfBitWidth = HalfVT.getSizeInBits();
1817 
1818   for (unsigned i = 0; i < halfBitWidth; ++i) {
1819     const unsigned bitPos = halfBitWidth - i - 1;
1820     SDValue POS = DAG.getConstant(bitPos, DL, HalfVT);
1821     // Get value of high bit
1822     SDValue HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
1823     HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, One);
1824     HBit = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, HBit);
1825 
1826     // Shift
1827     REM = DAG.getNode(ISD::SHL, DL, VT, REM, DAG.getConstant(1, DL, VT));
1828     // Add LHS high bit
1829     REM = DAG.getNode(ISD::OR, DL, VT, REM, HBit);
1830 
1831     SDValue BIT = DAG.getConstant(1ULL << bitPos, DL, HalfVT);
1832     SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, Zero, ISD::SETUGE);
1833 
1834     DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
1835 
1836     // Update REM
1837     SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
1838     REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETUGE);
1839   }
1840 
1841   SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {DIV_Lo, DIV_Hi});
1842   DIV = DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV);
1843   Results.push_back(DIV);
1844   Results.push_back(REM);
1845 }
1846 
1847 SDValue AMDGPUTargetLowering::LowerUDIVREM(SDValue Op,
1848                                            SelectionDAG &DAG) const {
1849   SDLoc DL(Op);
1850   EVT VT = Op.getValueType();
1851 
1852   if (VT == MVT::i64) {
1853     SmallVector<SDValue, 2> Results;
1854     LowerUDIVREM64(Op, DAG, Results);
1855     return DAG.getMergeValues(Results, DL);
1856   }
1857 
1858   if (VT == MVT::i32) {
1859     if (SDValue Res = LowerDIVREM24(Op, DAG, false))
1860       return Res;
1861   }
1862 
1863   SDValue Num = Op.getOperand(0);
1864   SDValue Den = Op.getOperand(1);
1865 
1866   // RCP =  URECIP(Den) = 2^32 / Den + e
1867   // e is rounding error.
1868   SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1869 
1870   // RCP_LO = mul(RCP, Den) */
1871   SDValue RCP_LO = DAG.getNode(ISD::MUL, DL, VT, RCP, Den);
1872 
1873   // RCP_HI = mulhu (RCP, Den) */
1874   SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1875 
1876   // NEG_RCP_LO = -RCP_LO
1877   SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
1878                                                      RCP_LO);
1879 
1880   // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1881   SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1882                                            NEG_RCP_LO, RCP_LO,
1883                                            ISD::SETEQ);
1884   // Calculate the rounding error from the URECIP instruction
1885   // E = mulhu(ABS_RCP_LO, RCP)
1886   SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1887 
1888   // RCP_A_E = RCP + E
1889   SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1890 
1891   // RCP_S_E = RCP - E
1892   SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1893 
1894   // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1895   SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1896                                      RCP_A_E, RCP_S_E,
1897                                      ISD::SETEQ);
1898   // Quotient = mulhu(Tmp0, Num)
1899   SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1900 
1901   // Num_S_Remainder = Quotient * Den
1902   SDValue Num_S_Remainder = DAG.getNode(ISD::MUL, DL, VT, Quotient, Den);
1903 
1904   // Remainder = Num - Num_S_Remainder
1905   SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1906 
1907   // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1908   SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1909                                                  DAG.getConstant(-1, DL, VT),
1910                                                  DAG.getConstant(0, DL, VT),
1911                                                  ISD::SETUGE);
1912   // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1913   SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1914                                                   Num_S_Remainder,
1915                                                   DAG.getConstant(-1, DL, VT),
1916                                                   DAG.getConstant(0, DL, VT),
1917                                                   ISD::SETUGE);
1918   // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1919   SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1920                                                Remainder_GE_Zero);
1921 
1922   // Calculate Division result:
1923 
1924   // Quotient_A_One = Quotient + 1
1925   SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1926                                        DAG.getConstant(1, DL, VT));
1927 
1928   // Quotient_S_One = Quotient - 1
1929   SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1930                                        DAG.getConstant(1, DL, VT));
1931 
1932   // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1933   SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1934                                      Quotient, Quotient_A_One, ISD::SETEQ);
1935 
1936   // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1937   Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1938                             Quotient_S_One, Div, ISD::SETEQ);
1939 
1940   // Calculate Rem result:
1941 
1942   // Remainder_S_Den = Remainder - Den
1943   SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1944 
1945   // Remainder_A_Den = Remainder + Den
1946   SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1947 
1948   // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1949   SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1950                                     Remainder, Remainder_S_Den, ISD::SETEQ);
1951 
1952   // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1953   Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1954                             Remainder_A_Den, Rem, ISD::SETEQ);
1955   SDValue Ops[2] = {
1956     Div,
1957     Rem
1958   };
1959   return DAG.getMergeValues(Ops, DL);
1960 }
1961 
1962 SDValue AMDGPUTargetLowering::LowerSDIVREM(SDValue Op,
1963                                            SelectionDAG &DAG) const {
1964   SDLoc DL(Op);
1965   EVT VT = Op.getValueType();
1966 
1967   SDValue LHS = Op.getOperand(0);
1968   SDValue RHS = Op.getOperand(1);
1969 
1970   SDValue Zero = DAG.getConstant(0, DL, VT);
1971   SDValue NegOne = DAG.getConstant(-1, DL, VT);
1972 
1973   if (VT == MVT::i32) {
1974     if (SDValue Res = LowerDIVREM24(Op, DAG, true))
1975       return Res;
1976   }
1977 
1978   if (VT == MVT::i64 &&
1979       DAG.ComputeNumSignBits(LHS) > 32 &&
1980       DAG.ComputeNumSignBits(RHS) > 32) {
1981     EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1982 
1983     //HiLo split
1984     SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1985     SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1986     SDValue DIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1987                                  LHS_Lo, RHS_Lo);
1988     SDValue Res[2] = {
1989       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(0)),
1990       DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(1))
1991     };
1992     return DAG.getMergeValues(Res, DL);
1993   }
1994 
1995   SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
1996   SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
1997   SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
1998   SDValue RSign = LHSign; // Remainder sign is the same as LHS
1999 
2000   LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
2001   RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
2002 
2003   LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
2004   RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
2005 
2006   SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
2007   SDValue Rem = Div.getValue(1);
2008 
2009   Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
2010   Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
2011 
2012   Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
2013   Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
2014 
2015   SDValue Res[2] = {
2016     Div,
2017     Rem
2018   };
2019   return DAG.getMergeValues(Res, DL);
2020 }
2021 
2022 // (frem x, y) -> (fsub x, (fmul (ftrunc (fdiv x, y)), y))
2023 SDValue AMDGPUTargetLowering::LowerFREM(SDValue Op, SelectionDAG &DAG) const {
2024   SDLoc SL(Op);
2025   EVT VT = Op.getValueType();
2026   SDValue X = Op.getOperand(0);
2027   SDValue Y = Op.getOperand(1);
2028 
2029   // TODO: Should this propagate fast-math-flags?
2030 
2031   SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y);
2032   SDValue Floor = DAG.getNode(ISD::FTRUNC, SL, VT, Div);
2033   SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Floor, Y);
2034 
2035   return DAG.getNode(ISD::FSUB, SL, VT, X, Mul);
2036 }
2037 
2038 SDValue AMDGPUTargetLowering::LowerFCEIL(SDValue Op, SelectionDAG &DAG) const {
2039   SDLoc SL(Op);
2040   SDValue Src = Op.getOperand(0);
2041 
2042   // result = trunc(src)
2043   // if (src > 0.0 && src != result)
2044   //   result += 1.0
2045 
2046   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2047 
2048   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
2049   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
2050 
2051   EVT SetCCVT =
2052       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
2053 
2054   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
2055   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2056   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2057 
2058   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
2059   // TODO: Should this propagate fast-math-flags?
2060   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2061 }
2062 
2063 static SDValue extractF64Exponent(SDValue Hi, const SDLoc &SL,
2064                                   SelectionDAG &DAG) {
2065   const unsigned FractBits = 52;
2066   const unsigned ExpBits = 11;
2067 
2068   SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
2069                                 Hi,
2070                                 DAG.getConstant(FractBits - 32, SL, MVT::i32),
2071                                 DAG.getConstant(ExpBits, SL, MVT::i32));
2072   SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
2073                             DAG.getConstant(1023, SL, MVT::i32));
2074 
2075   return Exp;
2076 }
2077 
2078 SDValue AMDGPUTargetLowering::LowerFTRUNC(SDValue Op, SelectionDAG &DAG) const {
2079   SDLoc SL(Op);
2080   SDValue Src = Op.getOperand(0);
2081 
2082   assert(Op.getValueType() == MVT::f64);
2083 
2084   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2085   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2086 
2087   SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2088 
2089   // Extract the upper half, since this is where we will find the sign and
2090   // exponent.
2091   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
2092 
2093   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2094 
2095   const unsigned FractBits = 52;
2096 
2097   // Extract the sign bit.
2098   const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, SL, MVT::i32);
2099   SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
2100 
2101   // Extend back to 64-bits.
2102   SDValue SignBit64 = DAG.getBuildVector(MVT::v2i32, SL, {Zero, SignBit});
2103   SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
2104 
2105   SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
2106   const SDValue FractMask
2107     = DAG.getConstant((UINT64_C(1) << FractBits) - 1, SL, MVT::i64);
2108 
2109   SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
2110   SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
2111   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
2112 
2113   EVT SetCCVT =
2114       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
2115 
2116   const SDValue FiftyOne = DAG.getConstant(FractBits - 1, SL, MVT::i32);
2117 
2118   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2119   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2120 
2121   SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
2122   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
2123 
2124   return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
2125 }
2126 
2127 SDValue AMDGPUTargetLowering::LowerFRINT(SDValue Op, SelectionDAG &DAG) const {
2128   SDLoc SL(Op);
2129   SDValue Src = Op.getOperand(0);
2130 
2131   assert(Op.getValueType() == MVT::f64);
2132 
2133   APFloat C1Val(APFloat::IEEEdouble(), "0x1.0p+52");
2134   SDValue C1 = DAG.getConstantFP(C1Val, SL, MVT::f64);
2135   SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
2136 
2137   // TODO: Should this propagate fast-math-flags?
2138 
2139   SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
2140   SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
2141 
2142   SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
2143 
2144   APFloat C2Val(APFloat::IEEEdouble(), "0x1.fffffffffffffp+51");
2145   SDValue C2 = DAG.getConstantFP(C2Val, SL, MVT::f64);
2146 
2147   EVT SetCCVT =
2148       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
2149   SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
2150 
2151   return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
2152 }
2153 
2154 SDValue AMDGPUTargetLowering::LowerFNEARBYINT(SDValue Op, SelectionDAG &DAG) const {
2155   // FNEARBYINT and FRINT are the same, except in their handling of FP
2156   // exceptions. Those aren't really meaningful for us, and OpenCL only has
2157   // rint, so just treat them as equivalent.
2158   return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
2159 }
2160 
2161 // XXX - May require not supporting f32 denormals?
2162 
2163 // Don't handle v2f16. The extra instructions to scalarize and repack around the
2164 // compare and vselect end up producing worse code than scalarizing the whole
2165 // operation.
2166 SDValue AMDGPUTargetLowering::LowerFROUND_LegalFTRUNC(SDValue Op,
2167                                                       SelectionDAG &DAG) const {
2168   SDLoc SL(Op);
2169   SDValue X = Op.getOperand(0);
2170   EVT VT = Op.getValueType();
2171 
2172   SDValue T = DAG.getNode(ISD::FTRUNC, SL, VT, X);
2173 
2174   // TODO: Should this propagate fast-math-flags?
2175 
2176   SDValue Diff = DAG.getNode(ISD::FSUB, SL, VT, X, T);
2177 
2178   SDValue AbsDiff = DAG.getNode(ISD::FABS, SL, VT, Diff);
2179 
2180   const SDValue Zero = DAG.getConstantFP(0.0, SL, VT);
2181   const SDValue One = DAG.getConstantFP(1.0, SL, VT);
2182   const SDValue Half = DAG.getConstantFP(0.5, SL, VT);
2183 
2184   SDValue SignOne = DAG.getNode(ISD::FCOPYSIGN, SL, VT, One, X);
2185 
2186   EVT SetCCVT =
2187       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2188 
2189   SDValue Cmp = DAG.getSetCC(SL, SetCCVT, AbsDiff, Half, ISD::SETOGE);
2190 
2191   SDValue Sel = DAG.getNode(ISD::SELECT, SL, VT, Cmp, SignOne, Zero);
2192 
2193   return DAG.getNode(ISD::FADD, SL, VT, T, Sel);
2194 }
2195 
2196 SDValue AMDGPUTargetLowering::LowerFROUND64(SDValue Op, SelectionDAG &DAG) const {
2197   SDLoc SL(Op);
2198   SDValue X = Op.getOperand(0);
2199 
2200   SDValue L = DAG.getNode(ISD::BITCAST, SL, MVT::i64, X);
2201 
2202   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2203   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2204   const SDValue NegOne = DAG.getConstant(-1, SL, MVT::i32);
2205   const SDValue FiftyOne = DAG.getConstant(51, SL, MVT::i32);
2206   EVT SetCCVT =
2207       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
2208 
2209   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
2210 
2211   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC, One);
2212 
2213   SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2214 
2215   const SDValue Mask = DAG.getConstant(INT64_C(0x000fffffffffffff), SL,
2216                                        MVT::i64);
2217 
2218   SDValue M = DAG.getNode(ISD::SRA, SL, MVT::i64, Mask, Exp);
2219   SDValue D = DAG.getNode(ISD::SRA, SL, MVT::i64,
2220                           DAG.getConstant(INT64_C(0x0008000000000000), SL,
2221                                           MVT::i64),
2222                           Exp);
2223 
2224   SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, L, M);
2225   SDValue Tmp1 = DAG.getSetCC(SL, SetCCVT,
2226                               DAG.getConstant(0, SL, MVT::i64), Tmp0,
2227                               ISD::SETNE);
2228 
2229   SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, Tmp1,
2230                              D, DAG.getConstant(0, SL, MVT::i64));
2231   SDValue K = DAG.getNode(ISD::ADD, SL, MVT::i64, L, Tmp2);
2232 
2233   K = DAG.getNode(ISD::AND, SL, MVT::i64, K, DAG.getNOT(SL, M, MVT::i64));
2234   K = DAG.getNode(ISD::BITCAST, SL, MVT::f64, K);
2235 
2236   SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2237   SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2238   SDValue ExpEqNegOne = DAG.getSetCC(SL, SetCCVT, NegOne, Exp, ISD::SETEQ);
2239 
2240   SDValue Mag = DAG.getNode(ISD::SELECT, SL, MVT::f64,
2241                             ExpEqNegOne,
2242                             DAG.getConstantFP(1.0, SL, MVT::f64),
2243                             DAG.getConstantFP(0.0, SL, MVT::f64));
2244 
2245   SDValue S = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, Mag, X);
2246 
2247   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpLt0, S, K);
2248   K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpGt51, X, K);
2249 
2250   return K;
2251 }
2252 
2253 SDValue AMDGPUTargetLowering::LowerFROUND(SDValue Op, SelectionDAG &DAG) const {
2254   EVT VT = Op.getValueType();
2255 
2256   if (isOperationLegal(ISD::FTRUNC, VT))
2257     return LowerFROUND_LegalFTRUNC(Op, DAG);
2258 
2259   if (VT == MVT::f64)
2260     return LowerFROUND64(Op, DAG);
2261 
2262   llvm_unreachable("unhandled type");
2263 }
2264 
2265 SDValue AMDGPUTargetLowering::LowerFFLOOR(SDValue Op, SelectionDAG &DAG) const {
2266   SDLoc SL(Op);
2267   SDValue Src = Op.getOperand(0);
2268 
2269   // result = trunc(src);
2270   // if (src < 0.0 && src != result)
2271   //   result += -1.0.
2272 
2273   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2274 
2275   const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
2276   const SDValue NegOne = DAG.getConstantFP(-1.0, SL, MVT::f64);
2277 
2278   EVT SetCCVT =
2279       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f64);
2280 
2281   SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
2282   SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2283   SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2284 
2285   SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
2286   // TODO: Should this propagate fast-math-flags?
2287   return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2288 }
2289 
2290 SDValue AMDGPUTargetLowering::LowerFLOG(SDValue Op, SelectionDAG &DAG,
2291                                         double Log2BaseInverted) const {
2292   EVT VT = Op.getValueType();
2293 
2294   SDLoc SL(Op);
2295   SDValue Operand = Op.getOperand(0);
2296   SDValue Log2Operand = DAG.getNode(ISD::FLOG2, SL, VT, Operand);
2297   SDValue Log2BaseInvertedOperand = DAG.getConstantFP(Log2BaseInverted, SL, VT);
2298 
2299   return DAG.getNode(ISD::FMUL, SL, VT, Log2Operand, Log2BaseInvertedOperand);
2300 }
2301 
2302 // exp2(M_LOG2E_F * f);
2303 SDValue AMDGPUTargetLowering::lowerFEXP(SDValue Op, SelectionDAG &DAG) const {
2304   EVT VT = Op.getValueType();
2305   SDLoc SL(Op);
2306   SDValue Src = Op.getOperand(0);
2307 
2308   const SDValue K = DAG.getConstantFP(numbers::log2e, SL, VT);
2309   SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Src, K, Op->getFlags());
2310   return DAG.getNode(ISD::FEXP2, SL, VT, Mul, Op->getFlags());
2311 }
2312 
2313 static bool isCtlzOpc(unsigned Opc) {
2314   return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_UNDEF;
2315 }
2316 
2317 static bool isCttzOpc(unsigned Opc) {
2318   return Opc == ISD::CTTZ || Opc == ISD::CTTZ_ZERO_UNDEF;
2319 }
2320 
2321 SDValue AMDGPUTargetLowering::LowerCTLZ_CTTZ(SDValue Op, SelectionDAG &DAG) const {
2322   SDLoc SL(Op);
2323   SDValue Src = Op.getOperand(0);
2324   bool ZeroUndef = Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
2325                    Op.getOpcode() == ISD::CTLZ_ZERO_UNDEF;
2326 
2327   unsigned ISDOpc, NewOpc;
2328   if (isCtlzOpc(Op.getOpcode())) {
2329     ISDOpc = ISD::CTLZ_ZERO_UNDEF;
2330     NewOpc = AMDGPUISD::FFBH_U32;
2331   } else if (isCttzOpc(Op.getOpcode())) {
2332     ISDOpc = ISD::CTTZ_ZERO_UNDEF;
2333     NewOpc = AMDGPUISD::FFBL_B32;
2334   } else
2335     llvm_unreachable("Unexpected OPCode!!!");
2336 
2337 
2338   if (ZeroUndef && Src.getValueType() == MVT::i32)
2339     return DAG.getNode(NewOpc, SL, MVT::i32, Src);
2340 
2341   SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2342 
2343   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2344   const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2345 
2346   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
2347   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
2348 
2349   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2350                                    *DAG.getContext(), MVT::i32);
2351 
2352   SDValue HiOrLo = isCtlzOpc(Op.getOpcode()) ? Hi : Lo;
2353   SDValue Hi0orLo0 = DAG.getSetCC(SL, SetCCVT, HiOrLo, Zero, ISD::SETEQ);
2354 
2355   SDValue OprLo = DAG.getNode(ISDOpc, SL, MVT::i32, Lo);
2356   SDValue OprHi = DAG.getNode(ISDOpc, SL, MVT::i32, Hi);
2357 
2358   const SDValue Bits32 = DAG.getConstant(32, SL, MVT::i32);
2359   SDValue Add, NewOpr;
2360   if (isCtlzOpc(Op.getOpcode())) {
2361     Add = DAG.getNode(ISD::ADD, SL, MVT::i32, OprLo, Bits32);
2362     // ctlz(x) = hi_32(x) == 0 ? ctlz(lo_32(x)) + 32 : ctlz(hi_32(x))
2363     NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0orLo0, Add, OprHi);
2364   } else {
2365     Add = DAG.getNode(ISD::ADD, SL, MVT::i32, OprHi, Bits32);
2366     // cttz(x) = lo_32(x) == 0 ? cttz(hi_32(x)) + 32 : cttz(lo_32(x))
2367     NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0orLo0, Add, OprLo);
2368   }
2369 
2370   if (!ZeroUndef) {
2371     // Test if the full 64-bit input is zero.
2372 
2373     // FIXME: DAG combines turn what should be an s_and_b64 into a v_or_b32,
2374     // which we probably don't want.
2375     SDValue LoOrHi = isCtlzOpc(Op.getOpcode()) ? Lo : Hi;
2376     SDValue Lo0OrHi0 = DAG.getSetCC(SL, SetCCVT, LoOrHi, Zero, ISD::SETEQ);
2377     SDValue SrcIsZero = DAG.getNode(ISD::AND, SL, SetCCVT, Lo0OrHi0, Hi0orLo0);
2378 
2379     // TODO: If i64 setcc is half rate, it can result in 1 fewer instruction
2380     // with the same cycles, otherwise it is slower.
2381     // SDValue SrcIsZero = DAG.getSetCC(SL, SetCCVT, Src,
2382     // DAG.getConstant(0, SL, MVT::i64), ISD::SETEQ);
2383 
2384     const SDValue Bits32 = DAG.getConstant(64, SL, MVT::i32);
2385 
2386     // The instruction returns -1 for 0 input, but the defined intrinsic
2387     // behavior is to return the number of bits.
2388     NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32,
2389                          SrcIsZero, Bits32, NewOpr);
2390   }
2391 
2392   return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, NewOpr);
2393 }
2394 
2395 SDValue AMDGPUTargetLowering::LowerINT_TO_FP32(SDValue Op, SelectionDAG &DAG,
2396                                                bool Signed) const {
2397   // Unsigned
2398   // cul2f(ulong u)
2399   //{
2400   //  uint lz = clz(u);
2401   //  uint e = (u != 0) ? 127U + 63U - lz : 0;
2402   //  u = (u << lz) & 0x7fffffffffffffffUL;
2403   //  ulong t = u & 0xffffffffffUL;
2404   //  uint v = (e << 23) | (uint)(u >> 40);
2405   //  uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
2406   //  return as_float(v + r);
2407   //}
2408   // Signed
2409   // cl2f(long l)
2410   //{
2411   //  long s = l >> 63;
2412   //  float r = cul2f((l + s) ^ s);
2413   //  return s ? -r : r;
2414   //}
2415 
2416   SDLoc SL(Op);
2417   SDValue Src = Op.getOperand(0);
2418   SDValue L = Src;
2419 
2420   SDValue S;
2421   if (Signed) {
2422     const SDValue SignBit = DAG.getConstant(63, SL, MVT::i64);
2423     S = DAG.getNode(ISD::SRA, SL, MVT::i64, L, SignBit);
2424 
2425     SDValue LPlusS = DAG.getNode(ISD::ADD, SL, MVT::i64, L, S);
2426     L = DAG.getNode(ISD::XOR, SL, MVT::i64, LPlusS, S);
2427   }
2428 
2429   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2430                                    *DAG.getContext(), MVT::f32);
2431 
2432 
2433   SDValue ZeroI32 = DAG.getConstant(0, SL, MVT::i32);
2434   SDValue ZeroI64 = DAG.getConstant(0, SL, MVT::i64);
2435   SDValue LZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i64, L);
2436   LZ = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LZ);
2437 
2438   SDValue K = DAG.getConstant(127U + 63U, SL, MVT::i32);
2439   SDValue E = DAG.getSelect(SL, MVT::i32,
2440     DAG.getSetCC(SL, SetCCVT, L, ZeroI64, ISD::SETNE),
2441     DAG.getNode(ISD::SUB, SL, MVT::i32, K, LZ),
2442     ZeroI32);
2443 
2444   SDValue U = DAG.getNode(ISD::AND, SL, MVT::i64,
2445     DAG.getNode(ISD::SHL, SL, MVT::i64, L, LZ),
2446     DAG.getConstant((-1ULL) >> 1, SL, MVT::i64));
2447 
2448   SDValue T = DAG.getNode(ISD::AND, SL, MVT::i64, U,
2449                           DAG.getConstant(0xffffffffffULL, SL, MVT::i64));
2450 
2451   SDValue UShl = DAG.getNode(ISD::SRL, SL, MVT::i64,
2452                              U, DAG.getConstant(40, SL, MVT::i64));
2453 
2454   SDValue V = DAG.getNode(ISD::OR, SL, MVT::i32,
2455     DAG.getNode(ISD::SHL, SL, MVT::i32, E, DAG.getConstant(23, SL, MVT::i32)),
2456     DAG.getNode(ISD::TRUNCATE, SL, MVT::i32,  UShl));
2457 
2458   SDValue C = DAG.getConstant(0x8000000000ULL, SL, MVT::i64);
2459   SDValue RCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETUGT);
2460   SDValue TCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETEQ);
2461 
2462   SDValue One = DAG.getConstant(1, SL, MVT::i32);
2463 
2464   SDValue VTrunc1 = DAG.getNode(ISD::AND, SL, MVT::i32, V, One);
2465 
2466   SDValue R = DAG.getSelect(SL, MVT::i32,
2467     RCmp,
2468     One,
2469     DAG.getSelect(SL, MVT::i32, TCmp, VTrunc1, ZeroI32));
2470   R = DAG.getNode(ISD::ADD, SL, MVT::i32, V, R);
2471   R = DAG.getNode(ISD::BITCAST, SL, MVT::f32, R);
2472 
2473   if (!Signed)
2474     return R;
2475 
2476   SDValue RNeg = DAG.getNode(ISD::FNEG, SL, MVT::f32, R);
2477   return DAG.getSelect(SL, MVT::f32, DAG.getSExtOrTrunc(S, SL, SetCCVT), RNeg, R);
2478 }
2479 
2480 SDValue AMDGPUTargetLowering::LowerINT_TO_FP64(SDValue Op, SelectionDAG &DAG,
2481                                                bool Signed) const {
2482   SDLoc SL(Op);
2483   SDValue Src = Op.getOperand(0);
2484 
2485   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2486 
2487   SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2488                            DAG.getConstant(0, SL, MVT::i32));
2489   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC,
2490                            DAG.getConstant(1, SL, MVT::i32));
2491 
2492   SDValue CvtHi = DAG.getNode(Signed ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
2493                               SL, MVT::f64, Hi);
2494 
2495   SDValue CvtLo = DAG.getNode(ISD::UINT_TO_FP, SL, MVT::f64, Lo);
2496 
2497   SDValue LdExp = DAG.getNode(AMDGPUISD::LDEXP, SL, MVT::f64, CvtHi,
2498                               DAG.getConstant(32, SL, MVT::i32));
2499   // TODO: Should this propagate fast-math-flags?
2500   return DAG.getNode(ISD::FADD, SL, MVT::f64, LdExp, CvtLo);
2501 }
2502 
2503 SDValue AMDGPUTargetLowering::LowerUINT_TO_FP(SDValue Op,
2504                                                SelectionDAG &DAG) const {
2505   // TODO: Factor out code common with LowerSINT_TO_FP.
2506   EVT DestVT = Op.getValueType();
2507   SDValue Src = Op.getOperand(0);
2508   EVT SrcVT = Src.getValueType();
2509 
2510   if (SrcVT == MVT::i16) {
2511     if (DestVT == MVT::f16)
2512       return Op;
2513     SDLoc DL(Op);
2514 
2515     // Promote src to i32
2516     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Src);
2517     return DAG.getNode(ISD::UINT_TO_FP, DL, DestVT, Ext);
2518   }
2519 
2520   assert(SrcVT == MVT::i64 && "operation should be legal");
2521 
2522   if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2523     SDLoc DL(Op);
2524 
2525     SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2526     SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2527     SDValue FPRound =
2528         DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2529 
2530     return FPRound;
2531   }
2532 
2533   if (DestVT == MVT::f32)
2534     return LowerINT_TO_FP32(Op, DAG, false);
2535 
2536   assert(DestVT == MVT::f64);
2537   return LowerINT_TO_FP64(Op, DAG, false);
2538 }
2539 
2540 SDValue AMDGPUTargetLowering::LowerSINT_TO_FP(SDValue Op,
2541                                               SelectionDAG &DAG) const {
2542   EVT DestVT = Op.getValueType();
2543 
2544   SDValue Src = Op.getOperand(0);
2545   EVT SrcVT = Src.getValueType();
2546 
2547   if (SrcVT == MVT::i16) {
2548     if (DestVT == MVT::f16)
2549       return Op;
2550 
2551     SDLoc DL(Op);
2552     // Promote src to i32
2553     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i32, Src);
2554     return DAG.getNode(ISD::SINT_TO_FP, DL, DestVT, Ext);
2555   }
2556 
2557   assert(SrcVT == MVT::i64 && "operation should be legal");
2558 
2559   // TODO: Factor out code common with LowerUINT_TO_FP.
2560 
2561   if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2562     SDLoc DL(Op);
2563     SDValue Src = Op.getOperand(0);
2564 
2565     SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2566     SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2567     SDValue FPRound =
2568         DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2569 
2570     return FPRound;
2571   }
2572 
2573   if (DestVT == MVT::f32)
2574     return LowerINT_TO_FP32(Op, DAG, true);
2575 
2576   assert(DestVT == MVT::f64);
2577   return LowerINT_TO_FP64(Op, DAG, true);
2578 }
2579 
2580 SDValue AMDGPUTargetLowering::LowerFP64_TO_INT(SDValue Op, SelectionDAG &DAG,
2581                                                bool Signed) const {
2582   SDLoc SL(Op);
2583 
2584   SDValue Src = Op.getOperand(0);
2585 
2586   SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2587 
2588   SDValue K0 = DAG.getConstantFP(BitsToDouble(UINT64_C(0x3df0000000000000)), SL,
2589                                  MVT::f64);
2590   SDValue K1 = DAG.getConstantFP(BitsToDouble(UINT64_C(0xc1f0000000000000)), SL,
2591                                  MVT::f64);
2592   // TODO: Should this propagate fast-math-flags?
2593   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, Trunc, K0);
2594 
2595   SDValue FloorMul = DAG.getNode(ISD::FFLOOR, SL, MVT::f64, Mul);
2596 
2597 
2598   SDValue Fma = DAG.getNode(ISD::FMA, SL, MVT::f64, FloorMul, K1, Trunc);
2599 
2600   SDValue Hi = DAG.getNode(Signed ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, SL,
2601                            MVT::i32, FloorMul);
2602   SDValue Lo = DAG.getNode(ISD::FP_TO_UINT, SL, MVT::i32, Fma);
2603 
2604   SDValue Result = DAG.getBuildVector(MVT::v2i32, SL, {Lo, Hi});
2605 
2606   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Result);
2607 }
2608 
2609 SDValue AMDGPUTargetLowering::LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) const {
2610   SDLoc DL(Op);
2611   SDValue N0 = Op.getOperand(0);
2612 
2613   // Convert to target node to get known bits
2614   if (N0.getValueType() == MVT::f32)
2615     return DAG.getNode(AMDGPUISD::FP_TO_FP16, DL, Op.getValueType(), N0);
2616 
2617   if (getTargetMachine().Options.UnsafeFPMath) {
2618     // There is a generic expand for FP_TO_FP16 with unsafe fast math.
2619     return SDValue();
2620   }
2621 
2622   assert(N0.getSimpleValueType() == MVT::f64);
2623 
2624   // f64 -> f16 conversion using round-to-nearest-even rounding mode.
2625   const unsigned ExpMask = 0x7ff;
2626   const unsigned ExpBiasf64 = 1023;
2627   const unsigned ExpBiasf16 = 15;
2628   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2629   SDValue One = DAG.getConstant(1, DL, MVT::i32);
2630   SDValue U = DAG.getNode(ISD::BITCAST, DL, MVT::i64, N0);
2631   SDValue UH = DAG.getNode(ISD::SRL, DL, MVT::i64, U,
2632                            DAG.getConstant(32, DL, MVT::i64));
2633   UH = DAG.getZExtOrTrunc(UH, DL, MVT::i32);
2634   U = DAG.getZExtOrTrunc(U, DL, MVT::i32);
2635   SDValue E = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2636                           DAG.getConstant(20, DL, MVT::i64));
2637   E = DAG.getNode(ISD::AND, DL, MVT::i32, E,
2638                   DAG.getConstant(ExpMask, DL, MVT::i32));
2639   // Subtract the fp64 exponent bias (1023) to get the real exponent and
2640   // add the f16 bias (15) to get the biased exponent for the f16 format.
2641   E = DAG.getNode(ISD::ADD, DL, MVT::i32, E,
2642                   DAG.getConstant(-ExpBiasf64 + ExpBiasf16, DL, MVT::i32));
2643 
2644   SDValue M = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2645                           DAG.getConstant(8, DL, MVT::i32));
2646   M = DAG.getNode(ISD::AND, DL, MVT::i32, M,
2647                   DAG.getConstant(0xffe, DL, MVT::i32));
2648 
2649   SDValue MaskedSig = DAG.getNode(ISD::AND, DL, MVT::i32, UH,
2650                                   DAG.getConstant(0x1ff, DL, MVT::i32));
2651   MaskedSig = DAG.getNode(ISD::OR, DL, MVT::i32, MaskedSig, U);
2652 
2653   SDValue Lo40Set = DAG.getSelectCC(DL, MaskedSig, Zero, Zero, One, ISD::SETEQ);
2654   M = DAG.getNode(ISD::OR, DL, MVT::i32, M, Lo40Set);
2655 
2656   // (M != 0 ? 0x0200 : 0) | 0x7c00;
2657   SDValue I = DAG.getNode(ISD::OR, DL, MVT::i32,
2658       DAG.getSelectCC(DL, M, Zero, DAG.getConstant(0x0200, DL, MVT::i32),
2659                       Zero, ISD::SETNE), DAG.getConstant(0x7c00, DL, MVT::i32));
2660 
2661   // N = M | (E << 12);
2662   SDValue N = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2663       DAG.getNode(ISD::SHL, DL, MVT::i32, E,
2664                   DAG.getConstant(12, DL, MVT::i32)));
2665 
2666   // B = clamp(1-E, 0, 13);
2667   SDValue OneSubExp = DAG.getNode(ISD::SUB, DL, MVT::i32,
2668                                   One, E);
2669   SDValue B = DAG.getNode(ISD::SMAX, DL, MVT::i32, OneSubExp, Zero);
2670   B = DAG.getNode(ISD::SMIN, DL, MVT::i32, B,
2671                   DAG.getConstant(13, DL, MVT::i32));
2672 
2673   SDValue SigSetHigh = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2674                                    DAG.getConstant(0x1000, DL, MVT::i32));
2675 
2676   SDValue D = DAG.getNode(ISD::SRL, DL, MVT::i32, SigSetHigh, B);
2677   SDValue D0 = DAG.getNode(ISD::SHL, DL, MVT::i32, D, B);
2678   SDValue D1 = DAG.getSelectCC(DL, D0, SigSetHigh, One, Zero, ISD::SETNE);
2679   D = DAG.getNode(ISD::OR, DL, MVT::i32, D, D1);
2680 
2681   SDValue V = DAG.getSelectCC(DL, E, One, D, N, ISD::SETLT);
2682   SDValue VLow3 = DAG.getNode(ISD::AND, DL, MVT::i32, V,
2683                               DAG.getConstant(0x7, DL, MVT::i32));
2684   V = DAG.getNode(ISD::SRL, DL, MVT::i32, V,
2685                   DAG.getConstant(2, DL, MVT::i32));
2686   SDValue V0 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(3, DL, MVT::i32),
2687                                One, Zero, ISD::SETEQ);
2688   SDValue V1 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(5, DL, MVT::i32),
2689                                One, Zero, ISD::SETGT);
2690   V1 = DAG.getNode(ISD::OR, DL, MVT::i32, V0, V1);
2691   V = DAG.getNode(ISD::ADD, DL, MVT::i32, V, V1);
2692 
2693   V = DAG.getSelectCC(DL, E, DAG.getConstant(30, DL, MVT::i32),
2694                       DAG.getConstant(0x7c00, DL, MVT::i32), V, ISD::SETGT);
2695   V = DAG.getSelectCC(DL, E, DAG.getConstant(1039, DL, MVT::i32),
2696                       I, V, ISD::SETEQ);
2697 
2698   // Extract the sign bit.
2699   SDValue Sign = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2700                             DAG.getConstant(16, DL, MVT::i32));
2701   Sign = DAG.getNode(ISD::AND, DL, MVT::i32, Sign,
2702                      DAG.getConstant(0x8000, DL, MVT::i32));
2703 
2704   V = DAG.getNode(ISD::OR, DL, MVT::i32, Sign, V);
2705   return DAG.getZExtOrTrunc(V, DL, Op.getValueType());
2706 }
2707 
2708 SDValue AMDGPUTargetLowering::LowerFP_TO_SINT(SDValue Op,
2709                                               SelectionDAG &DAG) const {
2710   SDValue Src = Op.getOperand(0);
2711 
2712   // TODO: Factor out code common with LowerFP_TO_UINT.
2713 
2714   EVT SrcVT = Src.getValueType();
2715   if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2716     SDLoc DL(Op);
2717 
2718     SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2719     SDValue FpToInt32 =
2720         DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2721 
2722     return FpToInt32;
2723   }
2724 
2725   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2726     return LowerFP64_TO_INT(Op, DAG, true);
2727 
2728   return SDValue();
2729 }
2730 
2731 SDValue AMDGPUTargetLowering::LowerFP_TO_UINT(SDValue Op,
2732                                               SelectionDAG &DAG) const {
2733   SDValue Src = Op.getOperand(0);
2734 
2735   // TODO: Factor out code common with LowerFP_TO_SINT.
2736 
2737   EVT SrcVT = Src.getValueType();
2738   if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2739     SDLoc DL(Op);
2740 
2741     SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2742     SDValue FpToInt32 =
2743         DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2744 
2745     return FpToInt32;
2746   }
2747 
2748   if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2749     return LowerFP64_TO_INT(Op, DAG, false);
2750 
2751   return SDValue();
2752 }
2753 
2754 SDValue AMDGPUTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
2755                                                      SelectionDAG &DAG) const {
2756   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2757   MVT VT = Op.getSimpleValueType();
2758   MVT ScalarVT = VT.getScalarType();
2759 
2760   assert(VT.isVector());
2761 
2762   SDValue Src = Op.getOperand(0);
2763   SDLoc DL(Op);
2764 
2765   // TODO: Don't scalarize on Evergreen?
2766   unsigned NElts = VT.getVectorNumElements();
2767   SmallVector<SDValue, 8> Args;
2768   DAG.ExtractVectorElements(Src, Args, 0, NElts);
2769 
2770   SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
2771   for (unsigned I = 0; I < NElts; ++I)
2772     Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
2773 
2774   return DAG.getBuildVector(VT, DL, Args);
2775 }
2776 
2777 //===----------------------------------------------------------------------===//
2778 // Custom DAG optimizations
2779 //===----------------------------------------------------------------------===//
2780 
2781 static bool isU24(SDValue Op, SelectionDAG &DAG) {
2782   return AMDGPUTargetLowering::numBitsUnsigned(Op, DAG) <= 24;
2783 }
2784 
2785 static bool isI24(SDValue Op, SelectionDAG &DAG) {
2786   EVT VT = Op.getValueType();
2787   return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
2788                                      // as unsigned 24-bit values.
2789     AMDGPUTargetLowering::numBitsSigned(Op, DAG) < 24;
2790 }
2791 
2792 static SDValue simplifyI24(SDNode *Node24,
2793                            TargetLowering::DAGCombinerInfo &DCI) {
2794   SelectionDAG &DAG = DCI.DAG;
2795   bool IsIntrin = Node24->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
2796 
2797   SDValue LHS = IsIntrin ? Node24->getOperand(1) : Node24->getOperand(0);
2798   SDValue RHS = IsIntrin ? Node24->getOperand(2) : Node24->getOperand(1);
2799   unsigned NewOpcode = Node24->getOpcode();
2800   if (IsIntrin) {
2801     unsigned IID = cast<ConstantSDNode>(Node24->getOperand(0))->getZExtValue();
2802     NewOpcode = IID == Intrinsic::amdgcn_mul_i24 ?
2803       AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
2804   }
2805 
2806   APInt Demanded = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 24);
2807 
2808   // First try to simplify using GetDemandedBits which allows the operands to
2809   // have other uses, but will only perform simplifications that involve
2810   // bypassing some nodes for this user.
2811   SDValue DemandedLHS = DAG.GetDemandedBits(LHS, Demanded);
2812   SDValue DemandedRHS = DAG.GetDemandedBits(RHS, Demanded);
2813   if (DemandedLHS || DemandedRHS)
2814     return DAG.getNode(NewOpcode, SDLoc(Node24), Node24->getVTList(),
2815                        DemandedLHS ? DemandedLHS : LHS,
2816                        DemandedRHS ? DemandedRHS : RHS);
2817 
2818   // Now try SimplifyDemandedBits which can simplify the nodes used by our
2819   // operands if this node is the only user.
2820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2821   if (TLI.SimplifyDemandedBits(LHS, Demanded, DCI))
2822     return SDValue(Node24, 0);
2823   if (TLI.SimplifyDemandedBits(RHS, Demanded, DCI))
2824     return SDValue(Node24, 0);
2825 
2826   return SDValue();
2827 }
2828 
2829 template <typename IntTy>
2830 static SDValue constantFoldBFE(SelectionDAG &DAG, IntTy Src0, uint32_t Offset,
2831                                uint32_t Width, const SDLoc &DL) {
2832   if (Width + Offset < 32) {
2833     uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
2834     IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
2835     return DAG.getConstant(Result, DL, MVT::i32);
2836   }
2837 
2838   return DAG.getConstant(Src0 >> Offset, DL, MVT::i32);
2839 }
2840 
2841 static bool hasVolatileUser(SDNode *Val) {
2842   for (SDNode *U : Val->uses()) {
2843     if (MemSDNode *M = dyn_cast<MemSDNode>(U)) {
2844       if (M->isVolatile())
2845         return true;
2846     }
2847   }
2848 
2849   return false;
2850 }
2851 
2852 bool AMDGPUTargetLowering::shouldCombineMemoryType(EVT VT) const {
2853   // i32 vectors are the canonical memory type.
2854   if (VT.getScalarType() == MVT::i32 || isTypeLegal(VT))
2855     return false;
2856 
2857   if (!VT.isByteSized())
2858     return false;
2859 
2860   unsigned Size = VT.getStoreSize();
2861 
2862   if ((Size == 1 || Size == 2 || Size == 4) && !VT.isVector())
2863     return false;
2864 
2865   if (Size == 3 || (Size > 4 && (Size % 4 != 0)))
2866     return false;
2867 
2868   return true;
2869 }
2870 
2871 // Replace load of an illegal type with a store of a bitcast to a friendlier
2872 // type.
2873 SDValue AMDGPUTargetLowering::performLoadCombine(SDNode *N,
2874                                                  DAGCombinerInfo &DCI) const {
2875   if (!DCI.isBeforeLegalize())
2876     return SDValue();
2877 
2878   LoadSDNode *LN = cast<LoadSDNode>(N);
2879   if (LN->isVolatile() || !ISD::isNormalLoad(LN) || hasVolatileUser(LN))
2880     return SDValue();
2881 
2882   SDLoc SL(N);
2883   SelectionDAG &DAG = DCI.DAG;
2884   EVT VT = LN->getMemoryVT();
2885 
2886   unsigned Size = VT.getStoreSize();
2887   unsigned Align = LN->getAlignment();
2888   if (Align < Size && isTypeLegal(VT)) {
2889     bool IsFast;
2890     unsigned AS = LN->getAddressSpace();
2891 
2892     // Expand unaligned loads earlier than legalization. Due to visitation order
2893     // problems during legalization, the emitted instructions to pack and unpack
2894     // the bytes again are not eliminated in the case of an unaligned copy.
2895     if (!allowsMisalignedMemoryAccesses(
2896             VT, AS, Align, LN->getMemOperand()->getFlags(), &IsFast)) {
2897       SDValue Ops[2];
2898 
2899       if (VT.isVector())
2900         std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(LN, DAG);
2901       else
2902         std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(LN, DAG);
2903 
2904       return DAG.getMergeValues(Ops, SDLoc(N));
2905     }
2906 
2907     if (!IsFast)
2908       return SDValue();
2909   }
2910 
2911   if (!shouldCombineMemoryType(VT))
2912     return SDValue();
2913 
2914   EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2915 
2916   SDValue NewLoad
2917     = DAG.getLoad(NewVT, SL, LN->getChain(),
2918                   LN->getBasePtr(), LN->getMemOperand());
2919 
2920   SDValue BC = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad);
2921   DCI.CombineTo(N, BC, NewLoad.getValue(1));
2922   return SDValue(N, 0);
2923 }
2924 
2925 // Replace store of an illegal type with a store of a bitcast to a friendlier
2926 // type.
2927 SDValue AMDGPUTargetLowering::performStoreCombine(SDNode *N,
2928                                                   DAGCombinerInfo &DCI) const {
2929   if (!DCI.isBeforeLegalize())
2930     return SDValue();
2931 
2932   StoreSDNode *SN = cast<StoreSDNode>(N);
2933   if (SN->isVolatile() || !ISD::isNormalStore(SN))
2934     return SDValue();
2935 
2936   EVT VT = SN->getMemoryVT();
2937   unsigned Size = VT.getStoreSize();
2938 
2939   SDLoc SL(N);
2940   SelectionDAG &DAG = DCI.DAG;
2941   unsigned Align = SN->getAlignment();
2942   if (Align < Size && isTypeLegal(VT)) {
2943     bool IsFast;
2944     unsigned AS = SN->getAddressSpace();
2945 
2946     // Expand unaligned stores earlier than legalization. Due to visitation
2947     // order problems during legalization, the emitted instructions to pack and
2948     // unpack the bytes again are not eliminated in the case of an unaligned
2949     // copy.
2950     if (!allowsMisalignedMemoryAccesses(
2951             VT, AS, Align, SN->getMemOperand()->getFlags(), &IsFast)) {
2952       if (VT.isVector())
2953         return scalarizeVectorStore(SN, DAG);
2954 
2955       return expandUnalignedStore(SN, DAG);
2956     }
2957 
2958     if (!IsFast)
2959       return SDValue();
2960   }
2961 
2962   if (!shouldCombineMemoryType(VT))
2963     return SDValue();
2964 
2965   EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2966   SDValue Val = SN->getValue();
2967 
2968   //DCI.AddToWorklist(Val.getNode());
2969 
2970   bool OtherUses = !Val.hasOneUse();
2971   SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NewVT, Val);
2972   if (OtherUses) {
2973     SDValue CastBack = DAG.getNode(ISD::BITCAST, SL, VT, CastVal);
2974     DAG.ReplaceAllUsesOfValueWith(Val, CastBack);
2975   }
2976 
2977   return DAG.getStore(SN->getChain(), SL, CastVal,
2978                       SN->getBasePtr(), SN->getMemOperand());
2979 }
2980 
2981 // FIXME: This should go in generic DAG combiner with an isTruncateFree check,
2982 // but isTruncateFree is inaccurate for i16 now because of SALU vs. VALU
2983 // issues.
2984 SDValue AMDGPUTargetLowering::performAssertSZExtCombine(SDNode *N,
2985                                                         DAGCombinerInfo &DCI) const {
2986   SelectionDAG &DAG = DCI.DAG;
2987   SDValue N0 = N->getOperand(0);
2988 
2989   // (vt2 (assertzext (truncate vt0:x), vt1)) ->
2990   //     (vt2 (truncate (assertzext vt0:x, vt1)))
2991   if (N0.getOpcode() == ISD::TRUNCATE) {
2992     SDValue N1 = N->getOperand(1);
2993     EVT ExtVT = cast<VTSDNode>(N1)->getVT();
2994     SDLoc SL(N);
2995 
2996     SDValue Src = N0.getOperand(0);
2997     EVT SrcVT = Src.getValueType();
2998     if (SrcVT.bitsGE(ExtVT)) {
2999       SDValue NewInReg = DAG.getNode(N->getOpcode(), SL, SrcVT, Src, N1);
3000       return DAG.getNode(ISD::TRUNCATE, SL, N->getValueType(0), NewInReg);
3001     }
3002   }
3003 
3004   return SDValue();
3005 }
3006 
3007 SDValue AMDGPUTargetLowering::performIntrinsicWOChainCombine(
3008   SDNode *N, DAGCombinerInfo &DCI) const {
3009   unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3010   switch (IID) {
3011   case Intrinsic::amdgcn_mul_i24:
3012   case Intrinsic::amdgcn_mul_u24:
3013     return simplifyI24(N, DCI);
3014   default:
3015     return SDValue();
3016   }
3017 }
3018 
3019 /// Split the 64-bit value \p LHS into two 32-bit components, and perform the
3020 /// binary operation \p Opc to it with the corresponding constant operands.
3021 SDValue AMDGPUTargetLowering::splitBinaryBitConstantOpImpl(
3022   DAGCombinerInfo &DCI, const SDLoc &SL,
3023   unsigned Opc, SDValue LHS,
3024   uint32_t ValLo, uint32_t ValHi) const {
3025   SelectionDAG &DAG = DCI.DAG;
3026   SDValue Lo, Hi;
3027   std::tie(Lo, Hi) = split64BitValue(LHS, DAG);
3028 
3029   SDValue LoRHS = DAG.getConstant(ValLo, SL, MVT::i32);
3030   SDValue HiRHS = DAG.getConstant(ValHi, SL, MVT::i32);
3031 
3032   SDValue LoAnd = DAG.getNode(Opc, SL, MVT::i32, Lo, LoRHS);
3033   SDValue HiAnd = DAG.getNode(Opc, SL, MVT::i32, Hi, HiRHS);
3034 
3035   // Re-visit the ands. It's possible we eliminated one of them and it could
3036   // simplify the vector.
3037   DCI.AddToWorklist(Lo.getNode());
3038   DCI.AddToWorklist(Hi.getNode());
3039 
3040   SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {LoAnd, HiAnd});
3041   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3042 }
3043 
3044 SDValue AMDGPUTargetLowering::performShlCombine(SDNode *N,
3045                                                 DAGCombinerInfo &DCI) const {
3046   EVT VT = N->getValueType(0);
3047 
3048   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3049   if (!RHS)
3050     return SDValue();
3051 
3052   SDValue LHS = N->getOperand(0);
3053   unsigned RHSVal = RHS->getZExtValue();
3054   if (!RHSVal)
3055     return LHS;
3056 
3057   SDLoc SL(N);
3058   SelectionDAG &DAG = DCI.DAG;
3059 
3060   switch (LHS->getOpcode()) {
3061   default:
3062     break;
3063   case ISD::ZERO_EXTEND:
3064   case ISD::SIGN_EXTEND:
3065   case ISD::ANY_EXTEND: {
3066     SDValue X = LHS->getOperand(0);
3067 
3068     if (VT == MVT::i32 && RHSVal == 16 && X.getValueType() == MVT::i16 &&
3069         isOperationLegal(ISD::BUILD_VECTOR, MVT::v2i16)) {
3070       // Prefer build_vector as the canonical form if packed types are legal.
3071       // (shl ([asz]ext i16:x), 16 -> build_vector 0, x
3072       SDValue Vec = DAG.getBuildVector(MVT::v2i16, SL,
3073        { DAG.getConstant(0, SL, MVT::i16), LHS->getOperand(0) });
3074       return DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3075     }
3076 
3077     // shl (ext x) => zext (shl x), if shift does not overflow int
3078     if (VT != MVT::i64)
3079       break;
3080     KnownBits Known = DAG.computeKnownBits(X);
3081     unsigned LZ = Known.countMinLeadingZeros();
3082     if (LZ < RHSVal)
3083       break;
3084     EVT XVT = X.getValueType();
3085     SDValue Shl = DAG.getNode(ISD::SHL, SL, XVT, X, SDValue(RHS, 0));
3086     return DAG.getZExtOrTrunc(Shl, SL, VT);
3087   }
3088   }
3089 
3090   if (VT != MVT::i64)
3091     return SDValue();
3092 
3093   // i64 (shl x, C) -> (build_pair 0, (shl x, C -32))
3094 
3095   // On some subtargets, 64-bit shift is a quarter rate instruction. In the
3096   // common case, splitting this into a move and a 32-bit shift is faster and
3097   // the same code size.
3098   if (RHSVal < 32)
3099     return SDValue();
3100 
3101   SDValue ShiftAmt = DAG.getConstant(RHSVal - 32, SL, MVT::i32);
3102 
3103   SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
3104   SDValue NewShift = DAG.getNode(ISD::SHL, SL, MVT::i32, Lo, ShiftAmt);
3105 
3106   const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
3107 
3108   SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {Zero, NewShift});
3109   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3110 }
3111 
3112 SDValue AMDGPUTargetLowering::performSraCombine(SDNode *N,
3113                                                 DAGCombinerInfo &DCI) const {
3114   if (N->getValueType(0) != MVT::i64)
3115     return SDValue();
3116 
3117   const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3118   if (!RHS)
3119     return SDValue();
3120 
3121   SelectionDAG &DAG = DCI.DAG;
3122   SDLoc SL(N);
3123   unsigned RHSVal = RHS->getZExtValue();
3124 
3125   // (sra i64:x, 32) -> build_pair x, (sra hi_32(x), 31)
3126   if (RHSVal == 32) {
3127     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
3128     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
3129                                    DAG.getConstant(31, SL, MVT::i32));
3130 
3131     SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {Hi, NewShift});
3132     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
3133   }
3134 
3135   // (sra i64:x, 63) -> build_pair (sra hi_32(x), 31), (sra hi_32(x), 31)
3136   if (RHSVal == 63) {
3137     SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
3138     SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
3139                                    DAG.getConstant(31, SL, MVT::i32));
3140     SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, NewShift});
3141     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
3142   }
3143 
3144   return SDValue();
3145 }
3146 
3147 SDValue AMDGPUTargetLowering::performSrlCombine(SDNode *N,
3148                                                 DAGCombinerInfo &DCI) const {
3149   auto *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3150   if (!RHS)
3151     return SDValue();
3152 
3153   EVT VT = N->getValueType(0);
3154   SDValue LHS = N->getOperand(0);
3155   unsigned ShiftAmt = RHS->getZExtValue();
3156   SelectionDAG &DAG = DCI.DAG;
3157   SDLoc SL(N);
3158 
3159   // fold (srl (and x, c1 << c2), c2) -> (and (srl(x, c2), c1)
3160   // this improves the ability to match BFE patterns in isel.
3161   if (LHS.getOpcode() == ISD::AND) {
3162     if (auto *Mask = dyn_cast<ConstantSDNode>(LHS.getOperand(1))) {
3163       if (Mask->getAPIntValue().isShiftedMask() &&
3164           Mask->getAPIntValue().countTrailingZeros() == ShiftAmt) {
3165         return DAG.getNode(
3166             ISD::AND, SL, VT,
3167             DAG.getNode(ISD::SRL, SL, VT, LHS.getOperand(0), N->getOperand(1)),
3168             DAG.getNode(ISD::SRL, SL, VT, LHS.getOperand(1), N->getOperand(1)));
3169       }
3170     }
3171   }
3172 
3173   if (VT != MVT::i64)
3174     return SDValue();
3175 
3176   if (ShiftAmt < 32)
3177     return SDValue();
3178 
3179   // srl i64:x, C for C >= 32
3180   // =>
3181   //   build_pair (srl hi_32(x), C - 32), 0
3182   SDValue One = DAG.getConstant(1, SL, MVT::i32);
3183   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
3184 
3185   SDValue VecOp = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, LHS);
3186   SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecOp, One);
3187 
3188   SDValue NewConst = DAG.getConstant(ShiftAmt - 32, SL, MVT::i32);
3189   SDValue NewShift = DAG.getNode(ISD::SRL, SL, MVT::i32, Hi, NewConst);
3190 
3191   SDValue BuildPair = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, Zero});
3192 
3193   return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildPair);
3194 }
3195 
3196 SDValue AMDGPUTargetLowering::performTruncateCombine(
3197   SDNode *N, DAGCombinerInfo &DCI) const {
3198   SDLoc SL(N);
3199   SelectionDAG &DAG = DCI.DAG;
3200   EVT VT = N->getValueType(0);
3201   SDValue Src = N->getOperand(0);
3202 
3203   // vt1 (truncate (bitcast (build_vector vt0:x, ...))) -> vt1 (bitcast vt0:x)
3204   if (Src.getOpcode() == ISD::BITCAST && !VT.isVector()) {
3205     SDValue Vec = Src.getOperand(0);
3206     if (Vec.getOpcode() == ISD::BUILD_VECTOR) {
3207       SDValue Elt0 = Vec.getOperand(0);
3208       EVT EltVT = Elt0.getValueType();
3209       if (VT.getSizeInBits() <= EltVT.getSizeInBits()) {
3210         if (EltVT.isFloatingPoint()) {
3211           Elt0 = DAG.getNode(ISD::BITCAST, SL,
3212                              EltVT.changeTypeToInteger(), Elt0);
3213         }
3214 
3215         return DAG.getNode(ISD::TRUNCATE, SL, VT, Elt0);
3216       }
3217     }
3218   }
3219 
3220   // Equivalent of above for accessing the high element of a vector as an
3221   // integer operation.
3222   // trunc (srl (bitcast (build_vector x, y))), 16 -> trunc (bitcast y)
3223   if (Src.getOpcode() == ISD::SRL && !VT.isVector()) {
3224     if (auto K = isConstOrConstSplat(Src.getOperand(1))) {
3225       if (2 * K->getZExtValue() == Src.getValueType().getScalarSizeInBits()) {
3226         SDValue BV = stripBitcast(Src.getOperand(0));
3227         if (BV.getOpcode() == ISD::BUILD_VECTOR &&
3228             BV.getValueType().getVectorNumElements() == 2) {
3229           SDValue SrcElt = BV.getOperand(1);
3230           EVT SrcEltVT = SrcElt.getValueType();
3231           if (SrcEltVT.isFloatingPoint()) {
3232             SrcElt = DAG.getNode(ISD::BITCAST, SL,
3233                                  SrcEltVT.changeTypeToInteger(), SrcElt);
3234           }
3235 
3236           return DAG.getNode(ISD::TRUNCATE, SL, VT, SrcElt);
3237         }
3238       }
3239     }
3240   }
3241 
3242   // Partially shrink 64-bit shifts to 32-bit if reduced to 16-bit.
3243   //
3244   // i16 (trunc (srl i64:x, K)), K <= 16 ->
3245   //     i16 (trunc (srl (i32 (trunc x), K)))
3246   if (VT.getScalarSizeInBits() < 32) {
3247     EVT SrcVT = Src.getValueType();
3248     if (SrcVT.getScalarSizeInBits() > 32 &&
3249         (Src.getOpcode() == ISD::SRL ||
3250          Src.getOpcode() == ISD::SRA ||
3251          Src.getOpcode() == ISD::SHL)) {
3252       SDValue Amt = Src.getOperand(1);
3253       KnownBits Known = DAG.computeKnownBits(Amt);
3254       unsigned Size = VT.getScalarSizeInBits();
3255       if ((Known.isConstant() && Known.getConstant().ule(Size)) ||
3256           (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size))) {
3257         EVT MidVT = VT.isVector() ?
3258           EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3259                            VT.getVectorNumElements()) : MVT::i32;
3260 
3261         EVT NewShiftVT = getShiftAmountTy(MidVT, DAG.getDataLayout());
3262         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MidVT,
3263                                     Src.getOperand(0));
3264         DCI.AddToWorklist(Trunc.getNode());
3265 
3266         if (Amt.getValueType() != NewShiftVT) {
3267           Amt = DAG.getZExtOrTrunc(Amt, SL, NewShiftVT);
3268           DCI.AddToWorklist(Amt.getNode());
3269         }
3270 
3271         SDValue ShrunkShift = DAG.getNode(Src.getOpcode(), SL, MidVT,
3272                                           Trunc, Amt);
3273         return DAG.getNode(ISD::TRUNCATE, SL, VT, ShrunkShift);
3274       }
3275     }
3276   }
3277 
3278   return SDValue();
3279 }
3280 
3281 // We need to specifically handle i64 mul here to avoid unnecessary conversion
3282 // instructions. If we only match on the legalized i64 mul expansion,
3283 // SimplifyDemandedBits will be unable to remove them because there will be
3284 // multiple uses due to the separate mul + mulh[su].
3285 static SDValue getMul24(SelectionDAG &DAG, const SDLoc &SL,
3286                         SDValue N0, SDValue N1, unsigned Size, bool Signed) {
3287   if (Size <= 32) {
3288     unsigned MulOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3289     return DAG.getNode(MulOpc, SL, MVT::i32, N0, N1);
3290   }
3291 
3292   // Because we want to eliminate extension instructions before the
3293   // operation, we need to create a single user here (i.e. not the separate
3294   // mul_lo + mul_hi) so that SimplifyDemandedBits will deal with it.
3295 
3296   unsigned MulOpc = Signed ? AMDGPUISD::MUL_LOHI_I24 : AMDGPUISD::MUL_LOHI_U24;
3297 
3298   SDValue Mul = DAG.getNode(MulOpc, SL,
3299                             DAG.getVTList(MVT::i32, MVT::i32), N0, N1);
3300 
3301   return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64,
3302                      Mul.getValue(0), Mul.getValue(1));
3303 }
3304 
3305 SDValue AMDGPUTargetLowering::performMulCombine(SDNode *N,
3306                                                 DAGCombinerInfo &DCI) const {
3307   EVT VT = N->getValueType(0);
3308 
3309   unsigned Size = VT.getSizeInBits();
3310   if (VT.isVector() || Size > 64)
3311     return SDValue();
3312 
3313   // There are i16 integer mul/mad.
3314   if (Subtarget->has16BitInsts() && VT.getScalarType().bitsLE(MVT::i16))
3315     return SDValue();
3316 
3317   SelectionDAG &DAG = DCI.DAG;
3318   SDLoc DL(N);
3319 
3320   SDValue N0 = N->getOperand(0);
3321   SDValue N1 = N->getOperand(1);
3322 
3323   // SimplifyDemandedBits has the annoying habit of turning useful zero_extends
3324   // in the source into any_extends if the result of the mul is truncated. Since
3325   // we can assume the high bits are whatever we want, use the underlying value
3326   // to avoid the unknown high bits from interfering.
3327   if (N0.getOpcode() == ISD::ANY_EXTEND)
3328     N0 = N0.getOperand(0);
3329 
3330   if (N1.getOpcode() == ISD::ANY_EXTEND)
3331     N1 = N1.getOperand(0);
3332 
3333   SDValue Mul;
3334 
3335   if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
3336     N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3337     N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3338     Mul = getMul24(DAG, DL, N0, N1, Size, false);
3339   } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
3340     N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3341     N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3342     Mul = getMul24(DAG, DL, N0, N1, Size, true);
3343   } else {
3344     return SDValue();
3345   }
3346 
3347   // We need to use sext even for MUL_U24, because MUL_U24 is used
3348   // for signed multiply of 8 and 16-bit types.
3349   return DAG.getSExtOrTrunc(Mul, DL, VT);
3350 }
3351 
3352 SDValue AMDGPUTargetLowering::performMulhsCombine(SDNode *N,
3353                                                   DAGCombinerInfo &DCI) const {
3354   EVT VT = N->getValueType(0);
3355 
3356   if (!Subtarget->hasMulI24() || VT.isVector())
3357     return SDValue();
3358 
3359   SelectionDAG &DAG = DCI.DAG;
3360   SDLoc DL(N);
3361 
3362   SDValue N0 = N->getOperand(0);
3363   SDValue N1 = N->getOperand(1);
3364 
3365   if (!isI24(N0, DAG) || !isI24(N1, DAG))
3366     return SDValue();
3367 
3368   N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3369   N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3370 
3371   SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_I24, DL, MVT::i32, N0, N1);
3372   DCI.AddToWorklist(Mulhi.getNode());
3373   return DAG.getSExtOrTrunc(Mulhi, DL, VT);
3374 }
3375 
3376 SDValue AMDGPUTargetLowering::performMulhuCombine(SDNode *N,
3377                                                   DAGCombinerInfo &DCI) const {
3378   EVT VT = N->getValueType(0);
3379 
3380   if (!Subtarget->hasMulU24() || VT.isVector() || VT.getSizeInBits() > 32)
3381     return SDValue();
3382 
3383   SelectionDAG &DAG = DCI.DAG;
3384   SDLoc DL(N);
3385 
3386   SDValue N0 = N->getOperand(0);
3387   SDValue N1 = N->getOperand(1);
3388 
3389   if (!isU24(N0, DAG) || !isU24(N1, DAG))
3390     return SDValue();
3391 
3392   N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3393   N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3394 
3395   SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_U24, DL, MVT::i32, N0, N1);
3396   DCI.AddToWorklist(Mulhi.getNode());
3397   return DAG.getZExtOrTrunc(Mulhi, DL, VT);
3398 }
3399 
3400 SDValue AMDGPUTargetLowering::performMulLoHi24Combine(
3401   SDNode *N, DAGCombinerInfo &DCI) const {
3402   SelectionDAG &DAG = DCI.DAG;
3403 
3404   // Simplify demanded bits before splitting into multiple users.
3405   if (SDValue V = simplifyI24(N, DCI))
3406     return V;
3407 
3408   SDValue N0 = N->getOperand(0);
3409   SDValue N1 = N->getOperand(1);
3410 
3411   bool Signed = (N->getOpcode() == AMDGPUISD::MUL_LOHI_I24);
3412 
3413   unsigned MulLoOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3414   unsigned MulHiOpc = Signed ? AMDGPUISD::MULHI_I24 : AMDGPUISD::MULHI_U24;
3415 
3416   SDLoc SL(N);
3417 
3418   SDValue MulLo = DAG.getNode(MulLoOpc, SL, MVT::i32, N0, N1);
3419   SDValue MulHi = DAG.getNode(MulHiOpc, SL, MVT::i32, N0, N1);
3420   return DAG.getMergeValues({ MulLo, MulHi }, SL);
3421 }
3422 
3423 static bool isNegativeOne(SDValue Val) {
3424   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val))
3425     return C->isAllOnesValue();
3426   return false;
3427 }
3428 
3429 SDValue AMDGPUTargetLowering::getFFBX_U32(SelectionDAG &DAG,
3430                                           SDValue Op,
3431                                           const SDLoc &DL,
3432                                           unsigned Opc) const {
3433   EVT VT = Op.getValueType();
3434   EVT LegalVT = getTypeToTransformTo(*DAG.getContext(), VT);
3435   if (LegalVT != MVT::i32 && (Subtarget->has16BitInsts() &&
3436                               LegalVT != MVT::i16))
3437     return SDValue();
3438 
3439   if (VT != MVT::i32)
3440     Op = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Op);
3441 
3442   SDValue FFBX = DAG.getNode(Opc, DL, MVT::i32, Op);
3443   if (VT != MVT::i32)
3444     FFBX = DAG.getNode(ISD::TRUNCATE, DL, VT, FFBX);
3445 
3446   return FFBX;
3447 }
3448 
3449 // The native instructions return -1 on 0 input. Optimize out a select that
3450 // produces -1 on 0.
3451 //
3452 // TODO: If zero is not undef, we could also do this if the output is compared
3453 // against the bitwidth.
3454 //
3455 // TODO: Should probably combine against FFBH_U32 instead of ctlz directly.
3456 SDValue AMDGPUTargetLowering::performCtlz_CttzCombine(const SDLoc &SL, SDValue Cond,
3457                                                  SDValue LHS, SDValue RHS,
3458                                                  DAGCombinerInfo &DCI) const {
3459   ConstantSDNode *CmpRhs = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3460   if (!CmpRhs || !CmpRhs->isNullValue())
3461     return SDValue();
3462 
3463   SelectionDAG &DAG = DCI.DAG;
3464   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
3465   SDValue CmpLHS = Cond.getOperand(0);
3466 
3467   unsigned Opc = isCttzOpc(RHS.getOpcode()) ? AMDGPUISD::FFBL_B32 :
3468                                            AMDGPUISD::FFBH_U32;
3469 
3470   // select (setcc x, 0, eq), -1, (ctlz_zero_undef x) -> ffbh_u32 x
3471   // select (setcc x, 0, eq), -1, (cttz_zero_undef x) -> ffbl_u32 x
3472   if (CCOpcode == ISD::SETEQ &&
3473       (isCtlzOpc(RHS.getOpcode()) || isCttzOpc(RHS.getOpcode())) &&
3474       RHS.getOperand(0) == CmpLHS &&
3475       isNegativeOne(LHS)) {
3476     return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3477   }
3478 
3479   // select (setcc x, 0, ne), (ctlz_zero_undef x), -1 -> ffbh_u32 x
3480   // select (setcc x, 0, ne), (cttz_zero_undef x), -1 -> ffbl_u32 x
3481   if (CCOpcode == ISD::SETNE &&
3482       (isCtlzOpc(LHS.getOpcode()) || isCttzOpc(RHS.getOpcode())) &&
3483       LHS.getOperand(0) == CmpLHS &&
3484       isNegativeOne(RHS)) {
3485     return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3486   }
3487 
3488   return SDValue();
3489 }
3490 
3491 static SDValue distributeOpThroughSelect(TargetLowering::DAGCombinerInfo &DCI,
3492                                          unsigned Op,
3493                                          const SDLoc &SL,
3494                                          SDValue Cond,
3495                                          SDValue N1,
3496                                          SDValue N2) {
3497   SelectionDAG &DAG = DCI.DAG;
3498   EVT VT = N1.getValueType();
3499 
3500   SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT, Cond,
3501                                   N1.getOperand(0), N2.getOperand(0));
3502   DCI.AddToWorklist(NewSelect.getNode());
3503   return DAG.getNode(Op, SL, VT, NewSelect);
3504 }
3505 
3506 // Pull a free FP operation out of a select so it may fold into uses.
3507 //
3508 // select c, (fneg x), (fneg y) -> fneg (select c, x, y)
3509 // select c, (fneg x), k -> fneg (select c, x, (fneg k))
3510 //
3511 // select c, (fabs x), (fabs y) -> fabs (select c, x, y)
3512 // select c, (fabs x), +k -> fabs (select c, x, k)
3513 static SDValue foldFreeOpFromSelect(TargetLowering::DAGCombinerInfo &DCI,
3514                                     SDValue N) {
3515   SelectionDAG &DAG = DCI.DAG;
3516   SDValue Cond = N.getOperand(0);
3517   SDValue LHS = N.getOperand(1);
3518   SDValue RHS = N.getOperand(2);
3519 
3520   EVT VT = N.getValueType();
3521   if ((LHS.getOpcode() == ISD::FABS && RHS.getOpcode() == ISD::FABS) ||
3522       (LHS.getOpcode() == ISD::FNEG && RHS.getOpcode() == ISD::FNEG)) {
3523     return distributeOpThroughSelect(DCI, LHS.getOpcode(),
3524                                      SDLoc(N), Cond, LHS, RHS);
3525   }
3526 
3527   bool Inv = false;
3528   if (RHS.getOpcode() == ISD::FABS || RHS.getOpcode() == ISD::FNEG) {
3529     std::swap(LHS, RHS);
3530     Inv = true;
3531   }
3532 
3533   // TODO: Support vector constants.
3534   ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
3535   if ((LHS.getOpcode() == ISD::FNEG || LHS.getOpcode() == ISD::FABS) && CRHS) {
3536     SDLoc SL(N);
3537     // If one side is an fneg/fabs and the other is a constant, we can push the
3538     // fneg/fabs down. If it's an fabs, the constant needs to be non-negative.
3539     SDValue NewLHS = LHS.getOperand(0);
3540     SDValue NewRHS = RHS;
3541 
3542     // Careful: if the neg can be folded up, don't try to pull it back down.
3543     bool ShouldFoldNeg = true;
3544 
3545     if (NewLHS.hasOneUse()) {
3546       unsigned Opc = NewLHS.getOpcode();
3547       if (LHS.getOpcode() == ISD::FNEG && fnegFoldsIntoOp(Opc))
3548         ShouldFoldNeg = false;
3549       if (LHS.getOpcode() == ISD::FABS && Opc == ISD::FMUL)
3550         ShouldFoldNeg = false;
3551     }
3552 
3553     if (ShouldFoldNeg) {
3554       if (LHS.getOpcode() == ISD::FNEG)
3555         NewRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3556       else if (CRHS->isNegative())
3557         return SDValue();
3558 
3559       if (Inv)
3560         std::swap(NewLHS, NewRHS);
3561 
3562       SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT,
3563                                       Cond, NewLHS, NewRHS);
3564       DCI.AddToWorklist(NewSelect.getNode());
3565       return DAG.getNode(LHS.getOpcode(), SL, VT, NewSelect);
3566     }
3567   }
3568 
3569   return SDValue();
3570 }
3571 
3572 
3573 SDValue AMDGPUTargetLowering::performSelectCombine(SDNode *N,
3574                                                    DAGCombinerInfo &DCI) const {
3575   if (SDValue Folded = foldFreeOpFromSelect(DCI, SDValue(N, 0)))
3576     return Folded;
3577 
3578   SDValue Cond = N->getOperand(0);
3579   if (Cond.getOpcode() != ISD::SETCC)
3580     return SDValue();
3581 
3582   EVT VT = N->getValueType(0);
3583   SDValue LHS = Cond.getOperand(0);
3584   SDValue RHS = Cond.getOperand(1);
3585   SDValue CC = Cond.getOperand(2);
3586 
3587   SDValue True = N->getOperand(1);
3588   SDValue False = N->getOperand(2);
3589 
3590   if (Cond.hasOneUse()) { // TODO: Look for multiple select uses.
3591     SelectionDAG &DAG = DCI.DAG;
3592     if (DAG.isConstantValueOfAnyType(True) &&
3593         !DAG.isConstantValueOfAnyType(False)) {
3594       // Swap cmp + select pair to move constant to false input.
3595       // This will allow using VOPC cndmasks more often.
3596       // select (setcc x, y), k, x -> select (setccinv x, y), x, k
3597 
3598       SDLoc SL(N);
3599       ISD::CondCode NewCC =
3600           getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), LHS.getValueType());
3601 
3602       SDValue NewCond = DAG.getSetCC(SL, Cond.getValueType(), LHS, RHS, NewCC);
3603       return DAG.getNode(ISD::SELECT, SL, VT, NewCond, False, True);
3604     }
3605 
3606     if (VT == MVT::f32 && Subtarget->hasFminFmaxLegacy()) {
3607       SDValue MinMax
3608         = combineFMinMaxLegacy(SDLoc(N), VT, LHS, RHS, True, False, CC, DCI);
3609       // Revisit this node so we can catch min3/max3/med3 patterns.
3610       //DCI.AddToWorklist(MinMax.getNode());
3611       return MinMax;
3612     }
3613   }
3614 
3615   // There's no reason to not do this if the condition has other uses.
3616   return performCtlz_CttzCombine(SDLoc(N), Cond, True, False, DCI);
3617 }
3618 
3619 static bool isInv2Pi(const APFloat &APF) {
3620   static const APFloat KF16(APFloat::IEEEhalf(), APInt(16, 0x3118));
3621   static const APFloat KF32(APFloat::IEEEsingle(), APInt(32, 0x3e22f983));
3622   static const APFloat KF64(APFloat::IEEEdouble(), APInt(64, 0x3fc45f306dc9c882));
3623 
3624   return APF.bitwiseIsEqual(KF16) ||
3625          APF.bitwiseIsEqual(KF32) ||
3626          APF.bitwiseIsEqual(KF64);
3627 }
3628 
3629 // 0 and 1.0 / (0.5 * pi) do not have inline immmediates, so there is an
3630 // additional cost to negate them.
3631 bool AMDGPUTargetLowering::isConstantCostlierToNegate(SDValue N) const {
3632   if (const ConstantFPSDNode *C = isConstOrConstSplatFP(N)) {
3633     if (C->isZero() && !C->isNegative())
3634       return true;
3635 
3636     if (Subtarget->hasInv2PiInlineImm() && isInv2Pi(C->getValueAPF()))
3637       return true;
3638   }
3639 
3640   return false;
3641 }
3642 
3643 static unsigned inverseMinMax(unsigned Opc) {
3644   switch (Opc) {
3645   case ISD::FMAXNUM:
3646     return ISD::FMINNUM;
3647   case ISD::FMINNUM:
3648     return ISD::FMAXNUM;
3649   case ISD::FMAXNUM_IEEE:
3650     return ISD::FMINNUM_IEEE;
3651   case ISD::FMINNUM_IEEE:
3652     return ISD::FMAXNUM_IEEE;
3653   case AMDGPUISD::FMAX_LEGACY:
3654     return AMDGPUISD::FMIN_LEGACY;
3655   case AMDGPUISD::FMIN_LEGACY:
3656     return  AMDGPUISD::FMAX_LEGACY;
3657   default:
3658     llvm_unreachable("invalid min/max opcode");
3659   }
3660 }
3661 
3662 SDValue AMDGPUTargetLowering::performFNegCombine(SDNode *N,
3663                                                  DAGCombinerInfo &DCI) const {
3664   SelectionDAG &DAG = DCI.DAG;
3665   SDValue N0 = N->getOperand(0);
3666   EVT VT = N->getValueType(0);
3667 
3668   unsigned Opc = N0.getOpcode();
3669 
3670   // If the input has multiple uses and we can either fold the negate down, or
3671   // the other uses cannot, give up. This both prevents unprofitable
3672   // transformations and infinite loops: we won't repeatedly try to fold around
3673   // a negate that has no 'good' form.
3674   if (N0.hasOneUse()) {
3675     // This may be able to fold into the source, but at a code size cost. Don't
3676     // fold if the fold into the user is free.
3677     if (allUsesHaveSourceMods(N, 0))
3678       return SDValue();
3679   } else {
3680     if (fnegFoldsIntoOp(Opc) &&
3681         (allUsesHaveSourceMods(N) || !allUsesHaveSourceMods(N0.getNode())))
3682       return SDValue();
3683   }
3684 
3685   SDLoc SL(N);
3686   switch (Opc) {
3687   case ISD::FADD: {
3688     if (!mayIgnoreSignedZero(N0))
3689       return SDValue();
3690 
3691     // (fneg (fadd x, y)) -> (fadd (fneg x), (fneg y))
3692     SDValue LHS = N0.getOperand(0);
3693     SDValue RHS = N0.getOperand(1);
3694 
3695     if (LHS.getOpcode() != ISD::FNEG)
3696       LHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3697     else
3698       LHS = LHS.getOperand(0);
3699 
3700     if (RHS.getOpcode() != ISD::FNEG)
3701       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3702     else
3703       RHS = RHS.getOperand(0);
3704 
3705     SDValue Res = DAG.getNode(ISD::FADD, SL, VT, LHS, RHS, N0->getFlags());
3706     if (Res.getOpcode() != ISD::FADD)
3707       return SDValue(); // Op got folded away.
3708     if (!N0.hasOneUse())
3709       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3710     return Res;
3711   }
3712   case ISD::FMUL:
3713   case AMDGPUISD::FMUL_LEGACY: {
3714     // (fneg (fmul x, y)) -> (fmul x, (fneg y))
3715     // (fneg (fmul_legacy x, y)) -> (fmul_legacy x, (fneg y))
3716     SDValue LHS = N0.getOperand(0);
3717     SDValue RHS = N0.getOperand(1);
3718 
3719     if (LHS.getOpcode() == ISD::FNEG)
3720       LHS = LHS.getOperand(0);
3721     else if (RHS.getOpcode() == ISD::FNEG)
3722       RHS = RHS.getOperand(0);
3723     else
3724       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3725 
3726     SDValue Res = DAG.getNode(Opc, SL, VT, LHS, RHS, N0->getFlags());
3727     if (Res.getOpcode() != Opc)
3728       return SDValue(); // Op got folded away.
3729     if (!N0.hasOneUse())
3730       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3731     return Res;
3732   }
3733   case ISD::FMA:
3734   case ISD::FMAD: {
3735     if (!mayIgnoreSignedZero(N0))
3736       return SDValue();
3737 
3738     // (fneg (fma x, y, z)) -> (fma x, (fneg y), (fneg z))
3739     SDValue LHS = N0.getOperand(0);
3740     SDValue MHS = N0.getOperand(1);
3741     SDValue RHS = N0.getOperand(2);
3742 
3743     if (LHS.getOpcode() == ISD::FNEG)
3744       LHS = LHS.getOperand(0);
3745     else if (MHS.getOpcode() == ISD::FNEG)
3746       MHS = MHS.getOperand(0);
3747     else
3748       MHS = DAG.getNode(ISD::FNEG, SL, VT, MHS);
3749 
3750     if (RHS.getOpcode() != ISD::FNEG)
3751       RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3752     else
3753       RHS = RHS.getOperand(0);
3754 
3755     SDValue Res = DAG.getNode(Opc, SL, VT, LHS, MHS, RHS);
3756     if (Res.getOpcode() != Opc)
3757       return SDValue(); // Op got folded away.
3758     if (!N0.hasOneUse())
3759       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3760     return Res;
3761   }
3762   case ISD::FMAXNUM:
3763   case ISD::FMINNUM:
3764   case ISD::FMAXNUM_IEEE:
3765   case ISD::FMINNUM_IEEE:
3766   case AMDGPUISD::FMAX_LEGACY:
3767   case AMDGPUISD::FMIN_LEGACY: {
3768     // fneg (fmaxnum x, y) -> fminnum (fneg x), (fneg y)
3769     // fneg (fminnum x, y) -> fmaxnum (fneg x), (fneg y)
3770     // fneg (fmax_legacy x, y) -> fmin_legacy (fneg x), (fneg y)
3771     // fneg (fmin_legacy x, y) -> fmax_legacy (fneg x), (fneg y)
3772 
3773     SDValue LHS = N0.getOperand(0);
3774     SDValue RHS = N0.getOperand(1);
3775 
3776     // 0 doesn't have a negated inline immediate.
3777     // TODO: This constant check should be generalized to other operations.
3778     if (isConstantCostlierToNegate(RHS))
3779       return SDValue();
3780 
3781     SDValue NegLHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3782     SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3783     unsigned Opposite = inverseMinMax(Opc);
3784 
3785     SDValue Res = DAG.getNode(Opposite, SL, VT, NegLHS, NegRHS, N0->getFlags());
3786     if (Res.getOpcode() != Opposite)
3787       return SDValue(); // Op got folded away.
3788     if (!N0.hasOneUse())
3789       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3790     return Res;
3791   }
3792   case AMDGPUISD::FMED3: {
3793     SDValue Ops[3];
3794     for (unsigned I = 0; I < 3; ++I)
3795       Ops[I] = DAG.getNode(ISD::FNEG, SL, VT, N0->getOperand(I), N0->getFlags());
3796 
3797     SDValue Res = DAG.getNode(AMDGPUISD::FMED3, SL, VT, Ops, N0->getFlags());
3798     if (Res.getOpcode() != AMDGPUISD::FMED3)
3799       return SDValue(); // Op got folded away.
3800     if (!N0.hasOneUse())
3801       DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3802     return Res;
3803   }
3804   case ISD::FP_EXTEND:
3805   case ISD::FTRUNC:
3806   case ISD::FRINT:
3807   case ISD::FNEARBYINT: // XXX - Should fround be handled?
3808   case ISD::FSIN:
3809   case ISD::FCANONICALIZE:
3810   case AMDGPUISD::RCP:
3811   case AMDGPUISD::RCP_LEGACY:
3812   case AMDGPUISD::RCP_IFLAG:
3813   case AMDGPUISD::SIN_HW: {
3814     SDValue CvtSrc = N0.getOperand(0);
3815     if (CvtSrc.getOpcode() == ISD::FNEG) {
3816       // (fneg (fp_extend (fneg x))) -> (fp_extend x)
3817       // (fneg (rcp (fneg x))) -> (rcp x)
3818       return DAG.getNode(Opc, SL, VT, CvtSrc.getOperand(0));
3819     }
3820 
3821     if (!N0.hasOneUse())
3822       return SDValue();
3823 
3824     // (fneg (fp_extend x)) -> (fp_extend (fneg x))
3825     // (fneg (rcp x)) -> (rcp (fneg x))
3826     SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3827     return DAG.getNode(Opc, SL, VT, Neg, N0->getFlags());
3828   }
3829   case ISD::FP_ROUND: {
3830     SDValue CvtSrc = N0.getOperand(0);
3831 
3832     if (CvtSrc.getOpcode() == ISD::FNEG) {
3833       // (fneg (fp_round (fneg x))) -> (fp_round x)
3834       return DAG.getNode(ISD::FP_ROUND, SL, VT,
3835                          CvtSrc.getOperand(0), N0.getOperand(1));
3836     }
3837 
3838     if (!N0.hasOneUse())
3839       return SDValue();
3840 
3841     // (fneg (fp_round x)) -> (fp_round (fneg x))
3842     SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3843     return DAG.getNode(ISD::FP_ROUND, SL, VT, Neg, N0.getOperand(1));
3844   }
3845   case ISD::FP16_TO_FP: {
3846     // v_cvt_f32_f16 supports source modifiers on pre-VI targets without legal
3847     // f16, but legalization of f16 fneg ends up pulling it out of the source.
3848     // Put the fneg back as a legal source operation that can be matched later.
3849     SDLoc SL(N);
3850 
3851     SDValue Src = N0.getOperand(0);
3852     EVT SrcVT = Src.getValueType();
3853 
3854     // fneg (fp16_to_fp x) -> fp16_to_fp (xor x, 0x8000)
3855     SDValue IntFNeg = DAG.getNode(ISD::XOR, SL, SrcVT, Src,
3856                                   DAG.getConstant(0x8000, SL, SrcVT));
3857     return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFNeg);
3858   }
3859   default:
3860     return SDValue();
3861   }
3862 }
3863 
3864 SDValue AMDGPUTargetLowering::performFAbsCombine(SDNode *N,
3865                                                  DAGCombinerInfo &DCI) const {
3866   SelectionDAG &DAG = DCI.DAG;
3867   SDValue N0 = N->getOperand(0);
3868 
3869   if (!N0.hasOneUse())
3870     return SDValue();
3871 
3872   switch (N0.getOpcode()) {
3873   case ISD::FP16_TO_FP: {
3874     assert(!Subtarget->has16BitInsts() && "should only see if f16 is illegal");
3875     SDLoc SL(N);
3876     SDValue Src = N0.getOperand(0);
3877     EVT SrcVT = Src.getValueType();
3878 
3879     // fabs (fp16_to_fp x) -> fp16_to_fp (and x, 0x7fff)
3880     SDValue IntFAbs = DAG.getNode(ISD::AND, SL, SrcVT, Src,
3881                                   DAG.getConstant(0x7fff, SL, SrcVT));
3882     return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFAbs);
3883   }
3884   default:
3885     return SDValue();
3886   }
3887 }
3888 
3889 SDValue AMDGPUTargetLowering::performRcpCombine(SDNode *N,
3890                                                 DAGCombinerInfo &DCI) const {
3891   const auto *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
3892   if (!CFP)
3893     return SDValue();
3894 
3895   // XXX - Should this flush denormals?
3896   const APFloat &Val = CFP->getValueAPF();
3897   APFloat One(Val.getSemantics(), "1.0");
3898   return DCI.DAG.getConstantFP(One / Val, SDLoc(N), N->getValueType(0));
3899 }
3900 
3901 SDValue AMDGPUTargetLowering::PerformDAGCombine(SDNode *N,
3902                                                 DAGCombinerInfo &DCI) const {
3903   SelectionDAG &DAG = DCI.DAG;
3904   SDLoc DL(N);
3905 
3906   switch(N->getOpcode()) {
3907   default:
3908     break;
3909   case ISD::BITCAST: {
3910     EVT DestVT = N->getValueType(0);
3911 
3912     // Push casts through vector builds. This helps avoid emitting a large
3913     // number of copies when materializing floating point vector constants.
3914     //
3915     // vNt1 bitcast (vNt0 (build_vector t0:x, t0:y)) =>
3916     //   vnt1 = build_vector (t1 (bitcast t0:x)), (t1 (bitcast t0:y))
3917     if (DestVT.isVector()) {
3918       SDValue Src = N->getOperand(0);
3919       if (Src.getOpcode() == ISD::BUILD_VECTOR) {
3920         EVT SrcVT = Src.getValueType();
3921         unsigned NElts = DestVT.getVectorNumElements();
3922 
3923         if (SrcVT.getVectorNumElements() == NElts) {
3924           EVT DestEltVT = DestVT.getVectorElementType();
3925 
3926           SmallVector<SDValue, 8> CastedElts;
3927           SDLoc SL(N);
3928           for (unsigned I = 0, E = SrcVT.getVectorNumElements(); I != E; ++I) {
3929             SDValue Elt = Src.getOperand(I);
3930             CastedElts.push_back(DAG.getNode(ISD::BITCAST, DL, DestEltVT, Elt));
3931           }
3932 
3933           return DAG.getBuildVector(DestVT, SL, CastedElts);
3934         }
3935       }
3936     }
3937 
3938     if (DestVT.getSizeInBits() != 64 && !DestVT.isVector())
3939       break;
3940 
3941     // Fold bitcasts of constants.
3942     //
3943     // v2i32 (bitcast i64:k) -> build_vector lo_32(k), hi_32(k)
3944     // TODO: Generalize and move to DAGCombiner
3945     SDValue Src = N->getOperand(0);
3946     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src)) {
3947       if (Src.getValueType() == MVT::i64) {
3948         SDLoc SL(N);
3949         uint64_t CVal = C->getZExtValue();
3950         SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3951                                  DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3952                                  DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3953         return DAG.getNode(ISD::BITCAST, SL, DestVT, BV);
3954       }
3955     }
3956 
3957     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Src)) {
3958       const APInt &Val = C->getValueAPF().bitcastToAPInt();
3959       SDLoc SL(N);
3960       uint64_t CVal = Val.getZExtValue();
3961       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3962                                 DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3963                                 DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3964 
3965       return DAG.getNode(ISD::BITCAST, SL, DestVT, Vec);
3966     }
3967 
3968     break;
3969   }
3970   case ISD::SHL: {
3971     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3972       break;
3973 
3974     return performShlCombine(N, DCI);
3975   }
3976   case ISD::SRL: {
3977     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3978       break;
3979 
3980     return performSrlCombine(N, DCI);
3981   }
3982   case ISD::SRA: {
3983     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3984       break;
3985 
3986     return performSraCombine(N, DCI);
3987   }
3988   case ISD::TRUNCATE:
3989     return performTruncateCombine(N, DCI);
3990   case ISD::MUL:
3991     return performMulCombine(N, DCI);
3992   case ISD::MULHS:
3993     return performMulhsCombine(N, DCI);
3994   case ISD::MULHU:
3995     return performMulhuCombine(N, DCI);
3996   case AMDGPUISD::MUL_I24:
3997   case AMDGPUISD::MUL_U24:
3998   case AMDGPUISD::MULHI_I24:
3999   case AMDGPUISD::MULHI_U24: {
4000     if (SDValue V = simplifyI24(N, DCI))
4001       return V;
4002     return SDValue();
4003   }
4004   case AMDGPUISD::MUL_LOHI_I24:
4005   case AMDGPUISD::MUL_LOHI_U24:
4006     return performMulLoHi24Combine(N, DCI);
4007   case ISD::SELECT:
4008     return performSelectCombine(N, DCI);
4009   case ISD::FNEG:
4010     return performFNegCombine(N, DCI);
4011   case ISD::FABS:
4012     return performFAbsCombine(N, DCI);
4013   case AMDGPUISD::BFE_I32:
4014   case AMDGPUISD::BFE_U32: {
4015     assert(!N->getValueType(0).isVector() &&
4016            "Vector handling of BFE not implemented");
4017     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
4018     if (!Width)
4019       break;
4020 
4021     uint32_t WidthVal = Width->getZExtValue() & 0x1f;
4022     if (WidthVal == 0)
4023       return DAG.getConstant(0, DL, MVT::i32);
4024 
4025     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
4026     if (!Offset)
4027       break;
4028 
4029     SDValue BitsFrom = N->getOperand(0);
4030     uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
4031 
4032     bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
4033 
4034     if (OffsetVal == 0) {
4035       // This is already sign / zero extended, so try to fold away extra BFEs.
4036       unsigned SignBits =  Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
4037 
4038       unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
4039       if (OpSignBits >= SignBits)
4040         return BitsFrom;
4041 
4042       EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
4043       if (Signed) {
4044         // This is a sign_extend_inreg. Replace it to take advantage of existing
4045         // DAG Combines. If not eliminated, we will match back to BFE during
4046         // selection.
4047 
4048         // TODO: The sext_inreg of extended types ends, although we can could
4049         // handle them in a single BFE.
4050         return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
4051                            DAG.getValueType(SmallVT));
4052       }
4053 
4054       return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
4055     }
4056 
4057     if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(BitsFrom)) {
4058       if (Signed) {
4059         return constantFoldBFE<int32_t>(DAG,
4060                                         CVal->getSExtValue(),
4061                                         OffsetVal,
4062                                         WidthVal,
4063                                         DL);
4064       }
4065 
4066       return constantFoldBFE<uint32_t>(DAG,
4067                                        CVal->getZExtValue(),
4068                                        OffsetVal,
4069                                        WidthVal,
4070                                        DL);
4071     }
4072 
4073     if ((OffsetVal + WidthVal) >= 32 &&
4074         !(Subtarget->hasSDWA() && OffsetVal == 16 && WidthVal == 16)) {
4075       SDValue ShiftVal = DAG.getConstant(OffsetVal, DL, MVT::i32);
4076       return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
4077                          BitsFrom, ShiftVal);
4078     }
4079 
4080     if (BitsFrom.hasOneUse()) {
4081       APInt Demanded = APInt::getBitsSet(32,
4082                                          OffsetVal,
4083                                          OffsetVal + WidthVal);
4084 
4085       KnownBits Known;
4086       TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4087                                             !DCI.isBeforeLegalizeOps());
4088       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4089       if (TLI.ShrinkDemandedConstant(BitsFrom, Demanded, TLO) ||
4090           TLI.SimplifyDemandedBits(BitsFrom, Demanded, Known, TLO)) {
4091         DCI.CommitTargetLoweringOpt(TLO);
4092       }
4093     }
4094 
4095     break;
4096   }
4097   case ISD::LOAD:
4098     return performLoadCombine(N, DCI);
4099   case ISD::STORE:
4100     return performStoreCombine(N, DCI);
4101   case AMDGPUISD::RCP:
4102   case AMDGPUISD::RCP_IFLAG:
4103     return performRcpCombine(N, DCI);
4104   case ISD::AssertZext:
4105   case ISD::AssertSext:
4106     return performAssertSZExtCombine(N, DCI);
4107   case ISD::INTRINSIC_WO_CHAIN:
4108     return performIntrinsicWOChainCombine(N, DCI);
4109   }
4110   return SDValue();
4111 }
4112 
4113 //===----------------------------------------------------------------------===//
4114 // Helper functions
4115 //===----------------------------------------------------------------------===//
4116 
4117 SDValue AMDGPUTargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
4118                                                    const TargetRegisterClass *RC,
4119                                                    unsigned Reg, EVT VT,
4120                                                    const SDLoc &SL,
4121                                                    bool RawReg) const {
4122   MachineFunction &MF = DAG.getMachineFunction();
4123   MachineRegisterInfo &MRI = MF.getRegInfo();
4124   unsigned VReg;
4125 
4126   if (!MRI.isLiveIn(Reg)) {
4127     VReg = MRI.createVirtualRegister(RC);
4128     MRI.addLiveIn(Reg, VReg);
4129   } else {
4130     VReg = MRI.getLiveInVirtReg(Reg);
4131   }
4132 
4133   if (RawReg)
4134     return DAG.getRegister(VReg, VT);
4135 
4136   return DAG.getCopyFromReg(DAG.getEntryNode(), SL, VReg, VT);
4137 }
4138 
4139 // This may be called multiple times, and nothing prevents creating multiple
4140 // objects at the same offset. See if we already defined this object.
4141 static int getOrCreateFixedStackObject(MachineFrameInfo &MFI, unsigned Size,
4142                                        int64_t Offset) {
4143   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
4144     if (MFI.getObjectOffset(I) == Offset) {
4145       assert(MFI.getObjectSize(I) == Size);
4146       return I;
4147     }
4148   }
4149 
4150   return MFI.CreateFixedObject(Size, Offset, true);
4151 }
4152 
4153 SDValue AMDGPUTargetLowering::loadStackInputValue(SelectionDAG &DAG,
4154                                                   EVT VT,
4155                                                   const SDLoc &SL,
4156                                                   int64_t Offset) const {
4157   MachineFunction &MF = DAG.getMachineFunction();
4158   MachineFrameInfo &MFI = MF.getFrameInfo();
4159   int FI = getOrCreateFixedStackObject(MFI, VT.getStoreSize(), Offset);
4160 
4161   auto SrcPtrInfo = MachinePointerInfo::getStack(MF, Offset);
4162   SDValue Ptr = DAG.getFrameIndex(FI, MVT::i32);
4163 
4164   return DAG.getLoad(VT, SL, DAG.getEntryNode(), Ptr, SrcPtrInfo, 4,
4165                      MachineMemOperand::MODereferenceable |
4166                      MachineMemOperand::MOInvariant);
4167 }
4168 
4169 SDValue AMDGPUTargetLowering::storeStackInputValue(SelectionDAG &DAG,
4170                                                    const SDLoc &SL,
4171                                                    SDValue Chain,
4172                                                    SDValue ArgVal,
4173                                                    int64_t Offset) const {
4174   MachineFunction &MF = DAG.getMachineFunction();
4175   MachinePointerInfo DstInfo = MachinePointerInfo::getStack(MF, Offset);
4176 
4177   SDValue Ptr = DAG.getConstant(Offset, SL, MVT::i32);
4178   SDValue Store = DAG.getStore(Chain, SL, ArgVal, Ptr, DstInfo, 4,
4179                                MachineMemOperand::MODereferenceable);
4180   return Store;
4181 }
4182 
4183 SDValue AMDGPUTargetLowering::loadInputValue(SelectionDAG &DAG,
4184                                              const TargetRegisterClass *RC,
4185                                              EVT VT, const SDLoc &SL,
4186                                              const ArgDescriptor &Arg) const {
4187   assert(Arg && "Attempting to load missing argument");
4188 
4189   SDValue V = Arg.isRegister() ?
4190     CreateLiveInRegister(DAG, RC, Arg.getRegister(), VT, SL) :
4191     loadStackInputValue(DAG, VT, SL, Arg.getStackOffset());
4192 
4193   if (!Arg.isMasked())
4194     return V;
4195 
4196   unsigned Mask = Arg.getMask();
4197   unsigned Shift = countTrailingZeros<unsigned>(Mask);
4198   V = DAG.getNode(ISD::SRL, SL, VT, V,
4199                   DAG.getShiftAmountConstant(Shift, VT, SL));
4200   return DAG.getNode(ISD::AND, SL, VT, V,
4201                      DAG.getConstant(Mask >> Shift, SL, VT));
4202 }
4203 
4204 uint32_t AMDGPUTargetLowering::getImplicitParameterOffset(
4205     const MachineFunction &MF, const ImplicitParameter Param) const {
4206   const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
4207   const AMDGPUSubtarget &ST =
4208       AMDGPUSubtarget::get(getTargetMachine(), MF.getFunction());
4209   unsigned ExplicitArgOffset = ST.getExplicitKernelArgOffset(MF.getFunction());
4210   const Align Alignment = ST.getAlignmentForImplicitArgPtr();
4211   uint64_t ArgOffset = alignTo(MFI->getExplicitKernArgSize(), Alignment) +
4212                        ExplicitArgOffset;
4213   switch (Param) {
4214   case GRID_DIM:
4215     return ArgOffset;
4216   case GRID_OFFSET:
4217     return ArgOffset + 4;
4218   }
4219   llvm_unreachable("unexpected implicit parameter type");
4220 }
4221 
4222 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
4223 
4224 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
4225   switch ((AMDGPUISD::NodeType)Opcode) {
4226   case AMDGPUISD::FIRST_NUMBER: break;
4227   // AMDIL DAG nodes
4228   NODE_NAME_CASE(UMUL);
4229   NODE_NAME_CASE(BRANCH_COND);
4230 
4231   // AMDGPU DAG nodes
4232   NODE_NAME_CASE(IF)
4233   NODE_NAME_CASE(ELSE)
4234   NODE_NAME_CASE(LOOP)
4235   NODE_NAME_CASE(CALL)
4236   NODE_NAME_CASE(TC_RETURN)
4237   NODE_NAME_CASE(TRAP)
4238   NODE_NAME_CASE(RET_FLAG)
4239   NODE_NAME_CASE(RETURN_TO_EPILOG)
4240   NODE_NAME_CASE(ENDPGM)
4241   NODE_NAME_CASE(DWORDADDR)
4242   NODE_NAME_CASE(FRACT)
4243   NODE_NAME_CASE(SETCC)
4244   NODE_NAME_CASE(SETREG)
4245   NODE_NAME_CASE(DENORM_MODE)
4246   NODE_NAME_CASE(FMA_W_CHAIN)
4247   NODE_NAME_CASE(FMUL_W_CHAIN)
4248   NODE_NAME_CASE(CLAMP)
4249   NODE_NAME_CASE(COS_HW)
4250   NODE_NAME_CASE(SIN_HW)
4251   NODE_NAME_CASE(FMAX_LEGACY)
4252   NODE_NAME_CASE(FMIN_LEGACY)
4253   NODE_NAME_CASE(FMAX3)
4254   NODE_NAME_CASE(SMAX3)
4255   NODE_NAME_CASE(UMAX3)
4256   NODE_NAME_CASE(FMIN3)
4257   NODE_NAME_CASE(SMIN3)
4258   NODE_NAME_CASE(UMIN3)
4259   NODE_NAME_CASE(FMED3)
4260   NODE_NAME_CASE(SMED3)
4261   NODE_NAME_CASE(UMED3)
4262   NODE_NAME_CASE(FDOT2)
4263   NODE_NAME_CASE(URECIP)
4264   NODE_NAME_CASE(DIV_SCALE)
4265   NODE_NAME_CASE(DIV_FMAS)
4266   NODE_NAME_CASE(DIV_FIXUP)
4267   NODE_NAME_CASE(FMAD_FTZ)
4268   NODE_NAME_CASE(TRIG_PREOP)
4269   NODE_NAME_CASE(RCP)
4270   NODE_NAME_CASE(RSQ)
4271   NODE_NAME_CASE(RCP_LEGACY)
4272   NODE_NAME_CASE(RSQ_LEGACY)
4273   NODE_NAME_CASE(RCP_IFLAG)
4274   NODE_NAME_CASE(FMUL_LEGACY)
4275   NODE_NAME_CASE(RSQ_CLAMP)
4276   NODE_NAME_CASE(LDEXP)
4277   NODE_NAME_CASE(FP_CLASS)
4278   NODE_NAME_CASE(DOT4)
4279   NODE_NAME_CASE(CARRY)
4280   NODE_NAME_CASE(BORROW)
4281   NODE_NAME_CASE(BFE_U32)
4282   NODE_NAME_CASE(BFE_I32)
4283   NODE_NAME_CASE(BFI)
4284   NODE_NAME_CASE(BFM)
4285   NODE_NAME_CASE(FFBH_U32)
4286   NODE_NAME_CASE(FFBH_I32)
4287   NODE_NAME_CASE(FFBL_B32)
4288   NODE_NAME_CASE(MUL_U24)
4289   NODE_NAME_CASE(MUL_I24)
4290   NODE_NAME_CASE(MULHI_U24)
4291   NODE_NAME_CASE(MULHI_I24)
4292   NODE_NAME_CASE(MUL_LOHI_U24)
4293   NODE_NAME_CASE(MUL_LOHI_I24)
4294   NODE_NAME_CASE(MAD_U24)
4295   NODE_NAME_CASE(MAD_I24)
4296   NODE_NAME_CASE(MAD_I64_I32)
4297   NODE_NAME_CASE(MAD_U64_U32)
4298   NODE_NAME_CASE(PERM)
4299   NODE_NAME_CASE(TEXTURE_FETCH)
4300   NODE_NAME_CASE(R600_EXPORT)
4301   NODE_NAME_CASE(CONST_ADDRESS)
4302   NODE_NAME_CASE(REGISTER_LOAD)
4303   NODE_NAME_CASE(REGISTER_STORE)
4304   NODE_NAME_CASE(SAMPLE)
4305   NODE_NAME_CASE(SAMPLEB)
4306   NODE_NAME_CASE(SAMPLED)
4307   NODE_NAME_CASE(SAMPLEL)
4308   NODE_NAME_CASE(CVT_F32_UBYTE0)
4309   NODE_NAME_CASE(CVT_F32_UBYTE1)
4310   NODE_NAME_CASE(CVT_F32_UBYTE2)
4311   NODE_NAME_CASE(CVT_F32_UBYTE3)
4312   NODE_NAME_CASE(CVT_PKRTZ_F16_F32)
4313   NODE_NAME_CASE(CVT_PKNORM_I16_F32)
4314   NODE_NAME_CASE(CVT_PKNORM_U16_F32)
4315   NODE_NAME_CASE(CVT_PK_I16_I32)
4316   NODE_NAME_CASE(CVT_PK_U16_U32)
4317   NODE_NAME_CASE(FP_TO_FP16)
4318   NODE_NAME_CASE(FP16_ZEXT)
4319   NODE_NAME_CASE(BUILD_VERTICAL_VECTOR)
4320   NODE_NAME_CASE(CONST_DATA_PTR)
4321   NODE_NAME_CASE(PC_ADD_REL_OFFSET)
4322   NODE_NAME_CASE(LDS)
4323   NODE_NAME_CASE(KILL)
4324   NODE_NAME_CASE(DUMMY_CHAIN)
4325   case AMDGPUISD::FIRST_MEM_OPCODE_NUMBER: break;
4326   NODE_NAME_CASE(INTERP_P1LL_F16)
4327   NODE_NAME_CASE(INTERP_P1LV_F16)
4328   NODE_NAME_CASE(INTERP_P2_F16)
4329   NODE_NAME_CASE(LOAD_D16_HI)
4330   NODE_NAME_CASE(LOAD_D16_LO)
4331   NODE_NAME_CASE(LOAD_D16_HI_I8)
4332   NODE_NAME_CASE(LOAD_D16_HI_U8)
4333   NODE_NAME_CASE(LOAD_D16_LO_I8)
4334   NODE_NAME_CASE(LOAD_D16_LO_U8)
4335   NODE_NAME_CASE(STORE_MSKOR)
4336   NODE_NAME_CASE(LOAD_CONSTANT)
4337   NODE_NAME_CASE(TBUFFER_STORE_FORMAT)
4338   NODE_NAME_CASE(TBUFFER_STORE_FORMAT_D16)
4339   NODE_NAME_CASE(TBUFFER_LOAD_FORMAT)
4340   NODE_NAME_CASE(TBUFFER_LOAD_FORMAT_D16)
4341   NODE_NAME_CASE(DS_ORDERED_COUNT)
4342   NODE_NAME_CASE(ATOMIC_CMP_SWAP)
4343   NODE_NAME_CASE(ATOMIC_INC)
4344   NODE_NAME_CASE(ATOMIC_DEC)
4345   NODE_NAME_CASE(ATOMIC_LOAD_FMIN)
4346   NODE_NAME_CASE(ATOMIC_LOAD_FMAX)
4347   NODE_NAME_CASE(BUFFER_LOAD)
4348   NODE_NAME_CASE(BUFFER_LOAD_UBYTE)
4349   NODE_NAME_CASE(BUFFER_LOAD_USHORT)
4350   NODE_NAME_CASE(BUFFER_LOAD_BYTE)
4351   NODE_NAME_CASE(BUFFER_LOAD_SHORT)
4352   NODE_NAME_CASE(BUFFER_LOAD_FORMAT)
4353   NODE_NAME_CASE(BUFFER_LOAD_FORMAT_D16)
4354   NODE_NAME_CASE(SBUFFER_LOAD)
4355   NODE_NAME_CASE(BUFFER_STORE)
4356   NODE_NAME_CASE(BUFFER_STORE_BYTE)
4357   NODE_NAME_CASE(BUFFER_STORE_SHORT)
4358   NODE_NAME_CASE(BUFFER_STORE_FORMAT)
4359   NODE_NAME_CASE(BUFFER_STORE_FORMAT_D16)
4360   NODE_NAME_CASE(BUFFER_ATOMIC_SWAP)
4361   NODE_NAME_CASE(BUFFER_ATOMIC_ADD)
4362   NODE_NAME_CASE(BUFFER_ATOMIC_SUB)
4363   NODE_NAME_CASE(BUFFER_ATOMIC_SMIN)
4364   NODE_NAME_CASE(BUFFER_ATOMIC_UMIN)
4365   NODE_NAME_CASE(BUFFER_ATOMIC_SMAX)
4366   NODE_NAME_CASE(BUFFER_ATOMIC_UMAX)
4367   NODE_NAME_CASE(BUFFER_ATOMIC_AND)
4368   NODE_NAME_CASE(BUFFER_ATOMIC_OR)
4369   NODE_NAME_CASE(BUFFER_ATOMIC_XOR)
4370   NODE_NAME_CASE(BUFFER_ATOMIC_INC)
4371   NODE_NAME_CASE(BUFFER_ATOMIC_DEC)
4372   NODE_NAME_CASE(BUFFER_ATOMIC_CMPSWAP)
4373   NODE_NAME_CASE(BUFFER_ATOMIC_FADD)
4374   NODE_NAME_CASE(BUFFER_ATOMIC_PK_FADD)
4375   NODE_NAME_CASE(ATOMIC_PK_FADD)
4376 
4377   case AMDGPUISD::LAST_AMDGPU_ISD_NUMBER: break;
4378   }
4379   return nullptr;
4380 }
4381 
4382 SDValue AMDGPUTargetLowering::getSqrtEstimate(SDValue Operand,
4383                                               SelectionDAG &DAG, int Enabled,
4384                                               int &RefinementSteps,
4385                                               bool &UseOneConstNR,
4386                                               bool Reciprocal) const {
4387   EVT VT = Operand.getValueType();
4388 
4389   if (VT == MVT::f32) {
4390     RefinementSteps = 0;
4391     return DAG.getNode(AMDGPUISD::RSQ, SDLoc(Operand), VT, Operand);
4392   }
4393 
4394   // TODO: There is also f64 rsq instruction, but the documentation is less
4395   // clear on its precision.
4396 
4397   return SDValue();
4398 }
4399 
4400 SDValue AMDGPUTargetLowering::getRecipEstimate(SDValue Operand,
4401                                                SelectionDAG &DAG, int Enabled,
4402                                                int &RefinementSteps) const {
4403   EVT VT = Operand.getValueType();
4404 
4405   if (VT == MVT::f32) {
4406     // Reciprocal, < 1 ulp error.
4407     //
4408     // This reciprocal approximation converges to < 0.5 ulp error with one
4409     // newton rhapson performed with two fused multiple adds (FMAs).
4410 
4411     RefinementSteps = 0;
4412     return DAG.getNode(AMDGPUISD::RCP, SDLoc(Operand), VT, Operand);
4413   }
4414 
4415   // TODO: There is also f64 rcp instruction, but the documentation is less
4416   // clear on its precision.
4417 
4418   return SDValue();
4419 }
4420 
4421 void AMDGPUTargetLowering::computeKnownBitsForTargetNode(
4422     const SDValue Op, KnownBits &Known,
4423     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
4424 
4425   Known.resetAll(); // Don't know anything.
4426 
4427   unsigned Opc = Op.getOpcode();
4428 
4429   switch (Opc) {
4430   default:
4431     break;
4432   case AMDGPUISD::CARRY:
4433   case AMDGPUISD::BORROW: {
4434     Known.Zero = APInt::getHighBitsSet(32, 31);
4435     break;
4436   }
4437 
4438   case AMDGPUISD::BFE_I32:
4439   case AMDGPUISD::BFE_U32: {
4440     ConstantSDNode *CWidth = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4441     if (!CWidth)
4442       return;
4443 
4444     uint32_t Width = CWidth->getZExtValue() & 0x1f;
4445 
4446     if (Opc == AMDGPUISD::BFE_U32)
4447       Known.Zero = APInt::getHighBitsSet(32, 32 - Width);
4448 
4449     break;
4450   }
4451   case AMDGPUISD::FP_TO_FP16:
4452   case AMDGPUISD::FP16_ZEXT: {
4453     unsigned BitWidth = Known.getBitWidth();
4454 
4455     // High bits are zero.
4456     Known.Zero = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
4457     break;
4458   }
4459   case AMDGPUISD::MUL_U24:
4460   case AMDGPUISD::MUL_I24: {
4461     KnownBits LHSKnown = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
4462     KnownBits RHSKnown = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
4463     unsigned TrailZ = LHSKnown.countMinTrailingZeros() +
4464                       RHSKnown.countMinTrailingZeros();
4465     Known.Zero.setLowBits(std::min(TrailZ, 32u));
4466     // Skip extra check if all bits are known zeros.
4467     if (TrailZ >= 32)
4468       break;
4469 
4470     // Truncate to 24 bits.
4471     LHSKnown = LHSKnown.trunc(24);
4472     RHSKnown = RHSKnown.trunc(24);
4473 
4474     if (Opc == AMDGPUISD::MUL_I24) {
4475       unsigned LHSValBits = 24 - LHSKnown.countMinSignBits();
4476       unsigned RHSValBits = 24 - RHSKnown.countMinSignBits();
4477       unsigned MaxValBits = std::min(LHSValBits + RHSValBits, 32u);
4478       if (MaxValBits >= 32)
4479         break;
4480       bool LHSNegative = LHSKnown.isNegative();
4481       bool LHSNonNegative = LHSKnown.isNonNegative();
4482       bool LHSPositive = LHSKnown.isStrictlyPositive();
4483       bool RHSNegative = RHSKnown.isNegative();
4484       bool RHSNonNegative = RHSKnown.isNonNegative();
4485       bool RHSPositive = RHSKnown.isStrictlyPositive();
4486 
4487       if ((LHSNonNegative && RHSNonNegative) || (LHSNegative && RHSNegative))
4488         Known.Zero.setHighBits(32 - MaxValBits);
4489       else if ((LHSNegative && RHSPositive) || (LHSPositive && RHSNegative))
4490         Known.One.setHighBits(32 - MaxValBits);
4491     } else {
4492       unsigned LHSValBits = 24 - LHSKnown.countMinLeadingZeros();
4493       unsigned RHSValBits = 24 - RHSKnown.countMinLeadingZeros();
4494       unsigned MaxValBits = std::min(LHSValBits + RHSValBits, 32u);
4495       if (MaxValBits >= 32)
4496         break;
4497       Known.Zero.setHighBits(32 - MaxValBits);
4498     }
4499     break;
4500   }
4501   case AMDGPUISD::PERM: {
4502     ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4503     if (!CMask)
4504       return;
4505 
4506     KnownBits LHSKnown = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
4507     KnownBits RHSKnown = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
4508     unsigned Sel = CMask->getZExtValue();
4509 
4510     for (unsigned I = 0; I < 32; I += 8) {
4511       unsigned SelBits = Sel & 0xff;
4512       if (SelBits < 4) {
4513         SelBits *= 8;
4514         Known.One |= ((RHSKnown.One.getZExtValue() >> SelBits) & 0xff) << I;
4515         Known.Zero |= ((RHSKnown.Zero.getZExtValue() >> SelBits) & 0xff) << I;
4516       } else if (SelBits < 7) {
4517         SelBits = (SelBits & 3) * 8;
4518         Known.One |= ((LHSKnown.One.getZExtValue() >> SelBits) & 0xff) << I;
4519         Known.Zero |= ((LHSKnown.Zero.getZExtValue() >> SelBits) & 0xff) << I;
4520       } else if (SelBits == 0x0c) {
4521         Known.Zero |= 0xFFull << I;
4522       } else if (SelBits > 0x0c) {
4523         Known.One |= 0xFFull << I;
4524       }
4525       Sel >>= 8;
4526     }
4527     break;
4528   }
4529   case AMDGPUISD::BUFFER_LOAD_UBYTE:  {
4530     Known.Zero.setHighBits(24);
4531     break;
4532   }
4533   case AMDGPUISD::BUFFER_LOAD_USHORT: {
4534     Known.Zero.setHighBits(16);
4535     break;
4536   }
4537   case AMDGPUISD::LDS: {
4538     auto GA = cast<GlobalAddressSDNode>(Op.getOperand(0).getNode());
4539     unsigned Align = GA->getGlobal()->getAlignment();
4540 
4541     Known.Zero.setHighBits(16);
4542     if (Align)
4543       Known.Zero.setLowBits(Log2_32(Align));
4544     break;
4545   }
4546   case ISD::INTRINSIC_WO_CHAIN: {
4547     unsigned IID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4548     switch (IID) {
4549     case Intrinsic::amdgcn_mbcnt_lo:
4550     case Intrinsic::amdgcn_mbcnt_hi: {
4551       const GCNSubtarget &ST =
4552           DAG.getMachineFunction().getSubtarget<GCNSubtarget>();
4553       // These return at most the wavefront size - 1.
4554       unsigned Size = Op.getValueType().getSizeInBits();
4555       Known.Zero.setHighBits(Size - ST.getWavefrontSizeLog2());
4556       break;
4557     }
4558     default:
4559       break;
4560     }
4561   }
4562   }
4563 }
4564 
4565 unsigned AMDGPUTargetLowering::ComputeNumSignBitsForTargetNode(
4566     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4567     unsigned Depth) const {
4568   switch (Op.getOpcode()) {
4569   case AMDGPUISD::BFE_I32: {
4570     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4571     if (!Width)
4572       return 1;
4573 
4574     unsigned SignBits = 32 - Width->getZExtValue() + 1;
4575     if (!isNullConstant(Op.getOperand(1)))
4576       return SignBits;
4577 
4578     // TODO: Could probably figure something out with non-0 offsets.
4579     unsigned Op0SignBits = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4580     return std::max(SignBits, Op0SignBits);
4581   }
4582 
4583   case AMDGPUISD::BFE_U32: {
4584     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4585     return Width ? 32 - (Width->getZExtValue() & 0x1f) : 1;
4586   }
4587 
4588   case AMDGPUISD::CARRY:
4589   case AMDGPUISD::BORROW:
4590     return 31;
4591   case AMDGPUISD::BUFFER_LOAD_BYTE:
4592     return 25;
4593   case AMDGPUISD::BUFFER_LOAD_SHORT:
4594     return 17;
4595   case AMDGPUISD::BUFFER_LOAD_UBYTE:
4596     return 24;
4597   case AMDGPUISD::BUFFER_LOAD_USHORT:
4598     return 16;
4599   case AMDGPUISD::FP_TO_FP16:
4600   case AMDGPUISD::FP16_ZEXT:
4601     return 16;
4602   default:
4603     return 1;
4604   }
4605 }
4606 
4607 bool AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
4608                                                         const SelectionDAG &DAG,
4609                                                         bool SNaN,
4610                                                         unsigned Depth) const {
4611   unsigned Opcode = Op.getOpcode();
4612   switch (Opcode) {
4613   case AMDGPUISD::FMIN_LEGACY:
4614   case AMDGPUISD::FMAX_LEGACY: {
4615     if (SNaN)
4616       return true;
4617 
4618     // TODO: Can check no nans on one of the operands for each one, but which
4619     // one?
4620     return false;
4621   }
4622   case AMDGPUISD::FMUL_LEGACY:
4623   case AMDGPUISD::CVT_PKRTZ_F16_F32: {
4624     if (SNaN)
4625       return true;
4626     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4627            DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4628   }
4629   case AMDGPUISD::FMED3:
4630   case AMDGPUISD::FMIN3:
4631   case AMDGPUISD::FMAX3:
4632   case AMDGPUISD::FMAD_FTZ: {
4633     if (SNaN)
4634       return true;
4635     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4636            DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4637            DAG.isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4638   }
4639   case AMDGPUISD::CVT_F32_UBYTE0:
4640   case AMDGPUISD::CVT_F32_UBYTE1:
4641   case AMDGPUISD::CVT_F32_UBYTE2:
4642   case AMDGPUISD::CVT_F32_UBYTE3:
4643     return true;
4644 
4645   case AMDGPUISD::RCP:
4646   case AMDGPUISD::RSQ:
4647   case AMDGPUISD::RCP_LEGACY:
4648   case AMDGPUISD::RSQ_LEGACY:
4649   case AMDGPUISD::RSQ_CLAMP: {
4650     if (SNaN)
4651       return true;
4652 
4653     // TODO: Need is known positive check.
4654     return false;
4655   }
4656   case AMDGPUISD::LDEXP:
4657   case AMDGPUISD::FRACT: {
4658     if (SNaN)
4659       return true;
4660     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4661   }
4662   case AMDGPUISD::DIV_SCALE:
4663   case AMDGPUISD::DIV_FMAS:
4664   case AMDGPUISD::DIV_FIXUP:
4665   case AMDGPUISD::TRIG_PREOP:
4666     // TODO: Refine on operands.
4667     return SNaN;
4668   case AMDGPUISD::SIN_HW:
4669   case AMDGPUISD::COS_HW: {
4670     // TODO: Need check for infinity
4671     return SNaN;
4672   }
4673   case ISD::INTRINSIC_WO_CHAIN: {
4674     unsigned IntrinsicID
4675       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4676     // TODO: Handle more intrinsics
4677     switch (IntrinsicID) {
4678     case Intrinsic::amdgcn_cubeid:
4679       return true;
4680 
4681     case Intrinsic::amdgcn_frexp_mant: {
4682       if (SNaN)
4683         return true;
4684       return DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4685     }
4686     case Intrinsic::amdgcn_cvt_pkrtz: {
4687       if (SNaN)
4688         return true;
4689       return DAG.isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4690              DAG.isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4691     }
4692     case Intrinsic::amdgcn_fdot2:
4693       // TODO: Refine on operand
4694       return SNaN;
4695     default:
4696       return false;
4697     }
4698   }
4699   default:
4700     return false;
4701   }
4702 }
4703 
4704 TargetLowering::AtomicExpansionKind
4705 AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
4706   switch (RMW->getOperation()) {
4707   case AtomicRMWInst::Nand:
4708   case AtomicRMWInst::FAdd:
4709   case AtomicRMWInst::FSub:
4710     return AtomicExpansionKind::CmpXChg;
4711   default:
4712     return AtomicExpansionKind::None;
4713   }
4714 }
4715