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