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