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