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