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