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