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