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