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