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