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