1 //===-- X86TargetTransformInfo.cpp - X86 specific TTI pass ----------------===//
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 /// \file
10 /// This file implements a TargetTransformInfo analysis pass specific to the
11 /// X86 target machine. It uses the target's detailed information to provide
12 /// more precise answers to certain TTI queries, while letting the target
13 /// independent and default TTI implementations handle the rest.
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "X86TargetTransformInfo.h"
18 #include "llvm/Analysis/TargetTransformInfo.h"
19 #include "llvm/CodeGen/BasicTTIImpl.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Target/CostTable.h"
23 #include "llvm/Target/TargetLowering.h"
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "x86tti"
28 
29 //===----------------------------------------------------------------------===//
30 //
31 // X86 cost model.
32 //
33 //===----------------------------------------------------------------------===//
34 
35 TargetTransformInfo::PopcntSupportKind
36 X86TTIImpl::getPopcntSupport(unsigned TyWidth) {
37   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
38   // TODO: Currently the __builtin_popcount() implementation using SSE3
39   //   instructions is inefficient. Once the problem is fixed, we should
40   //   call ST->hasSSE3() instead of ST->hasPOPCNT().
41   return ST->hasPOPCNT() ? TTI::PSK_FastHardware : TTI::PSK_Software;
42 }
43 
44 unsigned X86TTIImpl::getNumberOfRegisters(bool Vector) {
45   if (Vector && !ST->hasSSE1())
46     return 0;
47 
48   if (ST->is64Bit()) {
49     if (Vector && ST->hasAVX512())
50       return 32;
51     return 16;
52   }
53   return 8;
54 }
55 
56 unsigned X86TTIImpl::getRegisterBitWidth(bool Vector) {
57   if (Vector) {
58     if (ST->hasAVX512()) return 512;
59     if (ST->hasAVX()) return 256;
60     if (ST->hasSSE1()) return 128;
61     return 0;
62   }
63 
64   if (ST->is64Bit())
65     return 64;
66 
67   return 32;
68 }
69 
70 unsigned X86TTIImpl::getMaxInterleaveFactor(unsigned VF) {
71   // If the loop will not be vectorized, don't interleave the loop.
72   // Let regular unroll to unroll the loop, which saves the overflow
73   // check and memory check cost.
74   if (VF == 1)
75     return 1;
76 
77   if (ST->isAtom())
78     return 1;
79 
80   // Sandybridge and Haswell have multiple execution ports and pipelined
81   // vector units.
82   if (ST->hasAVX())
83     return 4;
84 
85   return 2;
86 }
87 
88 int X86TTIImpl::getArithmeticInstrCost(
89     unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
90     TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
91     TTI::OperandValueProperties Opd2PropInfo) {
92   // Legalize the type.
93   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
94 
95   int ISD = TLI->InstructionOpcodeToISD(Opcode);
96   assert(ISD && "Invalid opcode");
97 
98   if (ISD == ISD::SDIV &&
99       Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
100       Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
101     // On X86, vector signed division by constants power-of-two are
102     // normally expanded to the sequence SRA + SRL + ADD + SRA.
103     // The OperandValue properties many not be same as that of previous
104     // operation;conservatively assume OP_None.
105     int Cost = 2 * getArithmeticInstrCost(Instruction::AShr, Ty, Op1Info,
106                                           Op2Info, TargetTransformInfo::OP_None,
107                                           TargetTransformInfo::OP_None);
108     Cost += getArithmeticInstrCost(Instruction::LShr, Ty, Op1Info, Op2Info,
109                                    TargetTransformInfo::OP_None,
110                                    TargetTransformInfo::OP_None);
111     Cost += getArithmeticInstrCost(Instruction::Add, Ty, Op1Info, Op2Info,
112                                    TargetTransformInfo::OP_None,
113                                    TargetTransformInfo::OP_None);
114 
115     return Cost;
116   }
117 
118   static const CostTblEntry AVX2UniformConstCostTable[] = {
119     { ISD::SRA,  MVT::v4i64,   4 }, // 2 x psrad + shuffle.
120 
121     { ISD::SDIV, MVT::v16i16,  6 }, // vpmulhw sequence
122     { ISD::UDIV, MVT::v16i16,  6 }, // vpmulhuw sequence
123     { ISD::SDIV, MVT::v8i32,  15 }, // vpmuldq sequence
124     { ISD::UDIV, MVT::v8i32,  15 }, // vpmuludq sequence
125   };
126 
127   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
128       ST->hasAVX2()) {
129     if (const auto *Entry = CostTableLookup(AVX2UniformConstCostTable, ISD,
130                                             LT.second))
131       return LT.first * Entry->Cost;
132   }
133 
134   static const CostTblEntry AVX512CostTable[] = {
135     { ISD::SHL,     MVT::v16i32,    1 },
136     { ISD::SRL,     MVT::v16i32,    1 },
137     { ISD::SRA,     MVT::v16i32,    1 },
138     { ISD::SHL,     MVT::v8i64,    1 },
139     { ISD::SRL,     MVT::v8i64,    1 },
140     { ISD::SRA,     MVT::v8i64,    1 },
141   };
142 
143   if (ST->hasAVX512()) {
144     if (const auto *Entry = CostTableLookup(AVX512CostTable, ISD, LT.second))
145       return LT.first * Entry->Cost;
146   }
147 
148   static const CostTblEntry AVX2CostTable[] = {
149     // Shifts on v4i64/v8i32 on AVX2 is legal even though we declare to
150     // customize them to detect the cases where shift amount is a scalar one.
151     { ISD::SHL,     MVT::v4i32,    1 },
152     { ISD::SRL,     MVT::v4i32,    1 },
153     { ISD::SRA,     MVT::v4i32,    1 },
154     { ISD::SHL,     MVT::v8i32,    1 },
155     { ISD::SRL,     MVT::v8i32,    1 },
156     { ISD::SRA,     MVT::v8i32,    1 },
157     { ISD::SHL,     MVT::v2i64,    1 },
158     { ISD::SRL,     MVT::v2i64,    1 },
159     { ISD::SHL,     MVT::v4i64,    1 },
160     { ISD::SRL,     MVT::v4i64,    1 },
161   };
162 
163   // Look for AVX2 lowering tricks.
164   if (ST->hasAVX2()) {
165     if (ISD == ISD::SHL && LT.second == MVT::v16i16 &&
166         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
167          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
168       // On AVX2, a packed v16i16 shift left by a constant build_vector
169       // is lowered into a vector multiply (vpmullw).
170       return LT.first;
171 
172     if (const auto *Entry = CostTableLookup(AVX2CostTable, ISD, LT.second))
173       return LT.first * Entry->Cost;
174   }
175 
176   static const CostTblEntry XOPCostTable[] = {
177     // 128bit shifts take 1cy, but right shifts require negation beforehand.
178     { ISD::SHL,     MVT::v16i8,    1 },
179     { ISD::SRL,     MVT::v16i8,    2 },
180     { ISD::SRA,     MVT::v16i8,    2 },
181     { ISD::SHL,     MVT::v8i16,    1 },
182     { ISD::SRL,     MVT::v8i16,    2 },
183     { ISD::SRA,     MVT::v8i16,    2 },
184     { ISD::SHL,     MVT::v4i32,    1 },
185     { ISD::SRL,     MVT::v4i32,    2 },
186     { ISD::SRA,     MVT::v4i32,    2 },
187     { ISD::SHL,     MVT::v2i64,    1 },
188     { ISD::SRL,     MVT::v2i64,    2 },
189     { ISD::SRA,     MVT::v2i64,    2 },
190     // 256bit shifts require splitting if AVX2 didn't catch them above.
191     { ISD::SHL,     MVT::v32i8,    2 },
192     { ISD::SRL,     MVT::v32i8,    4 },
193     { ISD::SRA,     MVT::v32i8,    4 },
194     { ISD::SHL,     MVT::v16i16,   2 },
195     { ISD::SRL,     MVT::v16i16,   4 },
196     { ISD::SRA,     MVT::v16i16,   4 },
197     { ISD::SHL,     MVT::v8i32,    2 },
198     { ISD::SRL,     MVT::v8i32,    4 },
199     { ISD::SRA,     MVT::v8i32,    4 },
200     { ISD::SHL,     MVT::v4i64,    2 },
201     { ISD::SRL,     MVT::v4i64,    4 },
202     { ISD::SRA,     MVT::v4i64,    4 },
203   };
204 
205   // Look for XOP lowering tricks.
206   if (ST->hasXOP()) {
207     if (const auto *Entry = CostTableLookup(XOPCostTable, ISD, LT.second))
208       return LT.first * Entry->Cost;
209   }
210 
211   static const CostTblEntry AVX2CustomCostTable[] = {
212     { ISD::SHL,  MVT::v32i8,      11 }, // vpblendvb sequence.
213     { ISD::SHL,  MVT::v16i16,     10 }, // extend/vpsrlvd/pack sequence.
214 
215     { ISD::SRL,  MVT::v32i8,      11 }, // vpblendvb sequence.
216     { ISD::SRL,  MVT::v16i16,     10 }, // extend/vpsrlvd/pack sequence.
217 
218     { ISD::SRA,  MVT::v32i8,      24 }, // vpblendvb sequence.
219     { ISD::SRA,  MVT::v16i16,     10 }, // extend/vpsravd/pack sequence.
220     { ISD::SRA,  MVT::v2i64,       4 }, // srl/xor/sub sequence.
221     { ISD::SRA,  MVT::v4i64,       4 }, // srl/xor/sub sequence.
222 
223     // Vectorizing division is a bad idea. See the SSE2 table for more comments.
224     { ISD::SDIV,  MVT::v32i8,  32*20 },
225     { ISD::SDIV,  MVT::v16i16, 16*20 },
226     { ISD::SDIV,  MVT::v8i32,  8*20 },
227     { ISD::SDIV,  MVT::v4i64,  4*20 },
228     { ISD::UDIV,  MVT::v32i8,  32*20 },
229     { ISD::UDIV,  MVT::v16i16, 16*20 },
230     { ISD::UDIV,  MVT::v8i32,  8*20 },
231     { ISD::UDIV,  MVT::v4i64,  4*20 },
232   };
233 
234   // Look for AVX2 lowering tricks for custom cases.
235   if (ST->hasAVX2()) {
236     if (const auto *Entry = CostTableLookup(AVX2CustomCostTable, ISD,
237                                             LT.second))
238       return LT.first * Entry->Cost;
239   }
240 
241   static const CostTblEntry
242   SSE2UniformConstCostTable[] = {
243     // Constant splats are cheaper for the following instructions.
244     { ISD::SDIV, MVT::v8i16,  6 }, // pmulhw sequence
245     { ISD::UDIV, MVT::v8i16,  6 }, // pmulhuw sequence
246     { ISD::SDIV, MVT::v4i32, 19 }, // pmuludq sequence
247     { ISD::UDIV, MVT::v4i32, 15 }, // pmuludq sequence
248   };
249 
250   static const CostTblEntry
251   SSE2UniformCostTable[] = {
252     // Uniform splats are cheaper for the following instructions.
253     { ISD::SHL,  MVT::v16i8,  1 }, // psllw.
254     { ISD::SHL,  MVT::v32i8,  2 }, // psllw.
255     { ISD::SHL,  MVT::v8i16,  1 }, // psllw.
256     { ISD::SHL,  MVT::v16i16, 2 }, // psllw.
257     { ISD::SHL,  MVT::v4i32,  1 }, // pslld
258     { ISD::SHL,  MVT::v8i32,  2 }, // pslld
259     { ISD::SHL,  MVT::v2i64,  1 }, // psllq.
260     { ISD::SHL,  MVT::v4i64,  2 }, // psllq.
261 
262     { ISD::SRL,  MVT::v16i8,  1 }, // psrlw.
263     { ISD::SRL,  MVT::v32i8,  2 }, // psrlw.
264     { ISD::SRL,  MVT::v8i16,  1 }, // psrlw.
265     { ISD::SRL,  MVT::v16i16, 2 }, // psrlw.
266     { ISD::SRL,  MVT::v4i32,  1 }, // psrld.
267     { ISD::SRL,  MVT::v8i32,  2 }, // psrld.
268     { ISD::SRL,  MVT::v2i64,  1 }, // psrlq.
269     { ISD::SRL,  MVT::v4i64,  2 }, // psrlq.
270 
271     { ISD::SRA,  MVT::v16i8,  4 }, // psrlw, pand, pxor, psubb.
272     { ISD::SRA,  MVT::v32i8,  8 }, // psrlw, pand, pxor, psubb.
273     { ISD::SRA,  MVT::v8i16,  1 }, // psraw.
274     { ISD::SRA,  MVT::v16i16, 2 }, // psraw.
275     { ISD::SRA,  MVT::v4i32,  1 }, // psrad.
276     { ISD::SRA,  MVT::v8i32,  2 }, // psrad.
277     { ISD::SRA,  MVT::v2i64,  4 }, // 2 x psrad + shuffle.
278     { ISD::SRA,  MVT::v4i64,  8 }, // 2 x psrad + shuffle.
279   };
280 
281   if (ST->hasSSE2() &&
282       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
283        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
284     if (Op2Info == TargetTransformInfo::OK_UniformConstantValue) {
285       // pmuldq sequence.
286       if (ISD == ISD::SDIV && LT.second == MVT::v4i32 && ST->hasSSE41())
287         return LT.first * 15;
288       if (const auto *Entry =
289               CostTableLookup(SSE2UniformConstCostTable, ISD, LT.second))
290         return LT.first * Entry->Cost;
291     }
292     if (const auto *Entry =
293             CostTableLookup(SSE2UniformCostTable, ISD, LT.second))
294       return LT.first * Entry->Cost;
295   }
296 
297   if (ISD == ISD::SHL &&
298       Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) {
299     MVT VT = LT.second;
300     // Vector shift left by non uniform constant can be lowered
301     // into vector multiply (pmullw/pmulld).
302     if ((VT == MVT::v8i16 && ST->hasSSE2()) ||
303         (VT == MVT::v4i32 && ST->hasSSE41()))
304       return LT.first;
305 
306     // v16i16 and v8i32 shifts by non-uniform constants are lowered into a
307     // sequence of extract + two vector multiply + insert.
308     if ((VT == MVT::v8i32 || VT == MVT::v16i16) &&
309        (ST->hasAVX() && !ST->hasAVX2()))
310       ISD = ISD::MUL;
311 
312     // A vector shift left by non uniform constant is converted
313     // into a vector multiply; the new multiply is eventually
314     // lowered into a sequence of shuffles and 2 x pmuludq.
315     if (VT == MVT::v4i32 && ST->hasSSE2())
316       ISD = ISD::MUL;
317   }
318 
319   static const CostTblEntry SSE2CostTable[] = {
320     // We don't correctly identify costs of casts because they are marked as
321     // custom.
322     { ISD::SHL,  MVT::v16i8,    26 }, // cmpgtb sequence.
323     { ISD::SHL,  MVT::v32i8,  2*26 }, // cmpgtb sequence.
324     { ISD::SHL,  MVT::v8i16,    32 }, // cmpgtb sequence.
325     { ISD::SHL,  MVT::v16i16, 2*32 }, // cmpgtb sequence.
326     { ISD::SHL,  MVT::v4i32,   2*5 }, // We optimized this using mul.
327     { ISD::SHL,  MVT::v8i32, 2*2*5 }, // We optimized this using mul.
328     { ISD::SHL,  MVT::v2i64,     4 }, // splat+shuffle sequence.
329     { ISD::SHL,  MVT::v4i64,   2*4 }, // splat+shuffle sequence.
330 
331     { ISD::SRL,  MVT::v16i8,    26 }, // cmpgtb sequence.
332     { ISD::SRL,  MVT::v32i8,  2*26 }, // cmpgtb sequence.
333     { ISD::SRL,  MVT::v8i16,    32 }, // cmpgtb sequence.
334     { ISD::SRL,  MVT::v16i16, 2*32 }, // cmpgtb sequence.
335     { ISD::SRL,  MVT::v4i32,    16 }, // Shift each lane + blend.
336     { ISD::SRL,  MVT::v8i32,  2*16 }, // Shift each lane + blend.
337     { ISD::SRL,  MVT::v2i64,     4 }, // splat+shuffle sequence.
338     { ISD::SRL,  MVT::v4i64,   2*4 }, // splat+shuffle sequence.
339 
340     { ISD::SRA,  MVT::v16i8,    54 }, // unpacked cmpgtb sequence.
341     { ISD::SRA,  MVT::v32i8,  2*54 }, // unpacked cmpgtb sequence.
342     { ISD::SRA,  MVT::v8i16,    32 }, // cmpgtb sequence.
343     { ISD::SRA,  MVT::v16i16, 2*32 }, // cmpgtb sequence.
344     { ISD::SRA,  MVT::v4i32,    16 }, // Shift each lane + blend.
345     { ISD::SRA,  MVT::v8i32,  2*16 }, // Shift each lane + blend.
346     { ISD::SRA,  MVT::v2i64,    12 }, // srl/xor/sub sequence.
347     { ISD::SRA,  MVT::v4i64,  2*12 }, // srl/xor/sub sequence.
348 
349     // It is not a good idea to vectorize division. We have to scalarize it and
350     // in the process we will often end up having to spilling regular
351     // registers. The overhead of division is going to dominate most kernels
352     // anyways so try hard to prevent vectorization of division - it is
353     // generally a bad idea. Assume somewhat arbitrarily that we have to be able
354     // to hide "20 cycles" for each lane.
355     { ISD::SDIV,  MVT::v16i8,  16*20 },
356     { ISD::SDIV,  MVT::v8i16,  8*20 },
357     { ISD::SDIV,  MVT::v4i32,  4*20 },
358     { ISD::SDIV,  MVT::v2i64,  2*20 },
359     { ISD::UDIV,  MVT::v16i8,  16*20 },
360     { ISD::UDIV,  MVT::v8i16,  8*20 },
361     { ISD::UDIV,  MVT::v4i32,  4*20 },
362     { ISD::UDIV,  MVT::v2i64,  2*20 },
363   };
364 
365   if (ST->hasSSE2()) {
366     if (const auto *Entry = CostTableLookup(SSE2CostTable, ISD, LT.second))
367       return LT.first * Entry->Cost;
368   }
369 
370   static const CostTblEntry AVX1CostTable[] = {
371     // We don't have to scalarize unsupported ops. We can issue two half-sized
372     // operations and we only need to extract the upper YMM half.
373     // Two ops + 1 extract + 1 insert = 4.
374     { ISD::MUL,     MVT::v16i16,   4 },
375     { ISD::MUL,     MVT::v8i32,    4 },
376     { ISD::SUB,     MVT::v8i32,    4 },
377     { ISD::ADD,     MVT::v8i32,    4 },
378     { ISD::SUB,     MVT::v4i64,    4 },
379     { ISD::ADD,     MVT::v4i64,    4 },
380     // A v4i64 multiply is custom lowered as two split v2i64 vectors that then
381     // are lowered as a series of long multiplies(3), shifts(4) and adds(2)
382     // Because we believe v4i64 to be a legal type, we must also include the
383     // split factor of two in the cost table. Therefore, the cost here is 18
384     // instead of 9.
385     { ISD::MUL,     MVT::v4i64,    18 },
386   };
387 
388   // Look for AVX1 lowering tricks.
389   if (ST->hasAVX() && !ST->hasAVX2()) {
390     MVT VT = LT.second;
391 
392     if (const auto *Entry = CostTableLookup(AVX1CostTable, ISD, VT))
393       return LT.first * Entry->Cost;
394   }
395 
396   // Custom lowering of vectors.
397   static const CostTblEntry CustomLowered[] = {
398     // A v2i64/v4i64 and multiply is custom lowered as a series of long
399     // multiplies(3), shifts(4) and adds(2).
400     { ISD::MUL,     MVT::v2i64,    9 },
401     { ISD::MUL,     MVT::v4i64,    9 },
402   };
403   if (const auto *Entry = CostTableLookup(CustomLowered, ISD, LT.second))
404     return LT.first * Entry->Cost;
405 
406   // Special lowering of v4i32 mul on sse2, sse3: Lower v4i32 mul as 2x shuffle,
407   // 2x pmuludq, 2x shuffle.
408   if (ISD == ISD::MUL && LT.second == MVT::v4i32 && ST->hasSSE2() &&
409       !ST->hasSSE41())
410     return LT.first * 6;
411 
412   // Fallback to the default implementation.
413   return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info);
414 }
415 
416 int X86TTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
417                                Type *SubTp) {
418   // We only estimate the cost of reverse and alternate shuffles.
419   if (Kind != TTI::SK_Reverse && Kind != TTI::SK_Alternate)
420     return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
421 
422   if (Kind == TTI::SK_Reverse) {
423     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
424     int Cost = 1;
425     if (LT.second.getSizeInBits() > 128)
426       Cost = 3; // Extract + insert + copy.
427 
428     // Multiple by the number of parts.
429     return Cost * LT.first;
430   }
431 
432   if (Kind == TTI::SK_Alternate) {
433     // 64-bit packed float vectors (v2f32) are widened to type v4f32.
434     // 64-bit packed integer vectors (v2i32) are promoted to type v2i64.
435     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
436 
437     // The backend knows how to generate a single VEX.256 version of
438     // instruction VPBLENDW if the target supports AVX2.
439     if (ST->hasAVX2() && LT.second == MVT::v16i16)
440       return LT.first;
441 
442     static const CostTblEntry AVXAltShuffleTbl[] = {
443       {ISD::VECTOR_SHUFFLE, MVT::v4i64, 1},  // vblendpd
444       {ISD::VECTOR_SHUFFLE, MVT::v4f64, 1},  // vblendpd
445 
446       {ISD::VECTOR_SHUFFLE, MVT::v8i32, 1},  // vblendps
447       {ISD::VECTOR_SHUFFLE, MVT::v8f32, 1},  // vblendps
448 
449       // This shuffle is custom lowered into a sequence of:
450       //  2x  vextractf128 , 2x vpblendw , 1x vinsertf128
451       {ISD::VECTOR_SHUFFLE, MVT::v16i16, 5},
452 
453       // This shuffle is custom lowered into a long sequence of:
454       //  2x vextractf128 , 4x vpshufb , 2x vpor ,  1x vinsertf128
455       {ISD::VECTOR_SHUFFLE, MVT::v32i8, 9}
456     };
457 
458     if (ST->hasAVX())
459       if (const auto *Entry = CostTableLookup(AVXAltShuffleTbl,
460                                               ISD::VECTOR_SHUFFLE, LT.second))
461         return LT.first * Entry->Cost;
462 
463     static const CostTblEntry SSE41AltShuffleTbl[] = {
464       // These are lowered into movsd.
465       {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
466       {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
467 
468       // packed float vectors with four elements are lowered into BLENDI dag
469       // nodes. A v4i32/v4f32 BLENDI generates a single 'blendps'/'blendpd'.
470       {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
471       {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
472 
473       // This shuffle generates a single pshufw.
474       {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
475 
476       // There is no instruction that matches a v16i8 alternate shuffle.
477       // The backend will expand it into the sequence 'pshufb + pshufb + or'.
478       {ISD::VECTOR_SHUFFLE, MVT::v16i8, 3}
479     };
480 
481     if (ST->hasSSE41())
482       if (const auto *Entry = CostTableLookup(SSE41AltShuffleTbl, ISD::VECTOR_SHUFFLE,
483                                               LT.second))
484         return LT.first * Entry->Cost;
485 
486     static const CostTblEntry SSSE3AltShuffleTbl[] = {
487       {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},  // movsd
488       {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},  // movsd
489 
490       // SSE3 doesn't have 'blendps'. The following shuffles are expanded into
491       // the sequence 'shufps + pshufd'
492       {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
493       {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
494 
495       {ISD::VECTOR_SHUFFLE, MVT::v8i16, 3}, // pshufb + pshufb + or
496       {ISD::VECTOR_SHUFFLE, MVT::v16i8, 3}  // pshufb + pshufb + or
497     };
498 
499     if (ST->hasSSSE3())
500       if (const auto *Entry = CostTableLookup(SSSE3AltShuffleTbl,
501                                               ISD::VECTOR_SHUFFLE, LT.second))
502         return LT.first * Entry->Cost;
503 
504     static const CostTblEntry SSEAltShuffleTbl[] = {
505       {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},  // movsd
506       {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},  // movsd
507 
508       {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2}, // shufps + pshufd
509       {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2}, // shufps + pshufd
510 
511       // This is expanded into a long sequence of four extract + four insert.
512       {ISD::VECTOR_SHUFFLE, MVT::v8i16, 8}, // 4 x pextrw + 4 pinsrw.
513 
514       // 8 x (pinsrw + pextrw + and + movb + movzb + or)
515       {ISD::VECTOR_SHUFFLE, MVT::v16i8, 48}
516     };
517 
518     // Fall-back (SSE3 and SSE2).
519     if (const auto *Entry = CostTableLookup(SSEAltShuffleTbl,
520                                             ISD::VECTOR_SHUFFLE, LT.second))
521       return LT.first * Entry->Cost;
522     return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
523   }
524 
525   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
526 }
527 
528 int X86TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) {
529   int ISD = TLI->InstructionOpcodeToISD(Opcode);
530   assert(ISD && "Invalid opcode");
531 
532   // FIXME: Need a better design of the cost table to handle non-simple types of
533   // potential massive combinations (elem_num x src_type x dst_type).
534 
535   static const TypeConversionCostTblEntry AVX512DQConversionTbl[] = {
536     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  1 },
537     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  1 },
538     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i64,  1 },
539     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64,  1 },
540     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i64,  1 },
541     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i64,  1 },
542 
543     { ISD::FP_TO_UINT,  MVT::v2i64, MVT::v2f32, 1 },
544     { ISD::FP_TO_UINT,  MVT::v4i64, MVT::v4f32, 1 },
545     { ISD::FP_TO_UINT,  MVT::v8i64, MVT::v8f32, 1 },
546     { ISD::FP_TO_UINT,  MVT::v2i64, MVT::v2f64, 1 },
547     { ISD::FP_TO_UINT,  MVT::v4i64, MVT::v4f64, 1 },
548     { ISD::FP_TO_UINT,  MVT::v8i64, MVT::v8f64, 1 },
549   };
550 
551   // TODO: For AVX512DQ + AVX512VL, we also have cheap casts for 128-bit and
552   // 256-bit wide vectors.
553 
554   static const TypeConversionCostTblEntry AVX512FConversionTbl[] = {
555     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v8f32,  1 },
556     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v16f32, 3 },
557     { ISD::FP_ROUND,  MVT::v8f32,   MVT::v8f64,  1 },
558 
559     { ISD::TRUNCATE,  MVT::v16i8,   MVT::v16i32, 1 },
560     { ISD::TRUNCATE,  MVT::v16i16,  MVT::v16i32, 1 },
561     { ISD::TRUNCATE,  MVT::v8i16,   MVT::v8i64,  1 },
562     { ISD::TRUNCATE,  MVT::v8i32,   MVT::v8i64,  1 },
563 
564     // v16i1 -> v16i32 - load + broadcast
565     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i1,  2 },
566     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i1,  2 },
567     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
568     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
569     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
570     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
571     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i16,  1 },
572     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i16,  1 },
573     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i32,  1 },
574     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i32,  1 },
575 
576     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i1,   4 },
577     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i1,  3 },
578     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i8,   2 },
579     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i8,  2 },
580     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i16,  2 },
581     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 2 },
582     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 1 },
583     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  1 },
584     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i64, 26 },
585     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i64, 26 },
586 
587     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i1,   4 },
588     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i1,  3 },
589     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i8,   2 },
590     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i8,   2 },
591     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i8,   2 },
592     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i8,   2 },
593     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i8,  2 },
594     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i16,  5 },
595     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i16,  2 },
596     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  2 },
597     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i16,  2 },
598     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i16, 2 },
599     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  2 },
600     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i32,  1 },
601     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  1 },
602     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  1 },
603     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  1 },
604     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  1 },
605     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i32, 1 },
606     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  5 },
607     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  5 },
608     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64, 12 },
609     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i64, 26 },
610 
611     { ISD::FP_TO_UINT,  MVT::v2i32,  MVT::v2f32,  1 },
612     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  1 },
613     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f32,  1 },
614     { ISD::FP_TO_UINT,  MVT::v16i32, MVT::v16f32, 1 },
615   };
616 
617   static const TypeConversionCostTblEntry AVX2ConversionTbl[] = {
618     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
619     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
620     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
621     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
622     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,   3 },
623     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,   3 },
624     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   3 },
625     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   3 },
626     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
627     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
628     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16,  3 },
629     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16,  3 },
630     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
631     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
632     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
633     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
634 
635     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i64,  2 },
636     { ISD::TRUNCATE,    MVT::v4i16,  MVT::v4i64,  2 },
637     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v4i64,  2 },
638     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i32,  2 },
639     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  2 },
640     { ISD::TRUNCATE,    MVT::v8i32,  MVT::v8i64,  4 },
641 
642     { ISD::FP_EXTEND,   MVT::v8f64,  MVT::v8f32,  3 },
643     { ISD::FP_ROUND,    MVT::v8f32,  MVT::v8f64,  3 },
644 
645     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  8 },
646   };
647 
648   static const TypeConversionCostTblEntry AVXConversionTbl[] = {
649     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,  6 },
650     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,  4 },
651     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,  7 },
652     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,  4 },
653     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,  6 },
654     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,  4 },
655     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,  7 },
656     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,  4 },
657     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
658     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
659     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16, 6 },
660     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
661     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16, 4 },
662     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16, 4 },
663     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32, 4 },
664     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32, 4 },
665 
666     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i16, 4 },
667     { ISD::TRUNCATE,    MVT::v8i8,  MVT::v8i32,  4 },
668     { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i32,  5 },
669     { ISD::TRUNCATE,    MVT::v4i8,  MVT::v4i64,  4 },
670     { ISD::TRUNCATE,    MVT::v4i16, MVT::v4i64,  4 },
671     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64,  4 },
672     { ISD::TRUNCATE,    MVT::v8i32, MVT::v8i64,  9 },
673 
674     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i1,  3 },
675     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i1,  3 },
676     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i1,  8 },
677     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8,  3 },
678     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i8,  3 },
679     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i8,  8 },
680     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i16, 3 },
681     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i16, 3 },
682     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i16, 5 },
683     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
684     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i32, 1 },
685     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i32, 1 },
686 
687     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i1,  7 },
688     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i1,  7 },
689     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i1,  6 },
690     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8,  2 },
691     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i8,  2 },
692     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i8,  5 },
693     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
694     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i16, 2 },
695     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i16, 5 },
696     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 6 },
697     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i32, 6 },
698     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i32, 6 },
699     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i32, 9 },
700     // The generic code to compute the scalar overhead is currently broken.
701     // Workaround this limitation by estimating the scalarization overhead
702     // here. We have roughly 10 instructions per scalar element.
703     // Multiply that by the vector width.
704     // FIXME: remove that when PR19268 is fixed.
705     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i64, 10 },
706     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i64, 20 },
707     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i64, 13 },
708     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i64, 13 },
709 
710     { ISD::FP_TO_SINT,  MVT::v4i8,  MVT::v4f32, 1 },
711     { ISD::FP_TO_SINT,  MVT::v8i8,  MVT::v8f32, 7 },
712     // This node is expanded into scalarized operations but BasicTTI is overly
713     // optimistic estimating its cost.  It computes 3 per element (one
714     // vector-extract, one scalar conversion and one vector-insert).  The
715     // problem is that the inserts form a read-modify-write chain so latency
716     // should be factored in too.  Inflating the cost per element by 1.
717     { ISD::FP_TO_UINT,  MVT::v8i32, MVT::v8f32, 8*4 },
718     { ISD::FP_TO_UINT,  MVT::v4i32, MVT::v4f64, 4*4 },
719 
720     { ISD::FP_EXTEND,   MVT::v4f64,  MVT::v4f32,  1 },
721     { ISD::FP_ROUND,    MVT::v4f32,  MVT::v4f64,  1 },
722   };
723 
724   static const TypeConversionCostTblEntry SSE41ConversionTbl[] = {
725     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8,    2 },
726     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8,    2 },
727     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16,   2 },
728     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16,   2 },
729     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32,   2 },
730     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32,   2 },
731 
732     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i8,   1 },
733     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i8,   2 },
734     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i8,   1 },
735     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i8,   1 },
736     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i8,   1 },
737     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i8,   1 },
738     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   2 },
739     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   2 },
740     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
741     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
742     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  4 },
743     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  4 },
744     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i16,  1 },
745     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i16,  1 },
746     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
747     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
748     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
749     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
750 
751     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i16,  2 },
752     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i16,  1 },
753     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i32,  1 },
754     { ISD::TRUNCATE,    MVT::v4i16,  MVT::v4i32,  1 },
755     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i32,  3 },
756     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  3 },
757     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32, 6 },
758 
759   };
760 
761   static const TypeConversionCostTblEntry SSE2ConversionTbl[] = {
762     // These are somewhat magic numbers justified by looking at the output of
763     // Intel's IACA, running some kernels and making sure when we take
764     // legalization into account the throughput will be overestimated.
765     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
766     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
767     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
768     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
769     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 5 },
770     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
771     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
772     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
773 
774     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
775     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
776     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
777     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
778     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
779     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 8 },
780     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
781     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
782 
783     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i8,   1 },
784     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i8,   6 },
785     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i8,   2 },
786     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i8,   3 },
787     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,   4 },
788     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,   8 },
789     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i8,   1 },
790     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i8,   2 },
791     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   6 },
792     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   6 },
793     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  3 },
794     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  4 },
795     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  9 },
796     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  12 },
797     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i16,  1 },
798     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i16,  2 },
799     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16,  3 },
800     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16,  10 },
801     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  3 },
802     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  4 },
803     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 6 },
804     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 8 },
805     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  3 },
806     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  5 },
807 
808     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i16,  4 },
809     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i16,  2 },
810     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 3 },
811     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i32,  3 },
812     { ISD::TRUNCATE,    MVT::v4i16,  MVT::v4i32,  3 },
813     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i32,  4 },
814     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i32, 7 },
815     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  5 },
816     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32, 10 },
817   };
818 
819   std::pair<int, MVT> LTSrc = TLI->getTypeLegalizationCost(DL, Src);
820   std::pair<int, MVT> LTDest = TLI->getTypeLegalizationCost(DL, Dst);
821 
822   if (ST->hasSSE2() && !ST->hasAVX()) {
823     if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
824                                                    LTDest.second, LTSrc.second))
825       return LTSrc.first * Entry->Cost;
826   }
827 
828   EVT SrcTy = TLI->getValueType(DL, Src);
829   EVT DstTy = TLI->getValueType(DL, Dst);
830 
831   // The function getSimpleVT only handles simple value types.
832   if (!SrcTy.isSimple() || !DstTy.isSimple())
833     return BaseT::getCastInstrCost(Opcode, Dst, Src);
834 
835   if (ST->hasDQI())
836     if (const auto *Entry = ConvertCostTableLookup(AVX512DQConversionTbl, ISD,
837                                                    DstTy.getSimpleVT(),
838                                                    SrcTy.getSimpleVT()))
839       return Entry->Cost;
840 
841   if (ST->hasAVX512())
842     if (const auto *Entry = ConvertCostTableLookup(AVX512FConversionTbl, ISD,
843                                                    DstTy.getSimpleVT(),
844                                                    SrcTy.getSimpleVT()))
845       return Entry->Cost;
846 
847   if (ST->hasAVX2()) {
848     if (const auto *Entry = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
849                                                    DstTy.getSimpleVT(),
850                                                    SrcTy.getSimpleVT()))
851       return Entry->Cost;
852   }
853 
854   if (ST->hasAVX()) {
855     if (const auto *Entry = ConvertCostTableLookup(AVXConversionTbl, ISD,
856                                                    DstTy.getSimpleVT(),
857                                                    SrcTy.getSimpleVT()))
858       return Entry->Cost;
859   }
860 
861   if (ST->hasSSE41()) {
862     if (const auto *Entry = ConvertCostTableLookup(SSE41ConversionTbl, ISD,
863                                                    DstTy.getSimpleVT(),
864                                                    SrcTy.getSimpleVT()))
865       return Entry->Cost;
866   }
867 
868   if (ST->hasSSE2()) {
869     if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
870                                                    DstTy.getSimpleVT(),
871                                                    SrcTy.getSimpleVT()))
872       return Entry->Cost;
873   }
874 
875   return BaseT::getCastInstrCost(Opcode, Dst, Src);
876 }
877 
878 int X86TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
879   // Legalize the type.
880   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
881 
882   MVT MTy = LT.second;
883 
884   int ISD = TLI->InstructionOpcodeToISD(Opcode);
885   assert(ISD && "Invalid opcode");
886 
887   static const CostTblEntry SSE2CostTbl[] = {
888     { ISD::SETCC,   MVT::v2i64,   8 },
889     { ISD::SETCC,   MVT::v4i32,   1 },
890     { ISD::SETCC,   MVT::v8i16,   1 },
891     { ISD::SETCC,   MVT::v16i8,   1 },
892   };
893 
894   static const CostTblEntry SSE42CostTbl[] = {
895     { ISD::SETCC,   MVT::v2f64,   1 },
896     { ISD::SETCC,   MVT::v4f32,   1 },
897     { ISD::SETCC,   MVT::v2i64,   1 },
898   };
899 
900   static const CostTblEntry AVX1CostTbl[] = {
901     { ISD::SETCC,   MVT::v4f64,   1 },
902     { ISD::SETCC,   MVT::v8f32,   1 },
903     // AVX1 does not support 8-wide integer compare.
904     { ISD::SETCC,   MVT::v4i64,   4 },
905     { ISD::SETCC,   MVT::v8i32,   4 },
906     { ISD::SETCC,   MVT::v16i16,  4 },
907     { ISD::SETCC,   MVT::v32i8,   4 },
908   };
909 
910   static const CostTblEntry AVX2CostTbl[] = {
911     { ISD::SETCC,   MVT::v4i64,   1 },
912     { ISD::SETCC,   MVT::v8i32,   1 },
913     { ISD::SETCC,   MVT::v16i16,  1 },
914     { ISD::SETCC,   MVT::v32i8,   1 },
915   };
916 
917   static const CostTblEntry AVX512CostTbl[] = {
918     { ISD::SETCC,   MVT::v8i64,   1 },
919     { ISD::SETCC,   MVT::v16i32,  1 },
920     { ISD::SETCC,   MVT::v8f64,   1 },
921     { ISD::SETCC,   MVT::v16f32,  1 },
922   };
923 
924   if (ST->hasAVX512())
925     if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
926       return LT.first * Entry->Cost;
927 
928   if (ST->hasAVX2())
929     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
930       return LT.first * Entry->Cost;
931 
932   if (ST->hasAVX())
933     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
934       return LT.first * Entry->Cost;
935 
936   if (ST->hasSSE42())
937     if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
938       return LT.first * Entry->Cost;
939 
940   if (ST->hasSSE2())
941     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
942       return LT.first * Entry->Cost;
943 
944   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy);
945 }
946 
947 int X86TTIImpl::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
948                                       ArrayRef<Type *> Tys, FastMathFlags FMF) {
949   // Costs should match the codegen from:
950   // BITREVERSE: llvm\test\CodeGen\X86\vector-bitreverse.ll
951   // BSWAP: llvm\test\CodeGen\X86\bswap-vector.ll
952   // CTLZ: llvm\test\CodeGen\X86\vector-lzcnt-*.ll
953   // CTPOP: llvm\test\CodeGen\X86\vector-popcnt-*.ll
954   // CTTZ: llvm\test\CodeGen\X86\vector-tzcnt-*.ll
955   static const CostTblEntry XOPCostTbl[] = {
956     { ISD::BITREVERSE, MVT::v4i64,   4 },
957     { ISD::BITREVERSE, MVT::v8i32,   4 },
958     { ISD::BITREVERSE, MVT::v16i16,  4 },
959     { ISD::BITREVERSE, MVT::v32i8,   4 },
960     { ISD::BITREVERSE, MVT::v2i64,   1 },
961     { ISD::BITREVERSE, MVT::v4i32,   1 },
962     { ISD::BITREVERSE, MVT::v8i16,   1 },
963     { ISD::BITREVERSE, MVT::v16i8,   1 },
964     { ISD::BITREVERSE, MVT::i64,     3 },
965     { ISD::BITREVERSE, MVT::i32,     3 },
966     { ISD::BITREVERSE, MVT::i16,     3 },
967     { ISD::BITREVERSE, MVT::i8,      3 }
968   };
969   static const CostTblEntry AVX2CostTbl[] = {
970     { ISD::BITREVERSE, MVT::v4i64,   5 },
971     { ISD::BITREVERSE, MVT::v8i32,   5 },
972     { ISD::BITREVERSE, MVT::v16i16,  5 },
973     { ISD::BITREVERSE, MVT::v32i8,   5 },
974     { ISD::BSWAP,      MVT::v4i64,   1 },
975     { ISD::BSWAP,      MVT::v8i32,   1 },
976     { ISD::BSWAP,      MVT::v16i16,  1 },
977     { ISD::CTLZ,       MVT::v4i64,  23 },
978     { ISD::CTLZ,       MVT::v8i32,  18 },
979     { ISD::CTLZ,       MVT::v16i16, 14 },
980     { ISD::CTLZ,       MVT::v32i8,   9 },
981     { ISD::CTPOP,      MVT::v4i64,   7 },
982     { ISD::CTPOP,      MVT::v8i32,  11 },
983     { ISD::CTPOP,      MVT::v16i16,  9 },
984     { ISD::CTPOP,      MVT::v32i8,   6 },
985     { ISD::CTTZ,       MVT::v4i64,  10 },
986     { ISD::CTTZ,       MVT::v8i32,  14 },
987     { ISD::CTTZ,       MVT::v16i16, 12 },
988     { ISD::CTTZ,       MVT::v32i8,   9 }
989   };
990   static const CostTblEntry AVX1CostTbl[] = {
991     { ISD::BITREVERSE, MVT::v4i64,  10 },
992     { ISD::BITREVERSE, MVT::v8i32,  10 },
993     { ISD::BITREVERSE, MVT::v16i16, 10 },
994     { ISD::BITREVERSE, MVT::v32i8,  10 },
995     { ISD::BSWAP,      MVT::v4i64,   4 },
996     { ISD::BSWAP,      MVT::v8i32,   4 },
997     { ISD::BSWAP,      MVT::v16i16,  4 },
998     { ISD::CTLZ,       MVT::v4i64,  46 },
999     { ISD::CTLZ,       MVT::v8i32,  36 },
1000     { ISD::CTLZ,       MVT::v16i16, 28 },
1001     { ISD::CTLZ,       MVT::v32i8,  18 },
1002     { ISD::CTPOP,      MVT::v4i64,  14 },
1003     { ISD::CTPOP,      MVT::v8i32,  22 },
1004     { ISD::CTPOP,      MVT::v16i16, 18 },
1005     { ISD::CTPOP,      MVT::v32i8,  12 },
1006     { ISD::CTTZ,       MVT::v4i64,  20 },
1007     { ISD::CTTZ,       MVT::v8i32,  28 },
1008     { ISD::CTTZ,       MVT::v16i16, 24 },
1009     { ISD::CTTZ,       MVT::v32i8,  18 },
1010   };
1011   static const CostTblEntry SSSE3CostTbl[] = {
1012     { ISD::BITREVERSE, MVT::v2i64,   5 },
1013     { ISD::BITREVERSE, MVT::v4i32,   5 },
1014     { ISD::BITREVERSE, MVT::v8i16,   5 },
1015     { ISD::BITREVERSE, MVT::v16i8,   5 },
1016     { ISD::BSWAP,      MVT::v2i64,   1 },
1017     { ISD::BSWAP,      MVT::v4i32,   1 },
1018     { ISD::BSWAP,      MVT::v8i16,   1 },
1019     { ISD::CTLZ,       MVT::v2i64,  23 },
1020     { ISD::CTLZ,       MVT::v4i32,  18 },
1021     { ISD::CTLZ,       MVT::v8i16,  14 },
1022     { ISD::CTLZ,       MVT::v16i8,   9 },
1023     { ISD::CTPOP,      MVT::v2i64,   7 },
1024     { ISD::CTPOP,      MVT::v4i32,  11 },
1025     { ISD::CTPOP,      MVT::v8i16,   9 },
1026     { ISD::CTPOP,      MVT::v16i8,   6 },
1027     { ISD::CTTZ,       MVT::v2i64,  10 },
1028     { ISD::CTTZ,       MVT::v4i32,  14 },
1029     { ISD::CTTZ,       MVT::v8i16,  12 },
1030     { ISD::CTTZ,       MVT::v16i8,   9 }
1031   };
1032   static const CostTblEntry SSE2CostTbl[] = {
1033     { ISD::BSWAP,      MVT::v2i64,   7 },
1034     { ISD::BSWAP,      MVT::v4i32,   7 },
1035     { ISD::BSWAP,      MVT::v8i16,   7 },
1036     /* ISD::CTLZ - currently scalarized pre-SSSE3 */
1037     { ISD::CTPOP,      MVT::v2i64,  12 },
1038     { ISD::CTPOP,      MVT::v4i32,  15 },
1039     { ISD::CTPOP,      MVT::v8i16,  13 },
1040     { ISD::CTPOP,      MVT::v16i8,  10 },
1041     { ISD::CTTZ,       MVT::v2i64,  14 },
1042     { ISD::CTTZ,       MVT::v4i32,  18 },
1043     { ISD::CTTZ,       MVT::v8i16,  16 },
1044     { ISD::CTTZ,       MVT::v16i8,  13 }
1045   };
1046 
1047   unsigned ISD = ISD::DELETED_NODE;
1048   switch (IID) {
1049   default:
1050     break;
1051   case Intrinsic::bitreverse:
1052     ISD = ISD::BITREVERSE;
1053     break;
1054   case Intrinsic::bswap:
1055     ISD = ISD::BSWAP;
1056     break;
1057   case Intrinsic::ctlz:
1058     ISD = ISD::CTLZ;
1059     break;
1060   case Intrinsic::ctpop:
1061     ISD = ISD::CTPOP;
1062     break;
1063   case Intrinsic::cttz:
1064     ISD = ISD::CTTZ;
1065     break;
1066   }
1067 
1068   // Legalize the type.
1069   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
1070   MVT MTy = LT.second;
1071 
1072   // Attempt to lookup cost.
1073   if (ST->hasXOP())
1074     if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
1075       return LT.first * Entry->Cost;
1076 
1077   if (ST->hasAVX2())
1078     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
1079       return LT.first * Entry->Cost;
1080 
1081   if (ST->hasAVX())
1082     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
1083       return LT.first * Entry->Cost;
1084 
1085   if (ST->hasSSSE3())
1086     if (const auto *Entry = CostTableLookup(SSSE3CostTbl, ISD, MTy))
1087       return LT.first * Entry->Cost;
1088 
1089   if (ST->hasSSE2())
1090     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
1091       return LT.first * Entry->Cost;
1092 
1093   return BaseT::getIntrinsicInstrCost(IID, RetTy, Tys, FMF);
1094 }
1095 
1096 int X86TTIImpl::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
1097                                       ArrayRef<Value *> Args, FastMathFlags FMF) {
1098   return BaseT::getIntrinsicInstrCost(IID, RetTy, Args, FMF);
1099 }
1100 
1101 int X86TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
1102   assert(Val->isVectorTy() && "This must be a vector type");
1103 
1104   Type *ScalarType = Val->getScalarType();
1105 
1106   if (Index != -1U) {
1107     // Legalize the type.
1108     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
1109 
1110     // This type is legalized to a scalar type.
1111     if (!LT.second.isVector())
1112       return 0;
1113 
1114     // The type may be split. Normalize the index to the new type.
1115     unsigned Width = LT.second.getVectorNumElements();
1116     Index = Index % Width;
1117 
1118     // Floating point scalars are already located in index #0.
1119     if (ScalarType->isFloatingPointTy() && Index == 0)
1120       return 0;
1121   }
1122 
1123   // Add to the base cost if we know that the extracted element of a vector is
1124   // destined to be moved to and used in the integer register file.
1125   int RegisterFileMoveCost = 0;
1126   if (Opcode == Instruction::ExtractElement && ScalarType->isPointerTy())
1127     RegisterFileMoveCost = 1;
1128 
1129   return BaseT::getVectorInstrCost(Opcode, Val, Index) + RegisterFileMoveCost;
1130 }
1131 
1132 int X86TTIImpl::getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
1133   assert (Ty->isVectorTy() && "Can only scalarize vectors");
1134   int Cost = 0;
1135 
1136   for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
1137     if (Insert)
1138       Cost += getVectorInstrCost(Instruction::InsertElement, Ty, i);
1139     if (Extract)
1140       Cost += getVectorInstrCost(Instruction::ExtractElement, Ty, i);
1141   }
1142 
1143   return Cost;
1144 }
1145 
1146 int X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1147                                 unsigned AddressSpace) {
1148   // Handle non-power-of-two vectors such as <3 x float>
1149   if (VectorType *VTy = dyn_cast<VectorType>(Src)) {
1150     unsigned NumElem = VTy->getVectorNumElements();
1151 
1152     // Handle a few common cases:
1153     // <3 x float>
1154     if (NumElem == 3 && VTy->getScalarSizeInBits() == 32)
1155       // Cost = 64 bit store + extract + 32 bit store.
1156       return 3;
1157 
1158     // <3 x double>
1159     if (NumElem == 3 && VTy->getScalarSizeInBits() == 64)
1160       // Cost = 128 bit store + unpack + 64 bit store.
1161       return 3;
1162 
1163     // Assume that all other non-power-of-two numbers are scalarized.
1164     if (!isPowerOf2_32(NumElem)) {
1165       int Cost = BaseT::getMemoryOpCost(Opcode, VTy->getScalarType(), Alignment,
1166                                         AddressSpace);
1167       int SplitCost = getScalarizationOverhead(Src, Opcode == Instruction::Load,
1168                                                Opcode == Instruction::Store);
1169       return NumElem * Cost + SplitCost;
1170     }
1171   }
1172 
1173   // Legalize the type.
1174   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
1175   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
1176          "Invalid Opcode");
1177 
1178   // Each load/store unit costs 1.
1179   int Cost = LT.first * 1;
1180 
1181   // This isn't exactly right. We're using slow unaligned 32-byte accesses as a
1182   // proxy for a double-pumped AVX memory interface such as on Sandybridge.
1183   if (LT.second.getStoreSize() == 32 && ST->isUnalignedMem32Slow())
1184     Cost *= 2;
1185 
1186   return Cost;
1187 }
1188 
1189 int X86TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *SrcTy,
1190                                       unsigned Alignment,
1191                                       unsigned AddressSpace) {
1192   VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy);
1193   if (!SrcVTy)
1194     // To calculate scalar take the regular cost, without mask
1195     return getMemoryOpCost(Opcode, SrcTy, Alignment, AddressSpace);
1196 
1197   unsigned NumElem = SrcVTy->getVectorNumElements();
1198   VectorType *MaskTy =
1199     VectorType::get(Type::getInt8Ty(SrcVTy->getContext()), NumElem);
1200   if ((Opcode == Instruction::Load && !isLegalMaskedLoad(SrcVTy)) ||
1201       (Opcode == Instruction::Store && !isLegalMaskedStore(SrcVTy)) ||
1202       !isPowerOf2_32(NumElem)) {
1203     // Scalarization
1204     int MaskSplitCost = getScalarizationOverhead(MaskTy, false, true);
1205     int ScalarCompareCost = getCmpSelInstrCost(
1206         Instruction::ICmp, Type::getInt8Ty(SrcVTy->getContext()), nullptr);
1207     int BranchCost = getCFInstrCost(Instruction::Br);
1208     int MaskCmpCost = NumElem * (BranchCost + ScalarCompareCost);
1209 
1210     int ValueSplitCost = getScalarizationOverhead(
1211         SrcVTy, Opcode == Instruction::Load, Opcode == Instruction::Store);
1212     int MemopCost =
1213         NumElem * BaseT::getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
1214                                          Alignment, AddressSpace);
1215     return MemopCost + ValueSplitCost + MaskSplitCost + MaskCmpCost;
1216   }
1217 
1218   // Legalize the type.
1219   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, SrcVTy);
1220   auto VT = TLI->getValueType(DL, SrcVTy);
1221   int Cost = 0;
1222   if (VT.isSimple() && LT.second != VT.getSimpleVT() &&
1223       LT.second.getVectorNumElements() == NumElem)
1224     // Promotion requires expand/truncate for data and a shuffle for mask.
1225     Cost += getShuffleCost(TTI::SK_Alternate, SrcVTy, 0, nullptr) +
1226             getShuffleCost(TTI::SK_Alternate, MaskTy, 0, nullptr);
1227 
1228   else if (LT.second.getVectorNumElements() > NumElem) {
1229     VectorType *NewMaskTy = VectorType::get(MaskTy->getVectorElementType(),
1230                                             LT.second.getVectorNumElements());
1231     // Expanding requires fill mask with zeroes
1232     Cost += getShuffleCost(TTI::SK_InsertSubvector, NewMaskTy, 0, MaskTy);
1233   }
1234   if (!ST->hasAVX512())
1235     return Cost + LT.first*4; // Each maskmov costs 4
1236 
1237   // AVX-512 masked load/store is cheapper
1238   return Cost+LT.first;
1239 }
1240 
1241 int X86TTIImpl::getAddressComputationCost(Type *Ty, bool IsComplex) {
1242   // Address computations in vectorized code with non-consecutive addresses will
1243   // likely result in more instructions compared to scalar code where the
1244   // computation can more often be merged into the index mode. The resulting
1245   // extra micro-ops can significantly decrease throughput.
1246   unsigned NumVectorInstToHideOverhead = 10;
1247 
1248   if (Ty->isVectorTy() && IsComplex)
1249     return NumVectorInstToHideOverhead;
1250 
1251   return BaseT::getAddressComputationCost(Ty, IsComplex);
1252 }
1253 
1254 int X86TTIImpl::getReductionCost(unsigned Opcode, Type *ValTy,
1255                                  bool IsPairwise) {
1256 
1257   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
1258 
1259   MVT MTy = LT.second;
1260 
1261   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1262   assert(ISD && "Invalid opcode");
1263 
1264   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
1265   // and make it as the cost.
1266 
1267   static const CostTblEntry SSE42CostTblPairWise[] = {
1268     { ISD::FADD,  MVT::v2f64,   2 },
1269     { ISD::FADD,  MVT::v4f32,   4 },
1270     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
1271     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.5".
1272     { ISD::ADD,   MVT::v8i16,   5 },
1273   };
1274 
1275   static const CostTblEntry AVX1CostTblPairWise[] = {
1276     { ISD::FADD,  MVT::v4f32,   4 },
1277     { ISD::FADD,  MVT::v4f64,   5 },
1278     { ISD::FADD,  MVT::v8f32,   7 },
1279     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
1280     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.5".
1281     { ISD::ADD,   MVT::v4i64,   5 },      // The data reported by the IACA tool is "4.8".
1282     { ISD::ADD,   MVT::v8i16,   5 },
1283     { ISD::ADD,   MVT::v8i32,   5 },
1284   };
1285 
1286   static const CostTblEntry SSE42CostTblNoPairWise[] = {
1287     { ISD::FADD,  MVT::v2f64,   2 },
1288     { ISD::FADD,  MVT::v4f32,   4 },
1289     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
1290     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.3".
1291     { ISD::ADD,   MVT::v8i16,   4 },      // The data reported by the IACA tool is "4.3".
1292   };
1293 
1294   static const CostTblEntry AVX1CostTblNoPairWise[] = {
1295     { ISD::FADD,  MVT::v4f32,   3 },
1296     { ISD::FADD,  MVT::v4f64,   3 },
1297     { ISD::FADD,  MVT::v8f32,   4 },
1298     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
1299     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "2.8".
1300     { ISD::ADD,   MVT::v4i64,   3 },
1301     { ISD::ADD,   MVT::v8i16,   4 },
1302     { ISD::ADD,   MVT::v8i32,   5 },
1303   };
1304 
1305   if (IsPairwise) {
1306     if (ST->hasAVX())
1307       if (const auto *Entry = CostTableLookup(AVX1CostTblPairWise, ISD, MTy))
1308         return LT.first * Entry->Cost;
1309 
1310     if (ST->hasSSE42())
1311       if (const auto *Entry = CostTableLookup(SSE42CostTblPairWise, ISD, MTy))
1312         return LT.first * Entry->Cost;
1313   } else {
1314     if (ST->hasAVX())
1315       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
1316         return LT.first * Entry->Cost;
1317 
1318     if (ST->hasSSE42())
1319       if (const auto *Entry = CostTableLookup(SSE42CostTblNoPairWise, ISD, MTy))
1320         return LT.first * Entry->Cost;
1321   }
1322 
1323   return BaseT::getReductionCost(Opcode, ValTy, IsPairwise);
1324 }
1325 
1326 /// \brief Calculate the cost of materializing a 64-bit value. This helper
1327 /// method might only calculate a fraction of a larger immediate. Therefore it
1328 /// is valid to return a cost of ZERO.
1329 int X86TTIImpl::getIntImmCost(int64_t Val) {
1330   if (Val == 0)
1331     return TTI::TCC_Free;
1332 
1333   if (isInt<32>(Val))
1334     return TTI::TCC_Basic;
1335 
1336   return 2 * TTI::TCC_Basic;
1337 }
1338 
1339 int X86TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
1340   assert(Ty->isIntegerTy());
1341 
1342   unsigned BitSize = Ty->getPrimitiveSizeInBits();
1343   if (BitSize == 0)
1344     return ~0U;
1345 
1346   // Never hoist constants larger than 128bit, because this might lead to
1347   // incorrect code generation or assertions in codegen.
1348   // Fixme: Create a cost model for types larger than i128 once the codegen
1349   // issues have been fixed.
1350   if (BitSize > 128)
1351     return TTI::TCC_Free;
1352 
1353   if (Imm == 0)
1354     return TTI::TCC_Free;
1355 
1356   // Sign-extend all constants to a multiple of 64-bit.
1357   APInt ImmVal = Imm;
1358   if (BitSize & 0x3f)
1359     ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
1360 
1361   // Split the constant into 64-bit chunks and calculate the cost for each
1362   // chunk.
1363   int Cost = 0;
1364   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
1365     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
1366     int64_t Val = Tmp.getSExtValue();
1367     Cost += getIntImmCost(Val);
1368   }
1369   // We need at least one instruction to materialize the constant.
1370   return std::max(1, Cost);
1371 }
1372 
1373 int X86TTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
1374                               Type *Ty) {
1375   assert(Ty->isIntegerTy());
1376 
1377   unsigned BitSize = Ty->getPrimitiveSizeInBits();
1378   // There is no cost model for constants with a bit size of 0. Return TCC_Free
1379   // here, so that constant hoisting will ignore this constant.
1380   if (BitSize == 0)
1381     return TTI::TCC_Free;
1382 
1383   unsigned ImmIdx = ~0U;
1384   switch (Opcode) {
1385   default:
1386     return TTI::TCC_Free;
1387   case Instruction::GetElementPtr:
1388     // Always hoist the base address of a GetElementPtr. This prevents the
1389     // creation of new constants for every base constant that gets constant
1390     // folded with the offset.
1391     if (Idx == 0)
1392       return 2 * TTI::TCC_Basic;
1393     return TTI::TCC_Free;
1394   case Instruction::Store:
1395     ImmIdx = 0;
1396     break;
1397   case Instruction::ICmp:
1398     // This is an imperfect hack to prevent constant hoisting of
1399     // compares that might be trying to check if a 64-bit value fits in
1400     // 32-bits. The backend can optimize these cases using a right shift by 32.
1401     // Ideally we would check the compare predicate here. There also other
1402     // similar immediates the backend can use shifts for.
1403     if (Idx == 1 && Imm.getBitWidth() == 64) {
1404       uint64_t ImmVal = Imm.getZExtValue();
1405       if (ImmVal == 0x100000000ULL || ImmVal == 0xffffffff)
1406         return TTI::TCC_Free;
1407     }
1408     ImmIdx = 1;
1409     break;
1410   case Instruction::And:
1411     // We support 64-bit ANDs with immediates with 32-bits of leading zeroes
1412     // by using a 32-bit operation with implicit zero extension. Detect such
1413     // immediates here as the normal path expects bit 31 to be sign extended.
1414     if (Idx == 1 && Imm.getBitWidth() == 64 && isUInt<32>(Imm.getZExtValue()))
1415       return TTI::TCC_Free;
1416     LLVM_FALLTHROUGH;
1417   case Instruction::Add:
1418   case Instruction::Sub:
1419   case Instruction::Mul:
1420   case Instruction::UDiv:
1421   case Instruction::SDiv:
1422   case Instruction::URem:
1423   case Instruction::SRem:
1424   case Instruction::Or:
1425   case Instruction::Xor:
1426     ImmIdx = 1;
1427     break;
1428   // Always return TCC_Free for the shift value of a shift instruction.
1429   case Instruction::Shl:
1430   case Instruction::LShr:
1431   case Instruction::AShr:
1432     if (Idx == 1)
1433       return TTI::TCC_Free;
1434     break;
1435   case Instruction::Trunc:
1436   case Instruction::ZExt:
1437   case Instruction::SExt:
1438   case Instruction::IntToPtr:
1439   case Instruction::PtrToInt:
1440   case Instruction::BitCast:
1441   case Instruction::PHI:
1442   case Instruction::Call:
1443   case Instruction::Select:
1444   case Instruction::Ret:
1445   case Instruction::Load:
1446     break;
1447   }
1448 
1449   if (Idx == ImmIdx) {
1450     int NumConstants = (BitSize + 63) / 64;
1451     int Cost = X86TTIImpl::getIntImmCost(Imm, Ty);
1452     return (Cost <= NumConstants * TTI::TCC_Basic)
1453                ? static_cast<int>(TTI::TCC_Free)
1454                : Cost;
1455   }
1456 
1457   return X86TTIImpl::getIntImmCost(Imm, Ty);
1458 }
1459 
1460 int X86TTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
1461                               Type *Ty) {
1462   assert(Ty->isIntegerTy());
1463 
1464   unsigned BitSize = Ty->getPrimitiveSizeInBits();
1465   // There is no cost model for constants with a bit size of 0. Return TCC_Free
1466   // here, so that constant hoisting will ignore this constant.
1467   if (BitSize == 0)
1468     return TTI::TCC_Free;
1469 
1470   switch (IID) {
1471   default:
1472     return TTI::TCC_Free;
1473   case Intrinsic::sadd_with_overflow:
1474   case Intrinsic::uadd_with_overflow:
1475   case Intrinsic::ssub_with_overflow:
1476   case Intrinsic::usub_with_overflow:
1477   case Intrinsic::smul_with_overflow:
1478   case Intrinsic::umul_with_overflow:
1479     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<32>(Imm.getSExtValue()))
1480       return TTI::TCC_Free;
1481     break;
1482   case Intrinsic::experimental_stackmap:
1483     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
1484       return TTI::TCC_Free;
1485     break;
1486   case Intrinsic::experimental_patchpoint_void:
1487   case Intrinsic::experimental_patchpoint_i64:
1488     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
1489       return TTI::TCC_Free;
1490     break;
1491   }
1492   return X86TTIImpl::getIntImmCost(Imm, Ty);
1493 }
1494 
1495 // Return an average cost of Gather / Scatter instruction, maybe improved later
1496 int X86TTIImpl::getGSVectorCost(unsigned Opcode, Type *SrcVTy, Value *Ptr,
1497                                 unsigned Alignment, unsigned AddressSpace) {
1498 
1499   assert(isa<VectorType>(SrcVTy) && "Unexpected type in getGSVectorCost");
1500   unsigned VF = SrcVTy->getVectorNumElements();
1501 
1502   // Try to reduce index size from 64 bit (default for GEP)
1503   // to 32. It is essential for VF 16. If the index can't be reduced to 32, the
1504   // operation will use 16 x 64 indices which do not fit in a zmm and needs
1505   // to split. Also check that the base pointer is the same for all lanes,
1506   // and that there's at most one variable index.
1507   auto getIndexSizeInBits = [](Value *Ptr, const DataLayout& DL) {
1508     unsigned IndexSize = DL.getPointerSizeInBits();
1509     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1510     if (IndexSize < 64 || !GEP)
1511       return IndexSize;
1512 
1513     unsigned NumOfVarIndices = 0;
1514     Value *Ptrs = GEP->getPointerOperand();
1515     if (Ptrs->getType()->isVectorTy() && !getSplatValue(Ptrs))
1516       return IndexSize;
1517     for (unsigned i = 1; i < GEP->getNumOperands(); ++i) {
1518       if (isa<Constant>(GEP->getOperand(i)))
1519         continue;
1520       Type *IndxTy = GEP->getOperand(i)->getType();
1521       if (IndxTy->isVectorTy())
1522         IndxTy = IndxTy->getVectorElementType();
1523       if ((IndxTy->getPrimitiveSizeInBits() == 64 &&
1524           !isa<SExtInst>(GEP->getOperand(i))) ||
1525          ++NumOfVarIndices > 1)
1526         return IndexSize; // 64
1527     }
1528     return (unsigned)32;
1529   };
1530 
1531 
1532   // Trying to reduce IndexSize to 32 bits for vector 16.
1533   // By default the IndexSize is equal to pointer size.
1534   unsigned IndexSize = (VF >= 16) ? getIndexSizeInBits(Ptr, DL) :
1535     DL.getPointerSizeInBits();
1536 
1537   Type *IndexVTy = VectorType::get(IntegerType::get(SrcVTy->getContext(),
1538                                                     IndexSize), VF);
1539   std::pair<int, MVT> IdxsLT = TLI->getTypeLegalizationCost(DL, IndexVTy);
1540   std::pair<int, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, SrcVTy);
1541   int SplitFactor = std::max(IdxsLT.first, SrcLT.first);
1542   if (SplitFactor > 1) {
1543     // Handle splitting of vector of pointers
1544     Type *SplitSrcTy = VectorType::get(SrcVTy->getScalarType(), VF / SplitFactor);
1545     return SplitFactor * getGSVectorCost(Opcode, SplitSrcTy, Ptr, Alignment,
1546                                          AddressSpace);
1547   }
1548 
1549   // The gather / scatter cost is given by Intel architects. It is a rough
1550   // number since we are looking at one instruction in a time.
1551   const int GSOverhead = 2;
1552   return GSOverhead + VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
1553                                            Alignment, AddressSpace);
1554 }
1555 
1556 /// Return the cost of full scalarization of gather / scatter operation.
1557 ///
1558 /// Opcode - Load or Store instruction.
1559 /// SrcVTy - The type of the data vector that should be gathered or scattered.
1560 /// VariableMask - The mask is non-constant at compile time.
1561 /// Alignment - Alignment for one element.
1562 /// AddressSpace - pointer[s] address space.
1563 ///
1564 int X86TTIImpl::getGSScalarCost(unsigned Opcode, Type *SrcVTy,
1565                                 bool VariableMask, unsigned Alignment,
1566                                 unsigned AddressSpace) {
1567   unsigned VF = SrcVTy->getVectorNumElements();
1568 
1569   int MaskUnpackCost = 0;
1570   if (VariableMask) {
1571     VectorType *MaskTy =
1572       VectorType::get(Type::getInt1Ty(SrcVTy->getContext()), VF);
1573     MaskUnpackCost = getScalarizationOverhead(MaskTy, false, true);
1574     int ScalarCompareCost =
1575       getCmpSelInstrCost(Instruction::ICmp, Type::getInt1Ty(SrcVTy->getContext()),
1576                          nullptr);
1577     int BranchCost = getCFInstrCost(Instruction::Br);
1578     MaskUnpackCost += VF * (BranchCost + ScalarCompareCost);
1579   }
1580 
1581   // The cost of the scalar loads/stores.
1582   int MemoryOpCost = VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
1583                                           Alignment, AddressSpace);
1584 
1585   int InsertExtractCost = 0;
1586   if (Opcode == Instruction::Load)
1587     for (unsigned i = 0; i < VF; ++i)
1588       // Add the cost of inserting each scalar load into the vector
1589       InsertExtractCost +=
1590         getVectorInstrCost(Instruction::InsertElement, SrcVTy, i);
1591   else
1592     for (unsigned i = 0; i < VF; ++i)
1593       // Add the cost of extracting each element out of the data vector
1594       InsertExtractCost +=
1595         getVectorInstrCost(Instruction::ExtractElement, SrcVTy, i);
1596 
1597   return MemoryOpCost + MaskUnpackCost + InsertExtractCost;
1598 }
1599 
1600 /// Calculate the cost of Gather / Scatter operation
1601 int X86TTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *SrcVTy,
1602                                        Value *Ptr, bool VariableMask,
1603                                        unsigned Alignment) {
1604   assert(SrcVTy->isVectorTy() && "Unexpected data type for Gather/Scatter");
1605   unsigned VF = SrcVTy->getVectorNumElements();
1606   PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
1607   if (!PtrTy && Ptr->getType()->isVectorTy())
1608     PtrTy = dyn_cast<PointerType>(Ptr->getType()->getVectorElementType());
1609   assert(PtrTy && "Unexpected type for Ptr argument");
1610   unsigned AddressSpace = PtrTy->getAddressSpace();
1611 
1612   bool Scalarize = false;
1613   if ((Opcode == Instruction::Load && !isLegalMaskedGather(SrcVTy)) ||
1614       (Opcode == Instruction::Store && !isLegalMaskedScatter(SrcVTy)))
1615     Scalarize = true;
1616   // Gather / Scatter for vector 2 is not profitable on KNL / SKX
1617   // Vector-4 of gather/scatter instruction does not exist on KNL.
1618   // We can extend it to 8 elements, but zeroing upper bits of
1619   // the mask vector will add more instructions. Right now we give the scalar
1620   // cost of vector-4 for KNL. TODO: Check, maybe the gather/scatter instruction is
1621   // better in the VariableMask case.
1622   if (VF == 2 || (VF == 4 && !ST->hasVLX()))
1623     Scalarize = true;
1624 
1625   if (Scalarize)
1626     return getGSScalarCost(Opcode, SrcVTy, VariableMask, Alignment, AddressSpace);
1627 
1628   return getGSVectorCost(Opcode, SrcVTy, Ptr, Alignment, AddressSpace);
1629 }
1630 
1631 bool X86TTIImpl::isLegalMaskedLoad(Type *DataTy) {
1632   Type *ScalarTy = DataTy->getScalarType();
1633   int DataWidth = isa<PointerType>(ScalarTy) ?
1634     DL.getPointerSizeInBits() : ScalarTy->getPrimitiveSizeInBits();
1635 
1636   return ((DataWidth == 32 || DataWidth == 64) && ST->hasAVX()) ||
1637          ((DataWidth == 8 || DataWidth == 16) && ST->hasBWI());
1638 }
1639 
1640 bool X86TTIImpl::isLegalMaskedStore(Type *DataType) {
1641   return isLegalMaskedLoad(DataType);
1642 }
1643 
1644 bool X86TTIImpl::isLegalMaskedGather(Type *DataTy) {
1645   // This function is called now in two cases: from the Loop Vectorizer
1646   // and from the Scalarizer.
1647   // When the Loop Vectorizer asks about legality of the feature,
1648   // the vectorization factor is not calculated yet. The Loop Vectorizer
1649   // sends a scalar type and the decision is based on the width of the
1650   // scalar element.
1651   // Later on, the cost model will estimate usage this intrinsic based on
1652   // the vector type.
1653   // The Scalarizer asks again about legality. It sends a vector type.
1654   // In this case we can reject non-power-of-2 vectors.
1655   if (isa<VectorType>(DataTy) && !isPowerOf2_32(DataTy->getVectorNumElements()))
1656     return false;
1657   Type *ScalarTy = DataTy->getScalarType();
1658   int DataWidth = isa<PointerType>(ScalarTy) ?
1659     DL.getPointerSizeInBits() : ScalarTy->getPrimitiveSizeInBits();
1660 
1661   // AVX-512 allows gather and scatter
1662   return (DataWidth == 32 || DataWidth == 64) && ST->hasAVX512();
1663 }
1664 
1665 bool X86TTIImpl::isLegalMaskedScatter(Type *DataType) {
1666   return isLegalMaskedGather(DataType);
1667 }
1668 
1669 bool X86TTIImpl::areInlineCompatible(const Function *Caller,
1670                                      const Function *Callee) const {
1671   const TargetMachine &TM = getTLI()->getTargetMachine();
1672 
1673   // Work this as a subsetting of subtarget features.
1674   const FeatureBitset &CallerBits =
1675       TM.getSubtargetImpl(*Caller)->getFeatureBits();
1676   const FeatureBitset &CalleeBits =
1677       TM.getSubtargetImpl(*Callee)->getFeatureBits();
1678 
1679   // FIXME: This is likely too limiting as it will include subtarget features
1680   // that we might not care about for inlining, but it is conservatively
1681   // correct.
1682   return (CallerBits & CalleeBits) == CalleeBits;
1683 }
1684