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