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