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