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