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