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