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