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