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