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