1 //===-- X86TargetTransformInfo.cpp - X86 specific TTI pass ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements a TargetTransformInfo analysis pass specific to the
10 /// X86 target machine. It uses the target's detailed information to provide
11 /// more precise answers to certain TTI queries, while letting the target
12 /// independent and default TTI implementations handle the rest.
13 ///
14 //===----------------------------------------------------------------------===//
15 /// About Cost Model numbers used below it's necessary to say the following:
16 /// the numbers correspond to some "generic" X86 CPU instead of usage of
17 /// concrete CPU model. Usually the numbers correspond to CPU where the feature
18 /// apeared at the first time. For example, if we do Subtarget.hasSSE42() in
19 /// the lookups below the cost is based on Nehalem as that was the first CPU
20 /// to support that feature level and thus has most likely the worst case cost.
21 /// Some examples of other technologies/CPUs:
22 ///   SSE 3   - Pentium4 / Athlon64
23 ///   SSE 4.1 - Penryn
24 ///   SSE 4.2 - Nehalem
25 ///   AVX     - Sandy Bridge
26 ///   AVX2    - Haswell
27 ///   AVX-512 - Xeon Phi / Skylake
28 /// And some examples of instruction target dependent costs (latency)
29 ///                   divss     sqrtss          rsqrtss
30 ///   AMD K7            11-16     19              3
31 ///   Piledriver        9-24      13-15           5
32 ///   Jaguar            14        16              2
33 ///   Pentium II,III    18        30              2
34 ///   Nehalem           7-14      7-18            3
35 ///   Haswell           10-13     11              5
36 /// TODO: Develop and implement  the target dependent cost model and
37 /// specialize cost numbers for different Cost Model Targets such as throughput,
38 /// code size, latency and uop count.
39 //===----------------------------------------------------------------------===//
40 
41 #include "X86TargetTransformInfo.h"
42 #include "llvm/Analysis/TargetTransformInfo.h"
43 #include "llvm/CodeGen/BasicTTIImpl.h"
44 #include "llvm/CodeGen/CostTable.h"
45 #include "llvm/CodeGen/TargetLowering.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/Support/Debug.h"
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "x86tti"
52 
53 //===----------------------------------------------------------------------===//
54 //
55 // X86 cost model.
56 //
57 //===----------------------------------------------------------------------===//
58 
59 TargetTransformInfo::PopcntSupportKind
60 X86TTIImpl::getPopcntSupport(unsigned TyWidth) {
61   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
62   // TODO: Currently the __builtin_popcount() implementation using SSE3
63   //   instructions is inefficient. Once the problem is fixed, we should
64   //   call ST->hasSSE3() instead of ST->hasPOPCNT().
65   return ST->hasPOPCNT() ? TTI::PSK_FastHardware : TTI::PSK_Software;
66 }
67 
68 llvm::Optional<unsigned> X86TTIImpl::getCacheSize(
69   TargetTransformInfo::CacheLevel Level) const {
70   switch (Level) {
71   case TargetTransformInfo::CacheLevel::L1D:
72     //   - Penryn
73     //   - Nehalem
74     //   - Westmere
75     //   - Sandy Bridge
76     //   - Ivy Bridge
77     //   - Haswell
78     //   - Broadwell
79     //   - Skylake
80     //   - Kabylake
81     return 32 * 1024;  //  32 KByte
82   case TargetTransformInfo::CacheLevel::L2D:
83     //   - Penryn
84     //   - Nehalem
85     //   - Westmere
86     //   - Sandy Bridge
87     //   - Ivy Bridge
88     //   - Haswell
89     //   - Broadwell
90     //   - Skylake
91     //   - Kabylake
92     return 256 * 1024; // 256 KByte
93   }
94 
95   llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
96 }
97 
98 llvm::Optional<unsigned> X86TTIImpl::getCacheAssociativity(
99   TargetTransformInfo::CacheLevel Level) const {
100   //   - Penryn
101   //   - Nehalem
102   //   - Westmere
103   //   - Sandy Bridge
104   //   - Ivy Bridge
105   //   - Haswell
106   //   - Broadwell
107   //   - Skylake
108   //   - Kabylake
109   switch (Level) {
110   case TargetTransformInfo::CacheLevel::L1D:
111     LLVM_FALLTHROUGH;
112   case TargetTransformInfo::CacheLevel::L2D:
113     return 8;
114   }
115 
116   llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
117 }
118 
119 unsigned X86TTIImpl::getNumberOfRegisters(unsigned ClassID) const {
120   bool Vector = (ClassID == 1);
121   if (Vector && !ST->hasSSE1())
122     return 0;
123 
124   if (ST->is64Bit()) {
125     if (Vector && ST->hasAVX512())
126       return 32;
127     return 16;
128   }
129   return 8;
130 }
131 
132 TypeSize
133 X86TTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
134   unsigned PreferVectorWidth = ST->getPreferVectorWidth();
135   switch (K) {
136   case TargetTransformInfo::RGK_Scalar:
137     return TypeSize::getFixed(ST->is64Bit() ? 64 : 32);
138   case TargetTransformInfo::RGK_FixedWidthVector:
139     if (ST->hasAVX512() && PreferVectorWidth >= 512)
140       return TypeSize::getFixed(512);
141     if (ST->hasAVX() && PreferVectorWidth >= 256)
142       return TypeSize::getFixed(256);
143     if (ST->hasSSE1() && PreferVectorWidth >= 128)
144       return TypeSize::getFixed(128);
145     return TypeSize::getFixed(0);
146   case TargetTransformInfo::RGK_ScalableVector:
147     return TypeSize::getScalable(0);
148   }
149 
150   llvm_unreachable("Unsupported register kind");
151 }
152 
153 unsigned X86TTIImpl::getLoadStoreVecRegBitWidth(unsigned) const {
154   return getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
155       .getFixedSize();
156 }
157 
158 unsigned X86TTIImpl::getMaxInterleaveFactor(unsigned VF) {
159   // If the loop will not be vectorized, don't interleave the loop.
160   // Let regular unroll to unroll the loop, which saves the overflow
161   // check and memory check cost.
162   if (VF == 1)
163     return 1;
164 
165   if (ST->isAtom())
166     return 1;
167 
168   // Sandybridge and Haswell have multiple execution ports and pipelined
169   // vector units.
170   if (ST->hasAVX())
171     return 4;
172 
173   return 2;
174 }
175 
176 InstructionCost X86TTIImpl::getArithmeticInstrCost(
177     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
178     TTI::OperandValueKind Op1Info, TTI::OperandValueKind Op2Info,
179     TTI::OperandValueProperties Opd1PropInfo,
180     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
181     const Instruction *CxtI) {
182   // TODO: Handle more cost kinds.
183   if (CostKind != TTI::TCK_RecipThroughput)
184     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
185                                          Op2Info, Opd1PropInfo,
186                                          Opd2PropInfo, Args, CxtI);
187 
188   // vXi8 multiplications are always promoted to vXi16.
189   if (Opcode == Instruction::Mul && Ty->isVectorTy() &&
190       Ty->getScalarSizeInBits() == 8) {
191     Type *WideVecTy =
192         VectorType::getExtendedElementVectorType(cast<VectorType>(Ty));
193     return getCastInstrCost(Instruction::ZExt, WideVecTy, Ty,
194                             TargetTransformInfo::CastContextHint::None,
195                             CostKind) +
196            getCastInstrCost(Instruction::Trunc, Ty, WideVecTy,
197                             TargetTransformInfo::CastContextHint::None,
198                             CostKind) +
199            getArithmeticInstrCost(Opcode, WideVecTy, CostKind, Op1Info, Op2Info,
200                                   Opd1PropInfo, Opd2PropInfo);
201   }
202 
203   // Legalize the type.
204   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
205 
206   int ISD = TLI->InstructionOpcodeToISD(Opcode);
207   assert(ISD && "Invalid opcode");
208 
209   if (ISD == ISD::MUL && Args.size() == 2 && LT.second.isVector() &&
210       LT.second.getScalarType() == MVT::i32) {
211     // Check if the operands can be represented as a smaller datatype.
212     bool Op1Signed = false, Op2Signed = false;
213     unsigned Op1MinSize = BaseT::minRequiredElementSize(Args[0], Op1Signed);
214     unsigned Op2MinSize = BaseT::minRequiredElementSize(Args[1], Op2Signed);
215     unsigned OpMinSize = std::max(Op1MinSize, Op2MinSize);
216 
217     // If both are representable as i15 and at least one is constant,
218     // zero-extended, or sign-extended from vXi16 (or less pre-SSE41) then we
219     // can treat this as PMADDWD which has the same costs as a vXi16 multiply.
220     if (OpMinSize <= 15 && !ST->isPMADDWDSlow()) {
221       bool Op1Constant =
222           isa<ConstantDataVector>(Args[0]) || isa<ConstantVector>(Args[0]);
223       bool Op2Constant =
224           isa<ConstantDataVector>(Args[1]) || isa<ConstantVector>(Args[1]);
225       bool Op1Sext = isa<SExtInst>(Args[0]) &&
226                      (Op1MinSize == 15 || (Op1MinSize < 15 && !ST->hasSSE41()));
227       bool Op2Sext = isa<SExtInst>(Args[1]) &&
228                      (Op2MinSize == 15 || (Op2MinSize < 15 && !ST->hasSSE41()));
229 
230       bool IsZeroExtended = !Op1Signed || !Op2Signed;
231       bool IsConstant = Op1Constant || Op2Constant;
232       bool IsSext = Op1Sext || Op2Sext;
233       if (IsConstant || IsZeroExtended || IsSext)
234         LT.second =
235             MVT::getVectorVT(MVT::i16, 2 * LT.second.getVectorNumElements());
236     }
237   }
238 
239   if ((ISD == ISD::MUL || ISD == ISD::SDIV || ISD == ISD::SREM ||
240        ISD == ISD::UDIV || ISD == ISD::UREM) &&
241       (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
242        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
243       Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
244     // Vector multiply by pow2 will be simplified to shifts.
245     if (ISD == ISD::MUL) {
246       InstructionCost Cost = getArithmeticInstrCost(
247           Instruction::Shl, Ty, CostKind, Op1Info, Op2Info,
248           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
249       return Cost;
250     }
251 
252     if (ISD == ISD::SDIV || ISD == ISD::SREM) {
253       // On X86, vector signed division by constants power-of-two are
254       // normally expanded to the sequence SRA + SRL + ADD + SRA.
255       // The OperandValue properties may not be the same as that of the previous
256       // operation; conservatively assume OP_None.
257       InstructionCost Cost =
258           2 * getArithmeticInstrCost(Instruction::AShr, Ty, CostKind, Op1Info,
259                                      Op2Info, TargetTransformInfo::OP_None,
260                                      TargetTransformInfo::OP_None);
261       Cost += getArithmeticInstrCost(Instruction::LShr, Ty, CostKind, Op1Info,
262                                      Op2Info, TargetTransformInfo::OP_None,
263                                      TargetTransformInfo::OP_None);
264       Cost += getArithmeticInstrCost(Instruction::Add, Ty, CostKind, Op1Info,
265                                      Op2Info, TargetTransformInfo::OP_None,
266                                      TargetTransformInfo::OP_None);
267 
268       if (ISD == ISD::SREM) {
269         // For SREM: (X % C) is the equivalent of (X - (X/C)*C)
270         Cost += getArithmeticInstrCost(Instruction::Mul, Ty, CostKind, Op1Info,
271                                        Op2Info);
272         Cost += getArithmeticInstrCost(Instruction::Sub, Ty, CostKind, Op1Info,
273                                        Op2Info);
274       }
275 
276       return Cost;
277     }
278 
279     // Vector unsigned division/remainder will be simplified to shifts/masks.
280     if (ISD == ISD::UDIV)
281       return getArithmeticInstrCost(Instruction::LShr, Ty, CostKind, Op1Info,
282                                     Op2Info, TargetTransformInfo::OP_None,
283                                     TargetTransformInfo::OP_None);
284     // UREM
285     return getArithmeticInstrCost(Instruction::And, Ty, CostKind, Op1Info,
286                                   Op2Info, TargetTransformInfo::OP_None,
287                                   TargetTransformInfo::OP_None);
288   }
289 
290   static const CostTblEntry GLMCostTable[] = {
291     { ISD::FDIV,  MVT::f32,   18 }, // divss
292     { ISD::FDIV,  MVT::v4f32, 35 }, // divps
293     { ISD::FDIV,  MVT::f64,   33 }, // divsd
294     { ISD::FDIV,  MVT::v2f64, 65 }, // divpd
295   };
296 
297   if (ST->useGLMDivSqrtCosts())
298     if (const auto *Entry = CostTableLookup(GLMCostTable, ISD,
299                                             LT.second))
300       return LT.first * Entry->Cost;
301 
302   static const CostTblEntry SLMCostTable[] = {
303     { ISD::MUL,   MVT::v4i32, 11 }, // pmulld
304     { ISD::MUL,   MVT::v8i16, 2  }, // pmullw
305     { ISD::FMUL,  MVT::f64,   2  }, // mulsd
306     { ISD::FMUL,  MVT::v2f64, 4  }, // mulpd
307     { ISD::FMUL,  MVT::v4f32, 2  }, // mulps
308     { ISD::FDIV,  MVT::f32,   17 }, // divss
309     { ISD::FDIV,  MVT::v4f32, 39 }, // divps
310     { ISD::FDIV,  MVT::f64,   32 }, // divsd
311     { ISD::FDIV,  MVT::v2f64, 69 }, // divpd
312     { ISD::FADD,  MVT::v2f64, 2  }, // addpd
313     { ISD::FSUB,  MVT::v2f64, 2  }, // subpd
314     // v2i64/v4i64 mul is custom lowered as a series of long:
315     // multiplies(3), shifts(3) and adds(2)
316     // slm muldq version throughput is 2 and addq throughput 4
317     // thus: 3X2 (muldq throughput) + 3X1 (shift throughput) +
318     //       3X4 (addq throughput) = 17
319     { ISD::MUL,   MVT::v2i64, 17 },
320     // slm addq\subq throughput is 4
321     { ISD::ADD,   MVT::v2i64, 4  },
322     { ISD::SUB,   MVT::v2i64, 4  },
323   };
324 
325   if (ST->useSLMArithCosts()) {
326     if (Args.size() == 2 && ISD == ISD::MUL && LT.second == MVT::v4i32) {
327       // Check if the operands can be shrinked into a smaller datatype.
328       // TODO: Merge this into generiic vXi32 MUL patterns above.
329       bool Op1Signed = false;
330       unsigned Op1MinSize = BaseT::minRequiredElementSize(Args[0], Op1Signed);
331       bool Op2Signed = false;
332       unsigned Op2MinSize = BaseT::minRequiredElementSize(Args[1], Op2Signed);
333 
334       bool SignedMode = Op1Signed || Op2Signed;
335       unsigned OpMinSize = std::max(Op1MinSize, Op2MinSize);
336 
337       if (OpMinSize <= 7)
338         return LT.first * 3; // pmullw/sext
339       if (!SignedMode && OpMinSize <= 8)
340         return LT.first * 3; // pmullw/zext
341       if (OpMinSize <= 15)
342         return LT.first * 5; // pmullw/pmulhw/pshuf
343       if (!SignedMode && OpMinSize <= 16)
344         return LT.first * 5; // pmullw/pmulhw/pshuf
345     }
346 
347     if (const auto *Entry = CostTableLookup(SLMCostTable, ISD,
348                                             LT.second)) {
349       return LT.first * Entry->Cost;
350     }
351   }
352 
353   static const CostTblEntry AVX512BWUniformConstCostTable[] = {
354     { ISD::SHL,  MVT::v64i8,   2 }, // psllw + pand.
355     { ISD::SRL,  MVT::v64i8,   2 }, // psrlw + pand.
356     { ISD::SRA,  MVT::v64i8,   4 }, // psrlw, pand, pxor, psubb.
357   };
358 
359   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
360       ST->hasBWI()) {
361     if (const auto *Entry = CostTableLookup(AVX512BWUniformConstCostTable, ISD,
362                                             LT.second))
363       return LT.first * Entry->Cost;
364   }
365 
366   static const CostTblEntry AVX512UniformConstCostTable[] = {
367     { ISD::SRA,  MVT::v2i64,   1 },
368     { ISD::SRA,  MVT::v4i64,   1 },
369     { ISD::SRA,  MVT::v8i64,   1 },
370 
371     { ISD::SHL,  MVT::v64i8,   4 }, // psllw + pand.
372     { ISD::SRL,  MVT::v64i8,   4 }, // psrlw + pand.
373     { ISD::SRA,  MVT::v64i8,   8 }, // psrlw, pand, pxor, psubb.
374 
375     { ISD::SDIV, MVT::v16i32,  6 }, // pmuludq sequence
376     { ISD::SREM, MVT::v16i32,  8 }, // pmuludq+mul+sub sequence
377     { ISD::UDIV, MVT::v16i32,  5 }, // pmuludq sequence
378     { ISD::UREM, MVT::v16i32,  7 }, // pmuludq+mul+sub sequence
379   };
380 
381   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
382       ST->hasAVX512()) {
383     if (const auto *Entry = CostTableLookup(AVX512UniformConstCostTable, ISD,
384                                             LT.second))
385       return LT.first * Entry->Cost;
386   }
387 
388   static const CostTblEntry AVX2UniformConstCostTable[] = {
389     { ISD::SHL,  MVT::v32i8,   2 }, // psllw + pand.
390     { ISD::SRL,  MVT::v32i8,   2 }, // psrlw + pand.
391     { ISD::SRA,  MVT::v32i8,   4 }, // psrlw, pand, pxor, psubb.
392 
393     { ISD::SRA,  MVT::v4i64,   4 }, // 2 x psrad + shuffle.
394 
395     { ISD::SDIV, MVT::v8i32,   6 }, // pmuludq sequence
396     { ISD::SREM, MVT::v8i32,   8 }, // pmuludq+mul+sub sequence
397     { ISD::UDIV, MVT::v8i32,   5 }, // pmuludq sequence
398     { ISD::UREM, MVT::v8i32,   7 }, // pmuludq+mul+sub sequence
399   };
400 
401   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
402       ST->hasAVX2()) {
403     if (const auto *Entry = CostTableLookup(AVX2UniformConstCostTable, ISD,
404                                             LT.second))
405       return LT.first * Entry->Cost;
406   }
407 
408   static const CostTblEntry SSE2UniformConstCostTable[] = {
409     { ISD::SHL,  MVT::v16i8,     2 }, // psllw + pand.
410     { ISD::SRL,  MVT::v16i8,     2 }, // psrlw + pand.
411     { ISD::SRA,  MVT::v16i8,     4 }, // psrlw, pand, pxor, psubb.
412 
413     { ISD::SHL,  MVT::v32i8,   4+2 }, // 2*(psllw + pand) + split.
414     { ISD::SRL,  MVT::v32i8,   4+2 }, // 2*(psrlw + pand) + split.
415     { ISD::SRA,  MVT::v32i8,   8+2 }, // 2*(psrlw, pand, pxor, psubb) + split.
416 
417     { ISD::SDIV, MVT::v8i32,  12+2 }, // 2*pmuludq sequence + split.
418     { ISD::SREM, MVT::v8i32,  16+2 }, // 2*pmuludq+mul+sub sequence + split.
419     { ISD::SDIV, MVT::v4i32,     6 }, // pmuludq sequence
420     { ISD::SREM, MVT::v4i32,     8 }, // pmuludq+mul+sub sequence
421     { ISD::UDIV, MVT::v8i32,  10+2 }, // 2*pmuludq sequence + split.
422     { ISD::UREM, MVT::v8i32,  14+2 }, // 2*pmuludq+mul+sub sequence + split.
423     { ISD::UDIV, MVT::v4i32,     5 }, // pmuludq sequence
424     { ISD::UREM, MVT::v4i32,     7 }, // pmuludq+mul+sub sequence
425   };
426 
427   // XOP has faster vXi8 shifts.
428   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
429       ST->hasSSE2() && !ST->hasXOP()) {
430     if (const auto *Entry =
431             CostTableLookup(SSE2UniformConstCostTable, ISD, LT.second))
432       return LT.first * Entry->Cost;
433   }
434 
435   static const CostTblEntry AVX512BWConstCostTable[] = {
436     { ISD::SDIV, MVT::v64i8,  14 }, // 2*ext+2*pmulhw sequence
437     { ISD::SREM, MVT::v64i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
438     { ISD::UDIV, MVT::v64i8,  14 }, // 2*ext+2*pmulhw sequence
439     { ISD::UREM, MVT::v64i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
440     { ISD::SDIV, MVT::v32i16,  6 }, // vpmulhw sequence
441     { ISD::SREM, MVT::v32i16,  8 }, // vpmulhw+mul+sub sequence
442     { ISD::UDIV, MVT::v32i16,  6 }, // vpmulhuw sequence
443     { ISD::UREM, MVT::v32i16,  8 }, // vpmulhuw+mul+sub sequence
444   };
445 
446   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
447        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
448       ST->hasBWI()) {
449     if (const auto *Entry =
450             CostTableLookup(AVX512BWConstCostTable, ISD, LT.second))
451       return LT.first * Entry->Cost;
452   }
453 
454   static const CostTblEntry AVX512ConstCostTable[] = {
455     { ISD::SDIV, MVT::v16i32, 15 }, // vpmuldq sequence
456     { ISD::SREM, MVT::v16i32, 17 }, // vpmuldq+mul+sub sequence
457     { ISD::UDIV, MVT::v16i32, 15 }, // vpmuludq sequence
458     { ISD::UREM, MVT::v16i32, 17 }, // vpmuludq+mul+sub sequence
459     { ISD::SDIV, MVT::v64i8,  28 }, // 4*ext+4*pmulhw sequence
460     { ISD::SREM, MVT::v64i8,  32 }, // 4*ext+4*pmulhw+mul+sub sequence
461     { ISD::UDIV, MVT::v64i8,  28 }, // 4*ext+4*pmulhw sequence
462     { ISD::UREM, MVT::v64i8,  32 }, // 4*ext+4*pmulhw+mul+sub sequence
463     { ISD::SDIV, MVT::v32i16, 12 }, // 2*vpmulhw sequence
464     { ISD::SREM, MVT::v32i16, 16 }, // 2*vpmulhw+mul+sub sequence
465     { ISD::UDIV, MVT::v32i16, 12 }, // 2*vpmulhuw sequence
466     { ISD::UREM, MVT::v32i16, 16 }, // 2*vpmulhuw+mul+sub sequence
467   };
468 
469   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
470        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
471       ST->hasAVX512()) {
472     if (const auto *Entry =
473             CostTableLookup(AVX512ConstCostTable, ISD, LT.second))
474       return LT.first * Entry->Cost;
475   }
476 
477   static const CostTblEntry AVX2ConstCostTable[] = {
478     { ISD::SDIV, MVT::v32i8,  14 }, // 2*ext+2*pmulhw sequence
479     { ISD::SREM, MVT::v32i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
480     { ISD::UDIV, MVT::v32i8,  14 }, // 2*ext+2*pmulhw sequence
481     { ISD::UREM, MVT::v32i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
482     { ISD::SDIV, MVT::v16i16,  6 }, // vpmulhw sequence
483     { ISD::SREM, MVT::v16i16,  8 }, // vpmulhw+mul+sub sequence
484     { ISD::UDIV, MVT::v16i16,  6 }, // vpmulhuw sequence
485     { ISD::UREM, MVT::v16i16,  8 }, // vpmulhuw+mul+sub sequence
486     { ISD::SDIV, MVT::v8i32,  15 }, // vpmuldq sequence
487     { ISD::SREM, MVT::v8i32,  19 }, // vpmuldq+mul+sub sequence
488     { ISD::UDIV, MVT::v8i32,  15 }, // vpmuludq sequence
489     { ISD::UREM, MVT::v8i32,  19 }, // vpmuludq+mul+sub sequence
490   };
491 
492   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
493        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
494       ST->hasAVX2()) {
495     if (const auto *Entry = CostTableLookup(AVX2ConstCostTable, ISD, LT.second))
496       return LT.first * Entry->Cost;
497   }
498 
499   static const CostTblEntry SSE2ConstCostTable[] = {
500     { ISD::SDIV, MVT::v32i8,  28+2 }, // 4*ext+4*pmulhw sequence + split.
501     { ISD::SREM, MVT::v32i8,  32+2 }, // 4*ext+4*pmulhw+mul+sub sequence + split.
502     { ISD::SDIV, MVT::v16i8,    14 }, // 2*ext+2*pmulhw sequence
503     { ISD::SREM, MVT::v16i8,    16 }, // 2*ext+2*pmulhw+mul+sub sequence
504     { ISD::UDIV, MVT::v32i8,  28+2 }, // 4*ext+4*pmulhw sequence + split.
505     { ISD::UREM, MVT::v32i8,  32+2 }, // 4*ext+4*pmulhw+mul+sub sequence + split.
506     { ISD::UDIV, MVT::v16i8,    14 }, // 2*ext+2*pmulhw sequence
507     { ISD::UREM, MVT::v16i8,    16 }, // 2*ext+2*pmulhw+mul+sub sequence
508     { ISD::SDIV, MVT::v16i16, 12+2 }, // 2*pmulhw sequence + split.
509     { ISD::SREM, MVT::v16i16, 16+2 }, // 2*pmulhw+mul+sub sequence + split.
510     { ISD::SDIV, MVT::v8i16,     6 }, // pmulhw sequence
511     { ISD::SREM, MVT::v8i16,     8 }, // pmulhw+mul+sub sequence
512     { ISD::UDIV, MVT::v16i16, 12+2 }, // 2*pmulhuw sequence + split.
513     { ISD::UREM, MVT::v16i16, 16+2 }, // 2*pmulhuw+mul+sub sequence + split.
514     { ISD::UDIV, MVT::v8i16,     6 }, // pmulhuw sequence
515     { ISD::UREM, MVT::v8i16,     8 }, // pmulhuw+mul+sub sequence
516     { ISD::SDIV, MVT::v8i32,  38+2 }, // 2*pmuludq sequence + split.
517     { ISD::SREM, MVT::v8i32,  48+2 }, // 2*pmuludq+mul+sub sequence + split.
518     { ISD::SDIV, MVT::v4i32,    19 }, // pmuludq sequence
519     { ISD::SREM, MVT::v4i32,    24 }, // pmuludq+mul+sub sequence
520     { ISD::UDIV, MVT::v8i32,  30+2 }, // 2*pmuludq sequence + split.
521     { ISD::UREM, MVT::v8i32,  40+2 }, // 2*pmuludq+mul+sub sequence + split.
522     { ISD::UDIV, MVT::v4i32,    15 }, // pmuludq sequence
523     { ISD::UREM, MVT::v4i32,    20 }, // pmuludq+mul+sub sequence
524   };
525 
526   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
527        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
528       ST->hasSSE2()) {
529     // pmuldq sequence.
530     if (ISD == ISD::SDIV && LT.second == MVT::v8i32 && ST->hasAVX())
531       return LT.first * 32;
532     if (ISD == ISD::SREM && LT.second == MVT::v8i32 && ST->hasAVX())
533       return LT.first * 38;
534     if (ISD == ISD::SDIV && LT.second == MVT::v4i32 && ST->hasSSE41())
535       return LT.first * 15;
536     if (ISD == ISD::SREM && LT.second == MVT::v4i32 && ST->hasSSE41())
537       return LT.first * 20;
538 
539     if (const auto *Entry = CostTableLookup(SSE2ConstCostTable, ISD, LT.second))
540       return LT.first * Entry->Cost;
541   }
542 
543   static const CostTblEntry AVX512BWShiftCostTable[] = {
544     { ISD::SHL,   MVT::v16i8,      4 }, // extend/vpsllvw/pack sequence.
545     { ISD::SRL,   MVT::v16i8,      4 }, // extend/vpsrlvw/pack sequence.
546     { ISD::SRA,   MVT::v16i8,      4 }, // extend/vpsravw/pack sequence.
547     { ISD::SHL,   MVT::v32i8,      4 }, // extend/vpsllvw/pack sequence.
548     { ISD::SRL,   MVT::v32i8,      4 }, // extend/vpsrlvw/pack sequence.
549     { ISD::SRA,   MVT::v32i8,      6 }, // extend/vpsravw/pack sequence.
550     { ISD::SHL,   MVT::v64i8,      6 }, // extend/vpsllvw/pack sequence.
551     { ISD::SRL,   MVT::v64i8,      7 }, // extend/vpsrlvw/pack sequence.
552     { ISD::SRA,   MVT::v64i8,     15 }, // extend/vpsravw/pack sequence.
553 
554     { ISD::SHL,   MVT::v8i16,      1 }, // vpsllvw
555     { ISD::SRL,   MVT::v8i16,      1 }, // vpsrlvw
556     { ISD::SRA,   MVT::v8i16,      1 }, // vpsravw
557     { ISD::SHL,   MVT::v16i16,     1 }, // vpsllvw
558     { ISD::SRL,   MVT::v16i16,     1 }, // vpsrlvw
559     { ISD::SRA,   MVT::v16i16,     1 }, // vpsravw
560     { ISD::SHL,   MVT::v32i16,     1 }, // vpsllvw
561     { ISD::SRL,   MVT::v32i16,     1 }, // vpsrlvw
562     { ISD::SRA,   MVT::v32i16,     1 }, // vpsravw
563   };
564 
565   if (ST->hasBWI())
566     if (const auto *Entry = CostTableLookup(AVX512BWShiftCostTable, ISD, LT.second))
567       return LT.first * Entry->Cost;
568 
569   static const CostTblEntry AVX2UniformCostTable[] = {
570     // Uniform splats are cheaper for the following instructions.
571     { ISD::SHL,  MVT::v16i16, 1 }, // psllw.
572     { ISD::SRL,  MVT::v16i16, 1 }, // psrlw.
573     { ISD::SRA,  MVT::v16i16, 1 }, // psraw.
574     { ISD::SHL,  MVT::v32i16, 2 }, // 2*psllw.
575     { ISD::SRL,  MVT::v32i16, 2 }, // 2*psrlw.
576     { ISD::SRA,  MVT::v32i16, 2 }, // 2*psraw.
577 
578     { ISD::SHL,  MVT::v8i32,  1 }, // pslld
579     { ISD::SRL,  MVT::v8i32,  1 }, // psrld
580     { ISD::SRA,  MVT::v8i32,  1 }, // psrad
581     { ISD::SHL,  MVT::v4i64,  1 }, // psllq
582     { ISD::SRL,  MVT::v4i64,  1 }, // psrlq
583   };
584 
585   if (ST->hasAVX2() &&
586       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
587        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
588     if (const auto *Entry =
589             CostTableLookup(AVX2UniformCostTable, ISD, LT.second))
590       return LT.first * Entry->Cost;
591   }
592 
593   static const CostTblEntry SSE2UniformCostTable[] = {
594     // Uniform splats are cheaper for the following instructions.
595     { ISD::SHL,  MVT::v8i16,  1 }, // psllw.
596     { ISD::SHL,  MVT::v4i32,  1 }, // pslld
597     { ISD::SHL,  MVT::v2i64,  1 }, // psllq.
598 
599     { ISD::SRL,  MVT::v8i16,  1 }, // psrlw.
600     { ISD::SRL,  MVT::v4i32,  1 }, // psrld.
601     { ISD::SRL,  MVT::v2i64,  1 }, // psrlq.
602 
603     { ISD::SRA,  MVT::v8i16,  1 }, // psraw.
604     { ISD::SRA,  MVT::v4i32,  1 }, // psrad.
605   };
606 
607   if (ST->hasSSE2() &&
608       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
609        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
610     if (const auto *Entry =
611             CostTableLookup(SSE2UniformCostTable, ISD, LT.second))
612       return LT.first * Entry->Cost;
613   }
614 
615   static const CostTblEntry AVX512DQCostTable[] = {
616     { ISD::MUL,  MVT::v2i64, 2 }, // pmullq
617     { ISD::MUL,  MVT::v4i64, 2 }, // pmullq
618     { ISD::MUL,  MVT::v8i64, 2 }  // pmullq
619   };
620 
621   // Look for AVX512DQ lowering tricks for custom cases.
622   if (ST->hasDQI())
623     if (const auto *Entry = CostTableLookup(AVX512DQCostTable, ISD, LT.second))
624       return LT.first * Entry->Cost;
625 
626   static const CostTblEntry AVX512BWCostTable[] = {
627     { ISD::SHL,   MVT::v64i8,     11 }, // vpblendvb sequence.
628     { ISD::SRL,   MVT::v64i8,     11 }, // vpblendvb sequence.
629     { ISD::SRA,   MVT::v64i8,     24 }, // vpblendvb sequence.
630   };
631 
632   // Look for AVX512BW lowering tricks for custom cases.
633   if (ST->hasBWI())
634     if (const auto *Entry = CostTableLookup(AVX512BWCostTable, ISD, LT.second))
635       return LT.first * Entry->Cost;
636 
637   static const CostTblEntry AVX512CostTable[] = {
638     { ISD::SHL,     MVT::v4i32,      1 },
639     { ISD::SRL,     MVT::v4i32,      1 },
640     { ISD::SRA,     MVT::v4i32,      1 },
641     { ISD::SHL,     MVT::v8i32,      1 },
642     { ISD::SRL,     MVT::v8i32,      1 },
643     { ISD::SRA,     MVT::v8i32,      1 },
644     { ISD::SHL,     MVT::v16i32,     1 },
645     { ISD::SRL,     MVT::v16i32,     1 },
646     { ISD::SRA,     MVT::v16i32,     1 },
647 
648     { ISD::SHL,     MVT::v2i64,      1 },
649     { ISD::SRL,     MVT::v2i64,      1 },
650     { ISD::SHL,     MVT::v4i64,      1 },
651     { ISD::SRL,     MVT::v4i64,      1 },
652     { ISD::SHL,     MVT::v8i64,      1 },
653     { ISD::SRL,     MVT::v8i64,      1 },
654 
655     { ISD::SRA,     MVT::v2i64,      1 },
656     { ISD::SRA,     MVT::v4i64,      1 },
657     { ISD::SRA,     MVT::v8i64,      1 },
658 
659     { ISD::MUL,     MVT::v16i32,     1 }, // pmulld (Skylake from agner.org)
660     { ISD::MUL,     MVT::v8i32,      1 }, // pmulld (Skylake from agner.org)
661     { ISD::MUL,     MVT::v4i32,      1 }, // pmulld (Skylake from agner.org)
662     { ISD::MUL,     MVT::v8i64,      6 }, // 3*pmuludq/3*shift/2*add
663 
664     { ISD::FNEG,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
665     { ISD::FADD,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
666     { ISD::FSUB,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
667     { ISD::FMUL,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
668     { ISD::FDIV,    MVT::f64,        4 }, // Skylake from http://www.agner.org/
669     { ISD::FDIV,    MVT::v2f64,      4 }, // Skylake from http://www.agner.org/
670     { ISD::FDIV,    MVT::v4f64,      8 }, // Skylake from http://www.agner.org/
671     { ISD::FDIV,    MVT::v8f64,     16 }, // Skylake from http://www.agner.org/
672 
673     { ISD::FNEG,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
674     { ISD::FADD,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
675     { ISD::FSUB,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
676     { ISD::FMUL,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
677     { ISD::FDIV,    MVT::f32,        3 }, // Skylake from http://www.agner.org/
678     { ISD::FDIV,    MVT::v4f32,      3 }, // Skylake from http://www.agner.org/
679     { ISD::FDIV,    MVT::v8f32,      5 }, // Skylake from http://www.agner.org/
680     { ISD::FDIV,    MVT::v16f32,    10 }, // Skylake from http://www.agner.org/
681   };
682 
683   if (ST->hasAVX512())
684     if (const auto *Entry = CostTableLookup(AVX512CostTable, ISD, LT.second))
685       return LT.first * Entry->Cost;
686 
687   static const CostTblEntry AVX2ShiftCostTable[] = {
688     // Shifts on vXi64/vXi32 on AVX2 is legal even though we declare to
689     // customize them to detect the cases where shift amount is a scalar one.
690     { ISD::SHL,     MVT::v4i32,    2 }, // vpsllvd (Haswell from agner.org)
691     { ISD::SRL,     MVT::v4i32,    2 }, // vpsrlvd (Haswell from agner.org)
692     { ISD::SRA,     MVT::v4i32,    2 }, // vpsravd (Haswell from agner.org)
693     { ISD::SHL,     MVT::v8i32,    2 }, // vpsllvd (Haswell from agner.org)
694     { ISD::SRL,     MVT::v8i32,    2 }, // vpsrlvd (Haswell from agner.org)
695     { ISD::SRA,     MVT::v8i32,    2 }, // vpsravd (Haswell from agner.org)
696     { ISD::SHL,     MVT::v2i64,    1 }, // vpsllvq (Haswell from agner.org)
697     { ISD::SRL,     MVT::v2i64,    1 }, // vpsrlvq (Haswell from agner.org)
698     { ISD::SHL,     MVT::v4i64,    1 }, // vpsllvq (Haswell from agner.org)
699     { ISD::SRL,     MVT::v4i64,    1 }, // vpsrlvq (Haswell from agner.org)
700   };
701 
702   if (ST->hasAVX512()) {
703     if (ISD == ISD::SHL && LT.second == MVT::v32i16 &&
704         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
705          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
706       // On AVX512, a packed v32i16 shift left by a constant build_vector
707       // is lowered into a vector multiply (vpmullw).
708       return getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
709                                     Op1Info, Op2Info,
710                                     TargetTransformInfo::OP_None,
711                                     TargetTransformInfo::OP_None);
712   }
713 
714   // Look for AVX2 lowering tricks (XOP is always better at v4i32 shifts).
715   if (ST->hasAVX2() && !(ST->hasXOP() && LT.second == MVT::v4i32)) {
716     if (ISD == ISD::SHL && LT.second == MVT::v16i16 &&
717         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
718          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
719       // On AVX2, a packed v16i16 shift left by a constant build_vector
720       // is lowered into a vector multiply (vpmullw).
721       return getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
722                                     Op1Info, Op2Info,
723                                     TargetTransformInfo::OP_None,
724                                     TargetTransformInfo::OP_None);
725 
726     if (const auto *Entry = CostTableLookup(AVX2ShiftCostTable, ISD, LT.second))
727       return LT.first * Entry->Cost;
728   }
729 
730   static const CostTblEntry XOPShiftCostTable[] = {
731     // 128bit shifts take 1cy, but right shifts require negation beforehand.
732     { ISD::SHL,     MVT::v16i8,    1 },
733     { ISD::SRL,     MVT::v16i8,    2 },
734     { ISD::SRA,     MVT::v16i8,    2 },
735     { ISD::SHL,     MVT::v8i16,    1 },
736     { ISD::SRL,     MVT::v8i16,    2 },
737     { ISD::SRA,     MVT::v8i16,    2 },
738     { ISD::SHL,     MVT::v4i32,    1 },
739     { ISD::SRL,     MVT::v4i32,    2 },
740     { ISD::SRA,     MVT::v4i32,    2 },
741     { ISD::SHL,     MVT::v2i64,    1 },
742     { ISD::SRL,     MVT::v2i64,    2 },
743     { ISD::SRA,     MVT::v2i64,    2 },
744     // 256bit shifts require splitting if AVX2 didn't catch them above.
745     { ISD::SHL,     MVT::v32i8,  2+2 },
746     { ISD::SRL,     MVT::v32i8,  4+2 },
747     { ISD::SRA,     MVT::v32i8,  4+2 },
748     { ISD::SHL,     MVT::v16i16, 2+2 },
749     { ISD::SRL,     MVT::v16i16, 4+2 },
750     { ISD::SRA,     MVT::v16i16, 4+2 },
751     { ISD::SHL,     MVT::v8i32,  2+2 },
752     { ISD::SRL,     MVT::v8i32,  4+2 },
753     { ISD::SRA,     MVT::v8i32,  4+2 },
754     { ISD::SHL,     MVT::v4i64,  2+2 },
755     { ISD::SRL,     MVT::v4i64,  4+2 },
756     { ISD::SRA,     MVT::v4i64,  4+2 },
757   };
758 
759   // Look for XOP lowering tricks.
760   if (ST->hasXOP()) {
761     // If the right shift is constant then we'll fold the negation so
762     // it's as cheap as a left shift.
763     int ShiftISD = ISD;
764     if ((ShiftISD == ISD::SRL || ShiftISD == ISD::SRA) &&
765         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
766          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
767       ShiftISD = ISD::SHL;
768     if (const auto *Entry =
769             CostTableLookup(XOPShiftCostTable, ShiftISD, LT.second))
770       return LT.first * Entry->Cost;
771   }
772 
773   static const CostTblEntry SSE2UniformShiftCostTable[] = {
774     // Uniform splats are cheaper for the following instructions.
775     { ISD::SHL,  MVT::v16i16, 2+2 }, // 2*psllw + split.
776     { ISD::SHL,  MVT::v8i32,  2+2 }, // 2*pslld + split.
777     { ISD::SHL,  MVT::v4i64,  2+2 }, // 2*psllq + split.
778 
779     { ISD::SRL,  MVT::v16i16, 2+2 }, // 2*psrlw + split.
780     { ISD::SRL,  MVT::v8i32,  2+2 }, // 2*psrld + split.
781     { ISD::SRL,  MVT::v4i64,  2+2 }, // 2*psrlq + split.
782 
783     { ISD::SRA,  MVT::v16i16, 2+2 }, // 2*psraw + split.
784     { ISD::SRA,  MVT::v8i32,  2+2 }, // 2*psrad + split.
785     { ISD::SRA,  MVT::v2i64,    4 }, // 2*psrad + shuffle.
786     { ISD::SRA,  MVT::v4i64,  8+2 }, // 2*(2*psrad + shuffle) + split.
787   };
788 
789   if (ST->hasSSE2() &&
790       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
791        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
792 
793     // Handle AVX2 uniform v4i64 ISD::SRA, it's not worth a table.
794     if (ISD == ISD::SRA && LT.second == MVT::v4i64 && ST->hasAVX2())
795       return LT.first * 4; // 2*psrad + shuffle.
796 
797     if (const auto *Entry =
798             CostTableLookup(SSE2UniformShiftCostTable, ISD, LT.second))
799       return LT.first * Entry->Cost;
800   }
801 
802   if (ISD == ISD::SHL &&
803       Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) {
804     MVT VT = LT.second;
805     // Vector shift left by non uniform constant can be lowered
806     // into vector multiply.
807     if (((VT == MVT::v8i16 || VT == MVT::v4i32) && ST->hasSSE2()) ||
808         ((VT == MVT::v16i16 || VT == MVT::v8i32) && ST->hasAVX()))
809       ISD = ISD::MUL;
810   }
811 
812   static const CostTblEntry AVX2CostTable[] = {
813     { ISD::SHL,  MVT::v16i8,      6 }, // vpblendvb sequence.
814     { ISD::SHL,  MVT::v32i8,      6 }, // vpblendvb sequence.
815     { ISD::SHL,  MVT::v64i8,     12 }, // 2*vpblendvb sequence.
816     { ISD::SHL,  MVT::v8i16,      5 }, // extend/vpsrlvd/pack sequence.
817     { ISD::SHL,  MVT::v16i16,     7 }, // extend/vpsrlvd/pack sequence.
818     { ISD::SHL,  MVT::v32i16,    14 }, // 2*extend/vpsrlvd/pack sequence.
819 
820     { ISD::SRL,  MVT::v16i8,      6 }, // vpblendvb sequence.
821     { ISD::SRL,  MVT::v32i8,      6 }, // vpblendvb sequence.
822     { ISD::SRL,  MVT::v64i8,     12 }, // 2*vpblendvb sequence.
823     { ISD::SRL,  MVT::v8i16,      5 }, // extend/vpsrlvd/pack sequence.
824     { ISD::SRL,  MVT::v16i16,     7 }, // extend/vpsrlvd/pack sequence.
825     { ISD::SRL,  MVT::v32i16,    14 }, // 2*extend/vpsrlvd/pack sequence.
826 
827     { ISD::SRA,  MVT::v16i8,     17 }, // vpblendvb sequence.
828     { ISD::SRA,  MVT::v32i8,     17 }, // vpblendvb sequence.
829     { ISD::SRA,  MVT::v64i8,     34 }, // 2*vpblendvb sequence.
830     { ISD::SRA,  MVT::v8i16,      5 }, // extend/vpsravd/pack sequence.
831     { ISD::SRA,  MVT::v16i16,     7 }, // extend/vpsravd/pack sequence.
832     { ISD::SRA,  MVT::v32i16,    14 }, // 2*extend/vpsravd/pack sequence.
833     { ISD::SRA,  MVT::v2i64,      2 }, // srl/xor/sub sequence.
834     { ISD::SRA,  MVT::v4i64,      2 }, // srl/xor/sub sequence.
835 
836     { ISD::SUB,  MVT::v32i8,      1 }, // psubb
837     { ISD::ADD,  MVT::v32i8,      1 }, // paddb
838     { ISD::SUB,  MVT::v16i16,     1 }, // psubw
839     { ISD::ADD,  MVT::v16i16,     1 }, // paddw
840     { ISD::SUB,  MVT::v8i32,      1 }, // psubd
841     { ISD::ADD,  MVT::v8i32,      1 }, // paddd
842     { ISD::SUB,  MVT::v4i64,      1 }, // psubq
843     { ISD::ADD,  MVT::v4i64,      1 }, // paddq
844 
845     { ISD::MUL,  MVT::v16i16,     1 }, // pmullw
846     { ISD::MUL,  MVT::v8i32,      2 }, // pmulld (Haswell from agner.org)
847     { ISD::MUL,  MVT::v4i64,      6 }, // 3*pmuludq/3*shift/2*add
848 
849     { ISD::FNEG, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
850     { ISD::FNEG, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
851     { ISD::FADD, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
852     { ISD::FADD, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
853     { ISD::FSUB, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
854     { ISD::FSUB, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
855     { ISD::FMUL, MVT::f64,        1 }, // Haswell from http://www.agner.org/
856     { ISD::FMUL, MVT::v2f64,      1 }, // Haswell from http://www.agner.org/
857     { ISD::FMUL, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
858     { ISD::FMUL, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
859 
860     { ISD::FDIV, MVT::f32,        7 }, // Haswell from http://www.agner.org/
861     { ISD::FDIV, MVT::v4f32,      7 }, // Haswell from http://www.agner.org/
862     { ISD::FDIV, MVT::v8f32,     14 }, // Haswell from http://www.agner.org/
863     { ISD::FDIV, MVT::f64,       14 }, // Haswell from http://www.agner.org/
864     { ISD::FDIV, MVT::v2f64,     14 }, // Haswell from http://www.agner.org/
865     { ISD::FDIV, MVT::v4f64,     28 }, // Haswell from http://www.agner.org/
866   };
867 
868   // Look for AVX2 lowering tricks for custom cases.
869   if (ST->hasAVX2())
870     if (const auto *Entry = CostTableLookup(AVX2CostTable, ISD, LT.second))
871       return LT.first * Entry->Cost;
872 
873   static const CostTblEntry AVX1CostTable[] = {
874     // We don't have to scalarize unsupported ops. We can issue two half-sized
875     // operations and we only need to extract the upper YMM half.
876     // Two ops + 1 extract + 1 insert = 4.
877     { ISD::MUL,     MVT::v16i16,     4 },
878     { ISD::MUL,     MVT::v8i32,      5 }, // BTVER2 from http://www.agner.org/
879     { ISD::MUL,     MVT::v4i64,     12 },
880 
881     { ISD::SUB,     MVT::v32i8,      4 },
882     { ISD::ADD,     MVT::v32i8,      4 },
883     { ISD::SUB,     MVT::v16i16,     4 },
884     { ISD::ADD,     MVT::v16i16,     4 },
885     { ISD::SUB,     MVT::v8i32,      4 },
886     { ISD::ADD,     MVT::v8i32,      4 },
887     { ISD::SUB,     MVT::v4i64,      4 },
888     { ISD::ADD,     MVT::v4i64,      4 },
889 
890     { ISD::SHL,     MVT::v32i8,     22 }, // pblendvb sequence + split.
891     { ISD::SHL,     MVT::v8i16,      6 }, // pblendvb sequence.
892     { ISD::SHL,     MVT::v16i16,    13 }, // pblendvb sequence + split.
893     { ISD::SHL,     MVT::v4i32,      3 }, // pslld/paddd/cvttps2dq/pmulld
894     { ISD::SHL,     MVT::v8i32,      9 }, // pslld/paddd/cvttps2dq/pmulld + split
895     { ISD::SHL,     MVT::v2i64,      2 }, // Shift each lane + blend.
896     { ISD::SHL,     MVT::v4i64,      6 }, // Shift each lane + blend + split.
897 
898     { ISD::SRL,     MVT::v32i8,     23 }, // pblendvb sequence + split.
899     { ISD::SRL,     MVT::v16i16,    28 }, // pblendvb sequence + split.
900     { ISD::SRL,     MVT::v4i32,      6 }, // Shift each lane + blend.
901     { ISD::SRL,     MVT::v8i32,     14 }, // Shift each lane + blend + split.
902     { ISD::SRL,     MVT::v2i64,      2 }, // Shift each lane + blend.
903     { ISD::SRL,     MVT::v4i64,      6 }, // Shift each lane + blend + split.
904 
905     { ISD::SRA,     MVT::v32i8,     44 }, // pblendvb sequence + split.
906     { ISD::SRA,     MVT::v16i16,    28 }, // pblendvb sequence + split.
907     { ISD::SRA,     MVT::v4i32,      6 }, // Shift each lane + blend.
908     { ISD::SRA,     MVT::v8i32,     14 }, // Shift each lane + blend + split.
909     { ISD::SRA,     MVT::v2i64,      5 }, // Shift each lane + blend.
910     { ISD::SRA,     MVT::v4i64,     12 }, // Shift each lane + blend + split.
911 
912     { ISD::FNEG,    MVT::v4f64,      2 }, // BTVER2 from http://www.agner.org/
913     { ISD::FNEG,    MVT::v8f32,      2 }, // BTVER2 from http://www.agner.org/
914 
915     { ISD::FMUL,    MVT::f64,        2 }, // BTVER2 from http://www.agner.org/
916     { ISD::FMUL,    MVT::v2f64,      2 }, // BTVER2 from http://www.agner.org/
917     { ISD::FMUL,    MVT::v4f64,      4 }, // BTVER2 from http://www.agner.org/
918 
919     { ISD::FDIV,    MVT::f32,       14 }, // SNB from http://www.agner.org/
920     { ISD::FDIV,    MVT::v4f32,     14 }, // SNB from http://www.agner.org/
921     { ISD::FDIV,    MVT::v8f32,     28 }, // SNB from http://www.agner.org/
922     { ISD::FDIV,    MVT::f64,       22 }, // SNB from http://www.agner.org/
923     { ISD::FDIV,    MVT::v2f64,     22 }, // SNB from http://www.agner.org/
924     { ISD::FDIV,    MVT::v4f64,     44 }, // SNB from http://www.agner.org/
925   };
926 
927   if (ST->hasAVX())
928     if (const auto *Entry = CostTableLookup(AVX1CostTable, ISD, LT.second))
929       return LT.first * Entry->Cost;
930 
931   static const CostTblEntry SSE42CostTable[] = {
932     { ISD::FADD, MVT::f64,     1 }, // Nehalem from http://www.agner.org/
933     { ISD::FADD, MVT::f32,     1 }, // Nehalem from http://www.agner.org/
934     { ISD::FADD, MVT::v2f64,   1 }, // Nehalem from http://www.agner.org/
935     { ISD::FADD, MVT::v4f32,   1 }, // Nehalem from http://www.agner.org/
936 
937     { ISD::FSUB, MVT::f64,     1 }, // Nehalem from http://www.agner.org/
938     { ISD::FSUB, MVT::f32 ,    1 }, // Nehalem from http://www.agner.org/
939     { ISD::FSUB, MVT::v2f64,   1 }, // Nehalem from http://www.agner.org/
940     { ISD::FSUB, MVT::v4f32,   1 }, // Nehalem from http://www.agner.org/
941 
942     { ISD::FMUL, MVT::f64,     1 }, // Nehalem from http://www.agner.org/
943     { ISD::FMUL, MVT::f32,     1 }, // Nehalem from http://www.agner.org/
944     { ISD::FMUL, MVT::v2f64,   1 }, // Nehalem from http://www.agner.org/
945     { ISD::FMUL, MVT::v4f32,   1 }, // Nehalem from http://www.agner.org/
946 
947     { ISD::FDIV,  MVT::f32,   14 }, // Nehalem from http://www.agner.org/
948     { ISD::FDIV,  MVT::v4f32, 14 }, // Nehalem from http://www.agner.org/
949     { ISD::FDIV,  MVT::f64,   22 }, // Nehalem from http://www.agner.org/
950     { ISD::FDIV,  MVT::v2f64, 22 }, // Nehalem from http://www.agner.org/
951 
952     { ISD::MUL,   MVT::v2i64,  6 }  // 3*pmuludq/3*shift/2*add
953   };
954 
955   if (ST->hasSSE42())
956     if (const auto *Entry = CostTableLookup(SSE42CostTable, ISD, LT.second))
957       return LT.first * Entry->Cost;
958 
959   static const CostTblEntry SSE41CostTable[] = {
960     { ISD::SHL,  MVT::v16i8,      10 }, // pblendvb sequence.
961     { ISD::SHL,  MVT::v8i16,      11 }, // pblendvb sequence.
962     { ISD::SHL,  MVT::v4i32,       4 }, // pslld/paddd/cvttps2dq/pmulld
963 
964     { ISD::SRL,  MVT::v16i8,      11 }, // pblendvb sequence.
965     { ISD::SRL,  MVT::v8i16,      13 }, // pblendvb sequence.
966     { ISD::SRL,  MVT::v4i32,      16 }, // Shift each lane + blend.
967 
968     { ISD::SRA,  MVT::v16i8,      21 }, // pblendvb sequence.
969     { ISD::SRA,  MVT::v8i16,      13 }, // pblendvb sequence.
970 
971     { ISD::MUL,  MVT::v4i32,       2 }  // pmulld (Nehalem from agner.org)
972   };
973 
974   if (ST->hasSSE41())
975     if (const auto *Entry = CostTableLookup(SSE41CostTable, ISD, LT.second))
976       return LT.first * Entry->Cost;
977 
978   static const CostTblEntry SSE2CostTable[] = {
979     // We don't correctly identify costs of casts because they are marked as
980     // custom.
981     { ISD::SHL,  MVT::v16i8,      13 }, // cmpgtb sequence.
982     { ISD::SHL,  MVT::v8i16,      25 }, // cmpgtw sequence.
983     { ISD::SHL,  MVT::v4i32,      16 }, // pslld/paddd/cvttps2dq/pmuludq.
984     { ISD::SHL,  MVT::v2i64,       4 }, // splat+shuffle sequence.
985 
986     { ISD::SRL,  MVT::v16i8,      14 }, // cmpgtb sequence.
987     { ISD::SRL,  MVT::v8i16,      16 }, // cmpgtw sequence.
988     { ISD::SRL,  MVT::v4i32,      12 }, // Shift each lane + blend.
989     { ISD::SRL,  MVT::v2i64,       4 }, // splat+shuffle sequence.
990 
991     { ISD::SRA,  MVT::v16i8,      27 }, // unpacked cmpgtb sequence.
992     { ISD::SRA,  MVT::v8i16,      16 }, // cmpgtw sequence.
993     { ISD::SRA,  MVT::v4i32,      12 }, // Shift each lane + blend.
994     { ISD::SRA,  MVT::v2i64,       8 }, // srl/xor/sub splat+shuffle sequence.
995 
996     { ISD::MUL,  MVT::v8i16,       1 }, // pmullw
997     { ISD::MUL,  MVT::v4i32,       6 }, // 3*pmuludq/4*shuffle
998     { ISD::MUL,  MVT::v2i64,       8 }, // 3*pmuludq/3*shift/2*add
999 
1000     { ISD::FDIV, MVT::f32,        23 }, // Pentium IV from http://www.agner.org/
1001     { ISD::FDIV, MVT::v4f32,      39 }, // Pentium IV from http://www.agner.org/
1002     { ISD::FDIV, MVT::f64,        38 }, // Pentium IV from http://www.agner.org/
1003     { ISD::FDIV, MVT::v2f64,      69 }, // Pentium IV from http://www.agner.org/
1004 
1005     { ISD::FNEG, MVT::f32,         1 }, // Pentium IV from http://www.agner.org/
1006     { ISD::FNEG, MVT::f64,         1 }, // Pentium IV from http://www.agner.org/
1007     { ISD::FNEG, MVT::v4f32,       1 }, // Pentium IV from http://www.agner.org/
1008     { ISD::FNEG, MVT::v2f64,       1 }, // Pentium IV from http://www.agner.org/
1009 
1010     { ISD::FADD, MVT::f32,         2 }, // Pentium IV from http://www.agner.org/
1011     { ISD::FADD, MVT::f64,         2 }, // Pentium IV from http://www.agner.org/
1012 
1013     { ISD::FSUB, MVT::f32,         2 }, // Pentium IV from http://www.agner.org/
1014     { ISD::FSUB, MVT::f64,         2 }, // Pentium IV from http://www.agner.org/
1015   };
1016 
1017   if (ST->hasSSE2())
1018     if (const auto *Entry = CostTableLookup(SSE2CostTable, ISD, LT.second))
1019       return LT.first * Entry->Cost;
1020 
1021   static const CostTblEntry SSE1CostTable[] = {
1022     { ISD::FDIV, MVT::f32,   17 }, // Pentium III from http://www.agner.org/
1023     { ISD::FDIV, MVT::v4f32, 34 }, // Pentium III from http://www.agner.org/
1024 
1025     { ISD::FNEG, MVT::f32,    2 }, // Pentium III from http://www.agner.org/
1026     { ISD::FNEG, MVT::v4f32,  2 }, // Pentium III from http://www.agner.org/
1027 
1028     { ISD::FADD, MVT::f32,    1 }, // Pentium III from http://www.agner.org/
1029     { ISD::FADD, MVT::v4f32,  2 }, // Pentium III from http://www.agner.org/
1030 
1031     { ISD::FSUB, MVT::f32,    1 }, // Pentium III from http://www.agner.org/
1032     { ISD::FSUB, MVT::v4f32,  2 }, // Pentium III from http://www.agner.org/
1033   };
1034 
1035   if (ST->hasSSE1())
1036     if (const auto *Entry = CostTableLookup(SSE1CostTable, ISD, LT.second))
1037       return LT.first * Entry->Cost;
1038 
1039   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
1040     { ISD::ADD,  MVT::i64,    1 }, // Core (Merom) from http://www.agner.org/
1041     { ISD::SUB,  MVT::i64,    1 }, // Core (Merom) from http://www.agner.org/
1042     { ISD::MUL,  MVT::i64,    2 }, // Nehalem from http://www.agner.org/
1043   };
1044 
1045   if (ST->is64Bit())
1046     if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, LT.second))
1047       return LT.first * Entry->Cost;
1048 
1049   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
1050     { ISD::ADD,  MVT::i8,    1 }, // Pentium III from http://www.agner.org/
1051     { ISD::ADD,  MVT::i16,   1 }, // Pentium III from http://www.agner.org/
1052     { ISD::ADD,  MVT::i32,   1 }, // Pentium III from http://www.agner.org/
1053 
1054     { ISD::SUB,  MVT::i8,    1 }, // Pentium III from http://www.agner.org/
1055     { ISD::SUB,  MVT::i16,   1 }, // Pentium III from http://www.agner.org/
1056     { ISD::SUB,  MVT::i32,   1 }, // Pentium III from http://www.agner.org/
1057   };
1058 
1059   if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, LT.second))
1060     return LT.first * Entry->Cost;
1061 
1062   // It is not a good idea to vectorize division. We have to scalarize it and
1063   // in the process we will often end up having to spilling regular
1064   // registers. The overhead of division is going to dominate most kernels
1065   // anyways so try hard to prevent vectorization of division - it is
1066   // generally a bad idea. Assume somewhat arbitrarily that we have to be able
1067   // to hide "20 cycles" for each lane.
1068   if (LT.second.isVector() && (ISD == ISD::SDIV || ISD == ISD::SREM ||
1069                                ISD == ISD::UDIV || ISD == ISD::UREM)) {
1070     InstructionCost ScalarCost = getArithmeticInstrCost(
1071         Opcode, Ty->getScalarType(), CostKind, Op1Info, Op2Info,
1072         TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1073     return 20 * LT.first * LT.second.getVectorNumElements() * ScalarCost;
1074   }
1075 
1076   // Fallback to the default implementation.
1077   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info);
1078 }
1079 
1080 InstructionCost X86TTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
1081                                            VectorType *BaseTp,
1082                                            ArrayRef<int> Mask, int Index,
1083                                            VectorType *SubTp) {
1084   // 64-bit packed float vectors (v2f32) are widened to type v4f32.
1085   // 64-bit packed integer vectors (v2i32) are widened to type v4i32.
1086   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, BaseTp);
1087 
1088   Kind = improveShuffleKindFromMask(Kind, Mask);
1089   // Treat Transpose as 2-op shuffles - there's no difference in lowering.
1090   if (Kind == TTI::SK_Transpose)
1091     Kind = TTI::SK_PermuteTwoSrc;
1092 
1093   // For Broadcasts we are splatting the first element from the first input
1094   // register, so only need to reference that input and all the output
1095   // registers are the same.
1096   if (Kind == TTI::SK_Broadcast)
1097     LT.first = 1;
1098 
1099   // Subvector extractions are free if they start at the beginning of a
1100   // vector and cheap if the subvectors are aligned.
1101   if (Kind == TTI::SK_ExtractSubvector && LT.second.isVector()) {
1102     int NumElts = LT.second.getVectorNumElements();
1103     if ((Index % NumElts) == 0)
1104       return 0;
1105     std::pair<InstructionCost, MVT> SubLT =
1106         TLI->getTypeLegalizationCost(DL, SubTp);
1107     if (SubLT.second.isVector()) {
1108       int NumSubElts = SubLT.second.getVectorNumElements();
1109       if ((Index % NumSubElts) == 0 && (NumElts % NumSubElts) == 0)
1110         return SubLT.first;
1111       // Handle some cases for widening legalization. For now we only handle
1112       // cases where the original subvector was naturally aligned and evenly
1113       // fit in its legalized subvector type.
1114       // FIXME: Remove some of the alignment restrictions.
1115       // FIXME: We can use permq for 64-bit or larger extracts from 256-bit
1116       // vectors.
1117       int OrigSubElts = cast<FixedVectorType>(SubTp)->getNumElements();
1118       if (NumSubElts > OrigSubElts && (Index % OrigSubElts) == 0 &&
1119           (NumSubElts % OrigSubElts) == 0 &&
1120           LT.second.getVectorElementType() ==
1121               SubLT.second.getVectorElementType() &&
1122           LT.second.getVectorElementType().getSizeInBits() ==
1123               BaseTp->getElementType()->getPrimitiveSizeInBits()) {
1124         assert(NumElts >= NumSubElts && NumElts > OrigSubElts &&
1125                "Unexpected number of elements!");
1126         auto *VecTy = FixedVectorType::get(BaseTp->getElementType(),
1127                                            LT.second.getVectorNumElements());
1128         auto *SubTy = FixedVectorType::get(BaseTp->getElementType(),
1129                                            SubLT.second.getVectorNumElements());
1130         int ExtractIndex = alignDown((Index % NumElts), NumSubElts);
1131         InstructionCost ExtractCost = getShuffleCost(
1132             TTI::SK_ExtractSubvector, VecTy, None, ExtractIndex, SubTy);
1133 
1134         // If the original size is 32-bits or more, we can use pshufd. Otherwise
1135         // if we have SSSE3 we can use pshufb.
1136         if (SubTp->getPrimitiveSizeInBits() >= 32 || ST->hasSSSE3())
1137           return ExtractCost + 1; // pshufd or pshufb
1138 
1139         assert(SubTp->getPrimitiveSizeInBits() == 16 &&
1140                "Unexpected vector size");
1141 
1142         return ExtractCost + 2; // worst case pshufhw + pshufd
1143       }
1144     }
1145   }
1146 
1147   // Subvector insertions are cheap if the subvectors are aligned.
1148   // Note that in general, the insertion starting at the beginning of a vector
1149   // isn't free, because we need to preserve the rest of the wide vector.
1150   if (Kind == TTI::SK_InsertSubvector && LT.second.isVector()) {
1151     int NumElts = LT.second.getVectorNumElements();
1152     std::pair<InstructionCost, MVT> SubLT =
1153         TLI->getTypeLegalizationCost(DL, SubTp);
1154     if (SubLT.second.isVector()) {
1155       int NumSubElts = SubLT.second.getVectorNumElements();
1156       if ((Index % NumSubElts) == 0 && (NumElts % NumSubElts) == 0)
1157         return SubLT.first;
1158     }
1159 
1160     // If the insertion isn't aligned, treat it like a 2-op shuffle.
1161     Kind = TTI::SK_PermuteTwoSrc;
1162   }
1163 
1164   // Handle some common (illegal) sub-vector types as they are often very cheap
1165   // to shuffle even on targets without PSHUFB.
1166   EVT VT = TLI->getValueType(DL, BaseTp);
1167   if (VT.isSimple() && VT.isVector() && VT.getSizeInBits() < 128 &&
1168       !ST->hasSSSE3()) {
1169      static const CostTblEntry SSE2SubVectorShuffleTbl[] = {
1170       {TTI::SK_Broadcast,        MVT::v4i16, 1}, // pshuflw
1171       {TTI::SK_Broadcast,        MVT::v2i16, 1}, // pshuflw
1172       {TTI::SK_Broadcast,        MVT::v8i8,  2}, // punpck/pshuflw
1173       {TTI::SK_Broadcast,        MVT::v4i8,  2}, // punpck/pshuflw
1174       {TTI::SK_Broadcast,        MVT::v2i8,  1}, // punpck
1175 
1176       {TTI::SK_Reverse,          MVT::v4i16, 1}, // pshuflw
1177       {TTI::SK_Reverse,          MVT::v2i16, 1}, // pshuflw
1178       {TTI::SK_Reverse,          MVT::v4i8,  3}, // punpck/pshuflw/packus
1179       {TTI::SK_Reverse,          MVT::v2i8,  1}, // punpck
1180 
1181       {TTI::SK_PermuteTwoSrc,    MVT::v4i16, 2}, // punpck/pshuflw
1182       {TTI::SK_PermuteTwoSrc,    MVT::v2i16, 2}, // punpck/pshuflw
1183       {TTI::SK_PermuteTwoSrc,    MVT::v8i8,  7}, // punpck/pshuflw
1184       {TTI::SK_PermuteTwoSrc,    MVT::v4i8,  4}, // punpck/pshuflw
1185       {TTI::SK_PermuteTwoSrc,    MVT::v2i8,  2}, // punpck
1186 
1187       {TTI::SK_PermuteSingleSrc, MVT::v4i16, 1}, // pshuflw
1188       {TTI::SK_PermuteSingleSrc, MVT::v2i16, 1}, // pshuflw
1189       {TTI::SK_PermuteSingleSrc, MVT::v8i8,  5}, // punpck/pshuflw
1190       {TTI::SK_PermuteSingleSrc, MVT::v4i8,  3}, // punpck/pshuflw
1191       {TTI::SK_PermuteSingleSrc, MVT::v2i8,  1}, // punpck
1192     };
1193 
1194     if (ST->hasSSE2())
1195       if (const auto *Entry =
1196               CostTableLookup(SSE2SubVectorShuffleTbl, Kind, VT.getSimpleVT()))
1197         return Entry->Cost;
1198   }
1199 
1200   // We are going to permute multiple sources and the result will be in multiple
1201   // destinations. Providing an accurate cost only for splits where the element
1202   // type remains the same.
1203   if (Kind == TTI::SK_PermuteSingleSrc && LT.first != 1) {
1204     MVT LegalVT = LT.second;
1205     if (LegalVT.isVector() &&
1206         LegalVT.getVectorElementType().getSizeInBits() ==
1207             BaseTp->getElementType()->getPrimitiveSizeInBits() &&
1208         LegalVT.getVectorNumElements() <
1209             cast<FixedVectorType>(BaseTp)->getNumElements()) {
1210 
1211       unsigned VecTySize = DL.getTypeStoreSize(BaseTp);
1212       unsigned LegalVTSize = LegalVT.getStoreSize();
1213       // Number of source vectors after legalization:
1214       unsigned NumOfSrcs = (VecTySize + LegalVTSize - 1) / LegalVTSize;
1215       // Number of destination vectors after legalization:
1216       InstructionCost NumOfDests = LT.first;
1217 
1218       auto *SingleOpTy = FixedVectorType::get(BaseTp->getElementType(),
1219                                               LegalVT.getVectorNumElements());
1220 
1221       InstructionCost NumOfShuffles = (NumOfSrcs - 1) * NumOfDests;
1222       return NumOfShuffles * getShuffleCost(TTI::SK_PermuteTwoSrc, SingleOpTy,
1223                                             None, 0, nullptr);
1224     }
1225 
1226     return BaseT::getShuffleCost(Kind, BaseTp, Mask, Index, SubTp);
1227   }
1228 
1229   // For 2-input shuffles, we must account for splitting the 2 inputs into many.
1230   if (Kind == TTI::SK_PermuteTwoSrc && LT.first != 1) {
1231     // We assume that source and destination have the same vector type.
1232     InstructionCost NumOfDests = LT.first;
1233     InstructionCost NumOfShufflesPerDest = LT.first * 2 - 1;
1234     LT.first = NumOfDests * NumOfShufflesPerDest;
1235   }
1236 
1237   static const CostTblEntry AVX512FP16ShuffleTbl[] = {
1238       {TTI::SK_Broadcast, MVT::v32f16, 1}, // vpbroadcastw
1239       {TTI::SK_Broadcast, MVT::v16f16, 1}, // vpbroadcastw
1240       {TTI::SK_Broadcast, MVT::v8f16, 1},  // vpbroadcastw
1241 
1242       {TTI::SK_Reverse, MVT::v32f16, 2}, // vpermw
1243       {TTI::SK_Reverse, MVT::v16f16, 2}, // vpermw
1244       {TTI::SK_Reverse, MVT::v8f16, 1},  // vpshufb
1245 
1246       {TTI::SK_PermuteSingleSrc, MVT::v32f16, 2}, // vpermw
1247       {TTI::SK_PermuteSingleSrc, MVT::v16f16, 2}, // vpermw
1248       {TTI::SK_PermuteSingleSrc, MVT::v8f16, 1},  // vpshufb
1249 
1250       {TTI::SK_PermuteTwoSrc, MVT::v32f16, 2}, // vpermt2w
1251       {TTI::SK_PermuteTwoSrc, MVT::v16f16, 2}, // vpermt2w
1252       {TTI::SK_PermuteTwoSrc, MVT::v8f16, 2}   // vpermt2w
1253   };
1254 
1255   if (!ST->useSoftFloat() && ST->hasFP16())
1256     if (const auto *Entry =
1257             CostTableLookup(AVX512FP16ShuffleTbl, Kind, LT.second))
1258       return LT.first * Entry->Cost;
1259 
1260   static const CostTblEntry AVX512VBMIShuffleTbl[] = {
1261       {TTI::SK_Reverse, MVT::v64i8, 1}, // vpermb
1262       {TTI::SK_Reverse, MVT::v32i8, 1}, // vpermb
1263 
1264       {TTI::SK_PermuteSingleSrc, MVT::v64i8, 1}, // vpermb
1265       {TTI::SK_PermuteSingleSrc, MVT::v32i8, 1}, // vpermb
1266 
1267       {TTI::SK_PermuteTwoSrc, MVT::v64i8, 2}, // vpermt2b
1268       {TTI::SK_PermuteTwoSrc, MVT::v32i8, 2}, // vpermt2b
1269       {TTI::SK_PermuteTwoSrc, MVT::v16i8, 2}  // vpermt2b
1270   };
1271 
1272   if (ST->hasVBMI())
1273     if (const auto *Entry =
1274             CostTableLookup(AVX512VBMIShuffleTbl, Kind, LT.second))
1275       return LT.first * Entry->Cost;
1276 
1277   static const CostTblEntry AVX512BWShuffleTbl[] = {
1278       {TTI::SK_Broadcast, MVT::v32i16, 1}, // vpbroadcastw
1279       {TTI::SK_Broadcast, MVT::v64i8, 1},  // vpbroadcastb
1280 
1281       {TTI::SK_Reverse, MVT::v32i16, 2}, // vpermw
1282       {TTI::SK_Reverse, MVT::v16i16, 2}, // vpermw
1283       {TTI::SK_Reverse, MVT::v64i8, 2},  // pshufb + vshufi64x2
1284 
1285       {TTI::SK_PermuteSingleSrc, MVT::v32i16, 2}, // vpermw
1286       {TTI::SK_PermuteSingleSrc, MVT::v16i16, 2}, // vpermw
1287       {TTI::SK_PermuteSingleSrc, MVT::v64i8, 8},  // extend to v32i16
1288 
1289       {TTI::SK_PermuteTwoSrc, MVT::v32i16, 2}, // vpermt2w
1290       {TTI::SK_PermuteTwoSrc, MVT::v16i16, 2}, // vpermt2w
1291       {TTI::SK_PermuteTwoSrc, MVT::v8i16, 2},  // vpermt2w
1292       {TTI::SK_PermuteTwoSrc, MVT::v64i8, 19}, // 6 * v32i8 + 1
1293 
1294       {TTI::SK_Select, MVT::v32i16, 1}, // vblendmw
1295       {TTI::SK_Select, MVT::v64i8,  1}, // vblendmb
1296   };
1297 
1298   if (ST->hasBWI())
1299     if (const auto *Entry =
1300             CostTableLookup(AVX512BWShuffleTbl, Kind, LT.second))
1301       return LT.first * Entry->Cost;
1302 
1303   static const CostTblEntry AVX512ShuffleTbl[] = {
1304       {TTI::SK_Broadcast, MVT::v8f64, 1},  // vbroadcastpd
1305       {TTI::SK_Broadcast, MVT::v16f32, 1}, // vbroadcastps
1306       {TTI::SK_Broadcast, MVT::v8i64, 1},  // vpbroadcastq
1307       {TTI::SK_Broadcast, MVT::v16i32, 1}, // vpbroadcastd
1308       {TTI::SK_Broadcast, MVT::v32i16, 1}, // vpbroadcastw
1309       {TTI::SK_Broadcast, MVT::v64i8, 1},  // vpbroadcastb
1310 
1311       {TTI::SK_Reverse, MVT::v8f64, 1},  // vpermpd
1312       {TTI::SK_Reverse, MVT::v16f32, 1}, // vpermps
1313       {TTI::SK_Reverse, MVT::v8i64, 1},  // vpermq
1314       {TTI::SK_Reverse, MVT::v16i32, 1}, // vpermd
1315       {TTI::SK_Reverse, MVT::v32i16, 7}, // per mca
1316       {TTI::SK_Reverse, MVT::v64i8,  7}, // per mca
1317 
1318       {TTI::SK_PermuteSingleSrc, MVT::v8f64, 1},  // vpermpd
1319       {TTI::SK_PermuteSingleSrc, MVT::v4f64, 1},  // vpermpd
1320       {TTI::SK_PermuteSingleSrc, MVT::v2f64, 1},  // vpermpd
1321       {TTI::SK_PermuteSingleSrc, MVT::v16f32, 1}, // vpermps
1322       {TTI::SK_PermuteSingleSrc, MVT::v8f32, 1},  // vpermps
1323       {TTI::SK_PermuteSingleSrc, MVT::v4f32, 1},  // vpermps
1324       {TTI::SK_PermuteSingleSrc, MVT::v8i64, 1},  // vpermq
1325       {TTI::SK_PermuteSingleSrc, MVT::v4i64, 1},  // vpermq
1326       {TTI::SK_PermuteSingleSrc, MVT::v2i64, 1},  // vpermq
1327       {TTI::SK_PermuteSingleSrc, MVT::v16i32, 1}, // vpermd
1328       {TTI::SK_PermuteSingleSrc, MVT::v8i32, 1},  // vpermd
1329       {TTI::SK_PermuteSingleSrc, MVT::v4i32, 1},  // vpermd
1330       {TTI::SK_PermuteSingleSrc, MVT::v16i8, 1},  // pshufb
1331 
1332       {TTI::SK_PermuteTwoSrc, MVT::v8f64, 1},  // vpermt2pd
1333       {TTI::SK_PermuteTwoSrc, MVT::v16f32, 1}, // vpermt2ps
1334       {TTI::SK_PermuteTwoSrc, MVT::v8i64, 1},  // vpermt2q
1335       {TTI::SK_PermuteTwoSrc, MVT::v16i32, 1}, // vpermt2d
1336       {TTI::SK_PermuteTwoSrc, MVT::v4f64, 1},  // vpermt2pd
1337       {TTI::SK_PermuteTwoSrc, MVT::v8f32, 1},  // vpermt2ps
1338       {TTI::SK_PermuteTwoSrc, MVT::v4i64, 1},  // vpermt2q
1339       {TTI::SK_PermuteTwoSrc, MVT::v8i32, 1},  // vpermt2d
1340       {TTI::SK_PermuteTwoSrc, MVT::v2f64, 1},  // vpermt2pd
1341       {TTI::SK_PermuteTwoSrc, MVT::v4f32, 1},  // vpermt2ps
1342       {TTI::SK_PermuteTwoSrc, MVT::v2i64, 1},  // vpermt2q
1343       {TTI::SK_PermuteTwoSrc, MVT::v4i32, 1},  // vpermt2d
1344 
1345       // FIXME: This just applies the type legalization cost rules above
1346       // assuming these completely split.
1347       {TTI::SK_PermuteSingleSrc, MVT::v32i16, 14},
1348       {TTI::SK_PermuteSingleSrc, MVT::v64i8,  14},
1349       {TTI::SK_PermuteTwoSrc,    MVT::v32i16, 42},
1350       {TTI::SK_PermuteTwoSrc,    MVT::v64i8,  42},
1351 
1352       {TTI::SK_Select, MVT::v32i16, 1}, // vpternlogq
1353       {TTI::SK_Select, MVT::v64i8,  1}, // vpternlogq
1354       {TTI::SK_Select, MVT::v8f64,  1}, // vblendmpd
1355       {TTI::SK_Select, MVT::v16f32, 1}, // vblendmps
1356       {TTI::SK_Select, MVT::v8i64,  1}, // vblendmq
1357       {TTI::SK_Select, MVT::v16i32, 1}, // vblendmd
1358   };
1359 
1360   if (ST->hasAVX512())
1361     if (const auto *Entry = CostTableLookup(AVX512ShuffleTbl, Kind, LT.second))
1362       return LT.first * Entry->Cost;
1363 
1364   static const CostTblEntry AVX2ShuffleTbl[] = {
1365       {TTI::SK_Broadcast, MVT::v4f64, 1},  // vbroadcastpd
1366       {TTI::SK_Broadcast, MVT::v8f32, 1},  // vbroadcastps
1367       {TTI::SK_Broadcast, MVT::v4i64, 1},  // vpbroadcastq
1368       {TTI::SK_Broadcast, MVT::v8i32, 1},  // vpbroadcastd
1369       {TTI::SK_Broadcast, MVT::v16i16, 1}, // vpbroadcastw
1370       {TTI::SK_Broadcast, MVT::v32i8, 1},  // vpbroadcastb
1371 
1372       {TTI::SK_Reverse, MVT::v4f64, 1},  // vpermpd
1373       {TTI::SK_Reverse, MVT::v8f32, 1},  // vpermps
1374       {TTI::SK_Reverse, MVT::v4i64, 1},  // vpermq
1375       {TTI::SK_Reverse, MVT::v8i32, 1},  // vpermd
1376       {TTI::SK_Reverse, MVT::v16i16, 2}, // vperm2i128 + pshufb
1377       {TTI::SK_Reverse, MVT::v32i8, 2},  // vperm2i128 + pshufb
1378 
1379       {TTI::SK_Select, MVT::v16i16, 1}, // vpblendvb
1380       {TTI::SK_Select, MVT::v32i8, 1},  // vpblendvb
1381 
1382       {TTI::SK_PermuteSingleSrc, MVT::v4f64, 1},  // vpermpd
1383       {TTI::SK_PermuteSingleSrc, MVT::v8f32, 1},  // vpermps
1384       {TTI::SK_PermuteSingleSrc, MVT::v4i64, 1},  // vpermq
1385       {TTI::SK_PermuteSingleSrc, MVT::v8i32, 1},  // vpermd
1386       {TTI::SK_PermuteSingleSrc, MVT::v16i16, 4}, // vperm2i128 + 2*vpshufb
1387                                                   // + vpblendvb
1388       {TTI::SK_PermuteSingleSrc, MVT::v32i8, 4},  // vperm2i128 + 2*vpshufb
1389                                                   // + vpblendvb
1390 
1391       {TTI::SK_PermuteTwoSrc, MVT::v4f64, 3},  // 2*vpermpd + vblendpd
1392       {TTI::SK_PermuteTwoSrc, MVT::v8f32, 3},  // 2*vpermps + vblendps
1393       {TTI::SK_PermuteTwoSrc, MVT::v4i64, 3},  // 2*vpermq + vpblendd
1394       {TTI::SK_PermuteTwoSrc, MVT::v8i32, 3},  // 2*vpermd + vpblendd
1395       {TTI::SK_PermuteTwoSrc, MVT::v16i16, 7}, // 2*vperm2i128 + 4*vpshufb
1396                                                // + vpblendvb
1397       {TTI::SK_PermuteTwoSrc, MVT::v32i8, 7},  // 2*vperm2i128 + 4*vpshufb
1398                                                // + vpblendvb
1399   };
1400 
1401   if (ST->hasAVX2())
1402     if (const auto *Entry = CostTableLookup(AVX2ShuffleTbl, Kind, LT.second))
1403       return LT.first * Entry->Cost;
1404 
1405   static const CostTblEntry XOPShuffleTbl[] = {
1406       {TTI::SK_PermuteSingleSrc, MVT::v4f64, 2},  // vperm2f128 + vpermil2pd
1407       {TTI::SK_PermuteSingleSrc, MVT::v8f32, 2},  // vperm2f128 + vpermil2ps
1408       {TTI::SK_PermuteSingleSrc, MVT::v4i64, 2},  // vperm2f128 + vpermil2pd
1409       {TTI::SK_PermuteSingleSrc, MVT::v8i32, 2},  // vperm2f128 + vpermil2ps
1410       {TTI::SK_PermuteSingleSrc, MVT::v16i16, 4}, // vextractf128 + 2*vpperm
1411                                                   // + vinsertf128
1412       {TTI::SK_PermuteSingleSrc, MVT::v32i8, 4},  // vextractf128 + 2*vpperm
1413                                                   // + vinsertf128
1414 
1415       {TTI::SK_PermuteTwoSrc, MVT::v16i16, 9}, // 2*vextractf128 + 6*vpperm
1416                                                // + vinsertf128
1417       {TTI::SK_PermuteTwoSrc, MVT::v8i16, 1},  // vpperm
1418       {TTI::SK_PermuteTwoSrc, MVT::v32i8, 9},  // 2*vextractf128 + 6*vpperm
1419                                                // + vinsertf128
1420       {TTI::SK_PermuteTwoSrc, MVT::v16i8, 1},  // vpperm
1421   };
1422 
1423   if (ST->hasXOP())
1424     if (const auto *Entry = CostTableLookup(XOPShuffleTbl, Kind, LT.second))
1425       return LT.first * Entry->Cost;
1426 
1427   static const CostTblEntry AVX1ShuffleTbl[] = {
1428       {TTI::SK_Broadcast, MVT::v4f64, 2},  // vperm2f128 + vpermilpd
1429       {TTI::SK_Broadcast, MVT::v8f32, 2},  // vperm2f128 + vpermilps
1430       {TTI::SK_Broadcast, MVT::v4i64, 2},  // vperm2f128 + vpermilpd
1431       {TTI::SK_Broadcast, MVT::v8i32, 2},  // vperm2f128 + vpermilps
1432       {TTI::SK_Broadcast, MVT::v16i16, 3}, // vpshuflw + vpshufd + vinsertf128
1433       {TTI::SK_Broadcast, MVT::v32i8, 2},  // vpshufb + vinsertf128
1434 
1435       {TTI::SK_Reverse, MVT::v4f64, 2},  // vperm2f128 + vpermilpd
1436       {TTI::SK_Reverse, MVT::v8f32, 2},  // vperm2f128 + vpermilps
1437       {TTI::SK_Reverse, MVT::v4i64, 2},  // vperm2f128 + vpermilpd
1438       {TTI::SK_Reverse, MVT::v8i32, 2},  // vperm2f128 + vpermilps
1439       {TTI::SK_Reverse, MVT::v16i16, 4}, // vextractf128 + 2*pshufb
1440                                          // + vinsertf128
1441       {TTI::SK_Reverse, MVT::v32i8, 4},  // vextractf128 + 2*pshufb
1442                                          // + vinsertf128
1443 
1444       {TTI::SK_Select, MVT::v4i64, 1},  // vblendpd
1445       {TTI::SK_Select, MVT::v4f64, 1},  // vblendpd
1446       {TTI::SK_Select, MVT::v8i32, 1},  // vblendps
1447       {TTI::SK_Select, MVT::v8f32, 1},  // vblendps
1448       {TTI::SK_Select, MVT::v16i16, 3}, // vpand + vpandn + vpor
1449       {TTI::SK_Select, MVT::v32i8, 3},  // vpand + vpandn + vpor
1450 
1451       {TTI::SK_PermuteSingleSrc, MVT::v4f64, 2},  // vperm2f128 + vshufpd
1452       {TTI::SK_PermuteSingleSrc, MVT::v4i64, 2},  // vperm2f128 + vshufpd
1453       {TTI::SK_PermuteSingleSrc, MVT::v8f32, 4},  // 2*vperm2f128 + 2*vshufps
1454       {TTI::SK_PermuteSingleSrc, MVT::v8i32, 4},  // 2*vperm2f128 + 2*vshufps
1455       {TTI::SK_PermuteSingleSrc, MVT::v16i16, 8}, // vextractf128 + 4*pshufb
1456                                                   // + 2*por + vinsertf128
1457       {TTI::SK_PermuteSingleSrc, MVT::v32i8, 8},  // vextractf128 + 4*pshufb
1458                                                   // + 2*por + vinsertf128
1459 
1460       {TTI::SK_PermuteTwoSrc, MVT::v4f64, 3},   // 2*vperm2f128 + vshufpd
1461       {TTI::SK_PermuteTwoSrc, MVT::v4i64, 3},   // 2*vperm2f128 + vshufpd
1462       {TTI::SK_PermuteTwoSrc, MVT::v8f32, 4},   // 2*vperm2f128 + 2*vshufps
1463       {TTI::SK_PermuteTwoSrc, MVT::v8i32, 4},   // 2*vperm2f128 + 2*vshufps
1464       {TTI::SK_PermuteTwoSrc, MVT::v16i16, 15}, // 2*vextractf128 + 8*pshufb
1465                                                 // + 4*por + vinsertf128
1466       {TTI::SK_PermuteTwoSrc, MVT::v32i8, 15},  // 2*vextractf128 + 8*pshufb
1467                                                 // + 4*por + vinsertf128
1468   };
1469 
1470   if (ST->hasAVX())
1471     if (const auto *Entry = CostTableLookup(AVX1ShuffleTbl, Kind, LT.second))
1472       return LT.first * Entry->Cost;
1473 
1474   static const CostTblEntry SSE41ShuffleTbl[] = {
1475       {TTI::SK_Select, MVT::v2i64, 1}, // pblendw
1476       {TTI::SK_Select, MVT::v2f64, 1}, // movsd
1477       {TTI::SK_Select, MVT::v4i32, 1}, // pblendw
1478       {TTI::SK_Select, MVT::v4f32, 1}, // blendps
1479       {TTI::SK_Select, MVT::v8i16, 1}, // pblendw
1480       {TTI::SK_Select, MVT::v16i8, 1}  // pblendvb
1481   };
1482 
1483   if (ST->hasSSE41())
1484     if (const auto *Entry = CostTableLookup(SSE41ShuffleTbl, Kind, LT.second))
1485       return LT.first * Entry->Cost;
1486 
1487   static const CostTblEntry SSSE3ShuffleTbl[] = {
1488       {TTI::SK_Broadcast, MVT::v8i16, 1}, // pshufb
1489       {TTI::SK_Broadcast, MVT::v16i8, 1}, // pshufb
1490 
1491       {TTI::SK_Reverse, MVT::v8i16, 1}, // pshufb
1492       {TTI::SK_Reverse, MVT::v16i8, 1}, // pshufb
1493 
1494       {TTI::SK_Select, MVT::v8i16, 3}, // 2*pshufb + por
1495       {TTI::SK_Select, MVT::v16i8, 3}, // 2*pshufb + por
1496 
1497       {TTI::SK_PermuteSingleSrc, MVT::v8i16, 1}, // pshufb
1498       {TTI::SK_PermuteSingleSrc, MVT::v16i8, 1}, // pshufb
1499 
1500       {TTI::SK_PermuteTwoSrc, MVT::v8i16, 3}, // 2*pshufb + por
1501       {TTI::SK_PermuteTwoSrc, MVT::v16i8, 3}, // 2*pshufb + por
1502   };
1503 
1504   if (ST->hasSSSE3())
1505     if (const auto *Entry = CostTableLookup(SSSE3ShuffleTbl, Kind, LT.second))
1506       return LT.first * Entry->Cost;
1507 
1508   static const CostTblEntry SSE2ShuffleTbl[] = {
1509       {TTI::SK_Broadcast, MVT::v2f64, 1}, // shufpd
1510       {TTI::SK_Broadcast, MVT::v2i64, 1}, // pshufd
1511       {TTI::SK_Broadcast, MVT::v4i32, 1}, // pshufd
1512       {TTI::SK_Broadcast, MVT::v8i16, 2}, // pshuflw + pshufd
1513       {TTI::SK_Broadcast, MVT::v16i8, 3}, // unpck + pshuflw + pshufd
1514 
1515       {TTI::SK_Reverse, MVT::v2f64, 1}, // shufpd
1516       {TTI::SK_Reverse, MVT::v2i64, 1}, // pshufd
1517       {TTI::SK_Reverse, MVT::v4i32, 1}, // pshufd
1518       {TTI::SK_Reverse, MVT::v8i16, 3}, // pshuflw + pshufhw + pshufd
1519       {TTI::SK_Reverse, MVT::v16i8, 9}, // 2*pshuflw + 2*pshufhw
1520                                         // + 2*pshufd + 2*unpck + packus
1521 
1522       {TTI::SK_Select, MVT::v2i64, 1}, // movsd
1523       {TTI::SK_Select, MVT::v2f64, 1}, // movsd
1524       {TTI::SK_Select, MVT::v4i32, 2}, // 2*shufps
1525       {TTI::SK_Select, MVT::v8i16, 3}, // pand + pandn + por
1526       {TTI::SK_Select, MVT::v16i8, 3}, // pand + pandn + por
1527 
1528       {TTI::SK_PermuteSingleSrc, MVT::v2f64, 1}, // shufpd
1529       {TTI::SK_PermuteSingleSrc, MVT::v2i64, 1}, // pshufd
1530       {TTI::SK_PermuteSingleSrc, MVT::v4i32, 1}, // pshufd
1531       {TTI::SK_PermuteSingleSrc, MVT::v8i16, 5}, // 2*pshuflw + 2*pshufhw
1532                                                   // + pshufd/unpck
1533     { TTI::SK_PermuteSingleSrc, MVT::v16i8, 10 }, // 2*pshuflw + 2*pshufhw
1534                                                   // + 2*pshufd + 2*unpck + 2*packus
1535 
1536     { TTI::SK_PermuteTwoSrc,    MVT::v2f64,  1 }, // shufpd
1537     { TTI::SK_PermuteTwoSrc,    MVT::v2i64,  1 }, // shufpd
1538     { TTI::SK_PermuteTwoSrc,    MVT::v4i32,  2 }, // 2*{unpck,movsd,pshufd}
1539     { TTI::SK_PermuteTwoSrc,    MVT::v8i16,  8 }, // blend+permute
1540     { TTI::SK_PermuteTwoSrc,    MVT::v16i8, 13 }, // blend+permute
1541   };
1542 
1543   if (ST->hasSSE2())
1544     if (const auto *Entry = CostTableLookup(SSE2ShuffleTbl, Kind, LT.second))
1545       return LT.first * Entry->Cost;
1546 
1547   static const CostTblEntry SSE1ShuffleTbl[] = {
1548     { TTI::SK_Broadcast,        MVT::v4f32, 1 }, // shufps
1549     { TTI::SK_Reverse,          MVT::v4f32, 1 }, // shufps
1550     { TTI::SK_Select,           MVT::v4f32, 2 }, // 2*shufps
1551     { TTI::SK_PermuteSingleSrc, MVT::v4f32, 1 }, // shufps
1552     { TTI::SK_PermuteTwoSrc,    MVT::v4f32, 2 }, // 2*shufps
1553   };
1554 
1555   if (ST->hasSSE1())
1556     if (const auto *Entry = CostTableLookup(SSE1ShuffleTbl, Kind, LT.second))
1557       return LT.first * Entry->Cost;
1558 
1559   return BaseT::getShuffleCost(Kind, BaseTp, Mask, Index, SubTp);
1560 }
1561 
1562 InstructionCost X86TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst,
1563                                              Type *Src,
1564                                              TTI::CastContextHint CCH,
1565                                              TTI::TargetCostKind CostKind,
1566                                              const Instruction *I) {
1567   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1568   assert(ISD && "Invalid opcode");
1569 
1570   // TODO: Allow non-throughput costs that aren't binary.
1571   auto AdjustCost = [&CostKind](InstructionCost Cost) -> InstructionCost {
1572     if (CostKind != TTI::TCK_RecipThroughput)
1573       return Cost == 0 ? 0 : 1;
1574     return Cost;
1575   };
1576 
1577   // The cost tables include both specific, custom (non-legal) src/dst type
1578   // conversions and generic, legalized types. We test for customs first, before
1579   // falling back to legalization.
1580   // FIXME: Need a better design of the cost table to handle non-simple types of
1581   // potential massive combinations (elem_num x src_type x dst_type).
1582   static const TypeConversionCostTblEntry AVX512BWConversionTbl[] {
1583     { ISD::SIGN_EXTEND, MVT::v32i16, MVT::v32i8, 1 },
1584     { ISD::ZERO_EXTEND, MVT::v32i16, MVT::v32i8, 1 },
1585 
1586     // Mask sign extend has an instruction.
1587     { ISD::SIGN_EXTEND, MVT::v2i8,   MVT::v2i1,  1 },
1588     { ISD::SIGN_EXTEND, MVT::v2i16,  MVT::v2i1,  1 },
1589     { ISD::SIGN_EXTEND, MVT::v4i8,   MVT::v4i1,  1 },
1590     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i1,  1 },
1591     { ISD::SIGN_EXTEND, MVT::v8i8,   MVT::v8i1,  1 },
1592     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i1,  1 },
1593     { ISD::SIGN_EXTEND, MVT::v16i8,  MVT::v16i1, 1 },
1594     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1, 1 },
1595     { ISD::SIGN_EXTEND, MVT::v32i8,  MVT::v32i1, 1 },
1596     { ISD::SIGN_EXTEND, MVT::v32i16, MVT::v32i1, 1 },
1597     { ISD::SIGN_EXTEND, MVT::v64i8,  MVT::v64i1, 1 },
1598 
1599     // Mask zero extend is a sext + shift.
1600     { ISD::ZERO_EXTEND, MVT::v2i8,   MVT::v2i1,  2 },
1601     { ISD::ZERO_EXTEND, MVT::v2i16,  MVT::v2i1,  2 },
1602     { ISD::ZERO_EXTEND, MVT::v4i8,   MVT::v4i1,  2 },
1603     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i1,  2 },
1604     { ISD::ZERO_EXTEND, MVT::v8i8,   MVT::v8i1,  2 },
1605     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i1,  2 },
1606     { ISD::ZERO_EXTEND, MVT::v16i8,  MVT::v16i1, 2 },
1607     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1, 2 },
1608     { ISD::ZERO_EXTEND, MVT::v32i8,  MVT::v32i1, 2 },
1609     { ISD::ZERO_EXTEND, MVT::v32i16, MVT::v32i1, 2 },
1610     { ISD::ZERO_EXTEND, MVT::v64i8,  MVT::v64i1, 2 },
1611 
1612     { ISD::TRUNCATE,    MVT::v32i8,  MVT::v32i16, 2 },
1613     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 2 }, // widen to zmm
1614     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   2 }, // widen to zmm
1615     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  2 }, // widen to zmm
1616     { ISD::TRUNCATE,    MVT::v2i8,   MVT::v2i16,  2 }, // vpmovwb
1617     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   2 }, // widen to zmm
1618     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i16,  2 }, // widen to zmm
1619     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i16,  2 }, // vpmovwb
1620     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i8,   2 }, // widen to zmm
1621     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i16,  2 }, // widen to zmm
1622     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i16,  2 }, // vpmovwb
1623     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i8,  2 }, // widen to zmm
1624     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i16, 2 }, // widen to zmm
1625     { ISD::TRUNCATE,    MVT::v32i1,  MVT::v32i8,  2 }, // widen to zmm
1626     { ISD::TRUNCATE,    MVT::v32i1,  MVT::v32i16, 2 },
1627     { ISD::TRUNCATE,    MVT::v64i1,  MVT::v64i8,  2 },
1628   };
1629 
1630   static const TypeConversionCostTblEntry AVX512DQConversionTbl[] = {
1631     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i64,  1 },
1632     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i64,  1 },
1633 
1634     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i64,  1 },
1635     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i64,  1 },
1636 
1637     { ISD::FP_TO_SINT,  MVT::v8i64,  MVT::v8f32,  1 },
1638     { ISD::FP_TO_SINT,  MVT::v8i64,  MVT::v8f64,  1 },
1639 
1640     { ISD::FP_TO_UINT,  MVT::v8i64,  MVT::v8f32,  1 },
1641     { ISD::FP_TO_UINT,  MVT::v8i64,  MVT::v8f64,  1 },
1642   };
1643 
1644   // TODO: For AVX512DQ + AVX512VL, we also have cheap casts for 128-bit and
1645   // 256-bit wide vectors.
1646 
1647   static const TypeConversionCostTblEntry AVX512FConversionTbl[] = {
1648     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v8f32,  1 },
1649     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v16f32, 3 },
1650     { ISD::FP_ROUND,  MVT::v8f32,   MVT::v8f64,  1 },
1651 
1652     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i8,   3 }, // sext+vpslld+vptestmd
1653     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i8,   3 }, // sext+vpslld+vptestmd
1654     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i8,   3 }, // sext+vpslld+vptestmd
1655     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i8,  3 }, // sext+vpslld+vptestmd
1656     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i16,  3 }, // sext+vpsllq+vptestmq
1657     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i16,  3 }, // sext+vpsllq+vptestmq
1658     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i16,  3 }, // sext+vpsllq+vptestmq
1659     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i16, 3 }, // sext+vpslld+vptestmd
1660     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i32,  2 }, // zmm vpslld+vptestmd
1661     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i32,  2 }, // zmm vpslld+vptestmd
1662     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i32,  2 }, // zmm vpslld+vptestmd
1663     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i32, 2 }, // vpslld+vptestmd
1664     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i64,  2 }, // zmm vpsllq+vptestmq
1665     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i64,  2 }, // zmm vpsllq+vptestmq
1666     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i64,  2 }, // vpsllq+vptestmq
1667     { ISD::TRUNCATE,  MVT::v2i8,    MVT::v2i32,  2 }, // vpmovdb
1668     { ISD::TRUNCATE,  MVT::v4i8,    MVT::v4i32,  2 }, // vpmovdb
1669     { ISD::TRUNCATE,  MVT::v16i8,   MVT::v16i32, 2 }, // vpmovdb
1670     { ISD::TRUNCATE,  MVT::v16i16,  MVT::v16i32, 2 }, // vpmovdb
1671     { ISD::TRUNCATE,  MVT::v2i8,    MVT::v2i64,  2 }, // vpmovqb
1672     { ISD::TRUNCATE,  MVT::v2i16,   MVT::v2i64,  1 }, // vpshufb
1673     { ISD::TRUNCATE,  MVT::v8i8,    MVT::v8i64,  2 }, // vpmovqb
1674     { ISD::TRUNCATE,  MVT::v8i16,   MVT::v8i64,  2 }, // vpmovqw
1675     { ISD::TRUNCATE,  MVT::v8i32,   MVT::v8i64,  1 }, // vpmovqd
1676     { ISD::TRUNCATE,  MVT::v4i32,   MVT::v4i64,  1 }, // zmm vpmovqd
1677     { ISD::TRUNCATE,  MVT::v16i8,   MVT::v16i64, 5 },// 2*vpmovqd+concat+vpmovdb
1678 
1679     { ISD::TRUNCATE,  MVT::v16i8,  MVT::v16i16,  3 }, // extend to v16i32
1680     { ISD::TRUNCATE,  MVT::v32i8,  MVT::v32i16,  8 },
1681 
1682     // Sign extend is zmm vpternlogd+vptruncdb.
1683     // Zero extend is zmm broadcast load+vptruncdw.
1684     { ISD::SIGN_EXTEND, MVT::v2i8,   MVT::v2i1,   3 },
1685     { ISD::ZERO_EXTEND, MVT::v2i8,   MVT::v2i1,   4 },
1686     { ISD::SIGN_EXTEND, MVT::v4i8,   MVT::v4i1,   3 },
1687     { ISD::ZERO_EXTEND, MVT::v4i8,   MVT::v4i1,   4 },
1688     { ISD::SIGN_EXTEND, MVT::v8i8,   MVT::v8i1,   3 },
1689     { ISD::ZERO_EXTEND, MVT::v8i8,   MVT::v8i1,   4 },
1690     { ISD::SIGN_EXTEND, MVT::v16i8,  MVT::v16i1,  3 },
1691     { ISD::ZERO_EXTEND, MVT::v16i8,  MVT::v16i1,  4 },
1692 
1693     // Sign extend is zmm vpternlogd+vptruncdw.
1694     // Zero extend is zmm vpternlogd+vptruncdw+vpsrlw.
1695     { ISD::SIGN_EXTEND, MVT::v2i16,  MVT::v2i1,   3 },
1696     { ISD::ZERO_EXTEND, MVT::v2i16,  MVT::v2i1,   4 },
1697     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i1,   3 },
1698     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i1,   4 },
1699     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i1,   3 },
1700     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i1,   4 },
1701     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1,  3 },
1702     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1,  4 },
1703 
1704     { ISD::SIGN_EXTEND, MVT::v2i32,  MVT::v2i1,   1 }, // zmm vpternlogd
1705     { ISD::ZERO_EXTEND, MVT::v2i32,  MVT::v2i1,   2 }, // zmm vpternlogd+psrld
1706     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i1,   1 }, // zmm vpternlogd
1707     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i1,   2 }, // zmm vpternlogd+psrld
1708     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   1 }, // zmm vpternlogd
1709     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   2 }, // zmm vpternlogd+psrld
1710     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v2i1,   1 }, // zmm vpternlogq
1711     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v2i1,   2 }, // zmm vpternlogq+psrlq
1712     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   1 }, // zmm vpternlogq
1713     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   2 }, // zmm vpternlogq+psrlq
1714 
1715     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i1,  1 }, // vpternlogd
1716     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i1,  2 }, // vpternlogd+psrld
1717     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i1,   1 }, // vpternlogq
1718     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i1,   2 }, // vpternlogq+psrlq
1719 
1720     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
1721     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
1722     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
1723     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
1724     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i8,   1 },
1725     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i8,   1 },
1726     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i16,  1 },
1727     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i16,  1 },
1728     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i32,  1 },
1729     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i32,  1 },
1730 
1731     { ISD::SIGN_EXTEND, MVT::v32i16, MVT::v32i8,  3 }, // FIXME: May not be right
1732     { ISD::ZERO_EXTEND, MVT::v32i16, MVT::v32i8,  3 }, // FIXME: May not be right
1733 
1734     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i1,   4 },
1735     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i1,  3 },
1736     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v16i8,  2 },
1737     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i8,  1 },
1738     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i16,  2 },
1739     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 1 },
1740     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  1 },
1741     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 1 },
1742 
1743     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i1,   4 },
1744     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i1,  3 },
1745     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v16i8,  2 },
1746     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i8,  1 },
1747     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i16,  2 },
1748     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i16, 1 },
1749     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  1 },
1750     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i32, 1 },
1751     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i64, 26 },
1752     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i64,  5 },
1753 
1754     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v16f32, 2 },
1755     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v16f64, 7 },
1756     { ISD::FP_TO_SINT,  MVT::v32i8,  MVT::v32f64,15 },
1757     { ISD::FP_TO_SINT,  MVT::v64i8,  MVT::v64f32,11 },
1758     { ISD::FP_TO_SINT,  MVT::v64i8,  MVT::v64f64,31 },
1759     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v8f64,  3 },
1760     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v16f64, 7 },
1761     { ISD::FP_TO_SINT,  MVT::v32i16, MVT::v32f32, 5 },
1762     { ISD::FP_TO_SINT,  MVT::v32i16, MVT::v32f64,15 },
1763     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f64,  1 },
1764     { ISD::FP_TO_SINT,  MVT::v16i32, MVT::v16f64, 3 },
1765 
1766     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f64,  1 },
1767     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v8f64,  3 },
1768     { ISD::FP_TO_UINT,  MVT::v8i8,   MVT::v8f64,  3 },
1769     { ISD::FP_TO_UINT,  MVT::v16i32, MVT::v16f32, 1 },
1770     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v16f32, 3 },
1771     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v16f32, 3 },
1772   };
1773 
1774   static const TypeConversionCostTblEntry AVX512BWVLConversionTbl[] {
1775     // Mask sign extend has an instruction.
1776     { ISD::SIGN_EXTEND, MVT::v2i8,   MVT::v2i1,  1 },
1777     { ISD::SIGN_EXTEND, MVT::v2i16,  MVT::v2i1,  1 },
1778     { ISD::SIGN_EXTEND, MVT::v4i8,   MVT::v4i1,  1 },
1779     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i1,  1 },
1780     { ISD::SIGN_EXTEND, MVT::v8i8,   MVT::v8i1,  1 },
1781     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i1,  1 },
1782     { ISD::SIGN_EXTEND, MVT::v16i8,  MVT::v16i1, 1 },
1783     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1, 1 },
1784     { ISD::SIGN_EXTEND, MVT::v32i8,  MVT::v32i1, 1 },
1785 
1786     // Mask zero extend is a sext + shift.
1787     { ISD::ZERO_EXTEND, MVT::v2i8,   MVT::v2i1,  2 },
1788     { ISD::ZERO_EXTEND, MVT::v2i16,  MVT::v2i1,  2 },
1789     { ISD::ZERO_EXTEND, MVT::v4i8,   MVT::v4i1,  2 },
1790     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i1,  2 },
1791     { ISD::ZERO_EXTEND, MVT::v8i8,   MVT::v8i1,  2 },
1792     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i1,  2 },
1793     { ISD::ZERO_EXTEND, MVT::v16i8,  MVT::v16i1, 2 },
1794     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1, 2 },
1795     { ISD::ZERO_EXTEND, MVT::v32i8,  MVT::v32i1, 2 },
1796 
1797     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 2 },
1798     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   2 }, // vpsllw+vptestmb
1799     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  2 }, // vpsllw+vptestmw
1800     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   2 }, // vpsllw+vptestmb
1801     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i16,  2 }, // vpsllw+vptestmw
1802     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i8,   2 }, // vpsllw+vptestmb
1803     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i16,  2 }, // vpsllw+vptestmw
1804     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i8,  2 }, // vpsllw+vptestmb
1805     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i16, 2 }, // vpsllw+vptestmw
1806     { ISD::TRUNCATE,    MVT::v32i1,  MVT::v32i8,  2 }, // vpsllw+vptestmb
1807   };
1808 
1809   static const TypeConversionCostTblEntry AVX512DQVLConversionTbl[] = {
1810     { ISD::SINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  1 },
1811     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  1 },
1812     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i64,  1 },
1813     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i64,  1 },
1814 
1815     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  1 },
1816     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  1 },
1817     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i64,  1 },
1818     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64,  1 },
1819 
1820     { ISD::FP_TO_SINT,  MVT::v2i64,  MVT::v4f32,  1 },
1821     { ISD::FP_TO_SINT,  MVT::v4i64,  MVT::v4f32,  1 },
1822     { ISD::FP_TO_SINT,  MVT::v2i64,  MVT::v2f64,  1 },
1823     { ISD::FP_TO_SINT,  MVT::v4i64,  MVT::v4f64,  1 },
1824 
1825     { ISD::FP_TO_UINT,  MVT::v2i64,  MVT::v4f32,  1 },
1826     { ISD::FP_TO_UINT,  MVT::v4i64,  MVT::v4f32,  1 },
1827     { ISD::FP_TO_UINT,  MVT::v2i64,  MVT::v2f64,  1 },
1828     { ISD::FP_TO_UINT,  MVT::v4i64,  MVT::v4f64,  1 },
1829   };
1830 
1831   static const TypeConversionCostTblEntry AVX512VLConversionTbl[] = {
1832     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i8,   3 }, // sext+vpslld+vptestmd
1833     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i8,   3 }, // sext+vpslld+vptestmd
1834     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i8,   3 }, // sext+vpslld+vptestmd
1835     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i8,  8 }, // split+2*v8i8
1836     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i16,  3 }, // sext+vpsllq+vptestmq
1837     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i16,  3 }, // sext+vpsllq+vptestmq
1838     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i16,  3 }, // sext+vpsllq+vptestmq
1839     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i16, 8 }, // split+2*v8i16
1840     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i32,  2 }, // vpslld+vptestmd
1841     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i32,  2 }, // vpslld+vptestmd
1842     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i32,  2 }, // vpslld+vptestmd
1843     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i64,  2 }, // vpsllq+vptestmq
1844     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i64,  2 }, // vpsllq+vptestmq
1845     { ISD::TRUNCATE,  MVT::v4i32,   MVT::v4i64,  1 }, // vpmovqd
1846     { ISD::TRUNCATE,  MVT::v4i8,    MVT::v4i64,  2 }, // vpmovqb
1847     { ISD::TRUNCATE,  MVT::v4i16,   MVT::v4i64,  2 }, // vpmovqw
1848     { ISD::TRUNCATE,  MVT::v8i8,    MVT::v8i32,  2 }, // vpmovwb
1849 
1850     // sign extend is vpcmpeq+maskedmove+vpmovdw+vpacksswb
1851     // zero extend is vpcmpeq+maskedmove+vpmovdw+vpsrlw+vpackuswb
1852     { ISD::SIGN_EXTEND, MVT::v2i8,   MVT::v2i1,   5 },
1853     { ISD::ZERO_EXTEND, MVT::v2i8,   MVT::v2i1,   6 },
1854     { ISD::SIGN_EXTEND, MVT::v4i8,   MVT::v4i1,   5 },
1855     { ISD::ZERO_EXTEND, MVT::v4i8,   MVT::v4i1,   6 },
1856     { ISD::SIGN_EXTEND, MVT::v8i8,   MVT::v8i1,   5 },
1857     { ISD::ZERO_EXTEND, MVT::v8i8,   MVT::v8i1,   6 },
1858     { ISD::SIGN_EXTEND, MVT::v16i8,  MVT::v16i1, 10 },
1859     { ISD::ZERO_EXTEND, MVT::v16i8,  MVT::v16i1, 12 },
1860 
1861     // sign extend is vpcmpeq+maskedmove+vpmovdw
1862     // zero extend is vpcmpeq+maskedmove+vpmovdw+vpsrlw
1863     { ISD::SIGN_EXTEND, MVT::v2i16,  MVT::v2i1,   4 },
1864     { ISD::ZERO_EXTEND, MVT::v2i16,  MVT::v2i1,   5 },
1865     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i1,   4 },
1866     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i1,   5 },
1867     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i1,   4 },
1868     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i1,   5 },
1869     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1, 10 },
1870     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1, 12 },
1871 
1872     { ISD::SIGN_EXTEND, MVT::v2i32,  MVT::v2i1,   1 }, // vpternlogd
1873     { ISD::ZERO_EXTEND, MVT::v2i32,  MVT::v2i1,   2 }, // vpternlogd+psrld
1874     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i1,   1 }, // vpternlogd
1875     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i1,   2 }, // vpternlogd+psrld
1876     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   1 }, // vpternlogd
1877     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   2 }, // vpternlogd+psrld
1878     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v2i1,   1 }, // vpternlogq
1879     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v2i1,   2 }, // vpternlogq+psrlq
1880     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   1 }, // vpternlogq
1881     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   2 }, // vpternlogq+psrlq
1882 
1883     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v16i8,  1 },
1884     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v16i8,  1 },
1885     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v16i8,  1 },
1886     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v16i8,  1 },
1887     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
1888     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
1889     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v8i16,  1 },
1890     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v8i16,  1 },
1891     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
1892     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
1893     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
1894     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
1895 
1896     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  1 },
1897     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  1 },
1898     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  1 },
1899     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  1 },
1900 
1901     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i64,    1 },
1902     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i64,    1 },
1903     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  1 },
1904     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  1 },
1905     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  1 },
1906     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  1 },
1907     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  1 },
1908     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  1 },
1909     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  1 },
1910     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  1 },
1911     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  5 },
1912     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  5 },
1913     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64,  5 },
1914 
1915     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v8f32,  2 },
1916     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v16f32, 2 },
1917     { ISD::FP_TO_SINT,  MVT::v32i8,  MVT::v32f32, 5 },
1918 
1919     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    1 },
1920     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,    1 },
1921     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  1 },
1922     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  1 },
1923     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f64,  1 },
1924     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f32,  1 },
1925     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f64,  1 },
1926   };
1927 
1928   static const TypeConversionCostTblEntry AVX2ConversionTbl[] = {
1929     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
1930     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
1931     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
1932     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
1933     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1,  1 },
1934     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1,  1 },
1935 
1936     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v16i8,  2 },
1937     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v16i8,  2 },
1938     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v16i8,  2 },
1939     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v16i8,  2 },
1940     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
1941     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
1942     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v8i16,  2 },
1943     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v8i16,  2 },
1944     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
1945     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
1946     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 3 },
1947     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 3 },
1948     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  2 },
1949     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  2 },
1950 
1951     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i32,  2 },
1952 
1953     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32, 4 },
1954     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i32, 4 },
1955     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v8i16,  1 },
1956     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i32,  1 },
1957     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v2i64,  1 },
1958     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v8i32,  4 },
1959     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i64,  4 },
1960     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i32,  1 },
1961     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v2i64,  1 },
1962     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i64,  5 },
1963     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v4i64,  1 },
1964     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  2 },
1965 
1966     { ISD::FP_EXTEND,   MVT::v8f64,  MVT::v8f32,  3 },
1967     { ISD::FP_ROUND,    MVT::v8f32,  MVT::v8f64,  3 },
1968 
1969     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v8f32,  1 },
1970     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v4f64,  1 },
1971     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f32,  1 },
1972     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f64,  3 },
1973 
1974     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    3 },
1975     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,    3 },
1976     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v8f32,  1 },
1977     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  3 },
1978     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  4 },
1979     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f64,  4 },
1980     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f32,  3 },
1981     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v4f64,  4 },
1982 
1983     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  2 },
1984     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  2 },
1985     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  2 },
1986     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  2 },
1987     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  1 },
1988     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  1 },
1989     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  3 },
1990 
1991     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  2 },
1992     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  2 },
1993     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  2 },
1994     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  2 },
1995     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  2 },
1996     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i32,  1 },
1997     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  2 },
1998     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  2 },
1999     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  2 },
2000     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  4 },
2001   };
2002 
2003   static const TypeConversionCostTblEntry AVXConversionTbl[] = {
2004     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   6 },
2005     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   4 },
2006     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   7 },
2007     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   4 },
2008     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1,  4 },
2009     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1,  4 },
2010 
2011     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v16i8,  3 },
2012     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v16i8,  3 },
2013     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v16i8,  3 },
2014     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v16i8,  3 },
2015     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  3 },
2016     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  3 },
2017     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v8i16,  3 },
2018     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v8i16,  3 },
2019     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  3 },
2020     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  3 },
2021     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  3 },
2022     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  3 },
2023 
2024     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i64,  4 },
2025     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i32,  5 },
2026     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i16, 4 },
2027     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i64,  9 },
2028     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i64, 11 },
2029 
2030     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32, 6 },
2031     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i32, 6 },
2032     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 2 }, // and+extract+packuswb
2033     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v8i32,  5 },
2034     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  5 },
2035     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i64,  5 },
2036     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i64,  3 }, // and+extract+2*packusdw
2037     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v4i64,  2 },
2038 
2039     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i1,   3 },
2040     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i1,   3 },
2041     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i1,   8 },
2042     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  4 },
2043     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v16i8,  2 },
2044     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  4 },
2045     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v8i16,  2 },
2046     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  2 },
2047     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  2 },
2048     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  4 },
2049     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v2i64,  5 },
2050     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i64,  8 },
2051 
2052     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i1,   7 },
2053     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i1,   7 },
2054     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i1,   6 },
2055     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  4 },
2056     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v16i8,  2 },
2057     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  4 },
2058     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v8i16,  2 },
2059     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  4 },
2060     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i32,  4 },
2061     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  5 },
2062     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  6 },
2063     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  8 },
2064     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i32, 10 },
2065     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64, 10 },
2066     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i64, 18 },
2067     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  5 },
2068     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64, 10 },
2069 
2070     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v8f32,  2 },
2071     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v4f64,  2 },
2072     { ISD::FP_TO_SINT,  MVT::v32i8,  MVT::v8f32,  2 },
2073     { ISD::FP_TO_SINT,  MVT::v32i8,  MVT::v4f64,  2 },
2074     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v8f32,  2 },
2075     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v4f64,  2 },
2076     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v8f32,  2 },
2077     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v4f64,  2 },
2078     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v4f64,  2 },
2079     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f32,  2 },
2080     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f64,  5 },
2081 
2082     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v8f32,  2 },
2083     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v4f64,  2 },
2084     { ISD::FP_TO_UINT,  MVT::v32i8,  MVT::v8f32,  2 },
2085     { ISD::FP_TO_UINT,  MVT::v32i8,  MVT::v4f64,  2 },
2086     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v8f32,  2 },
2087     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v4f64,  2 },
2088     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v8f32,  2 },
2089     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v4f64,  2 },
2090     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  3 },
2091     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  4 },
2092     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f64,  6 },
2093     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f32,  7 },
2094     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v4f64,  7 },
2095 
2096     { ISD::FP_EXTEND,   MVT::v4f64,  MVT::v4f32,  1 },
2097     { ISD::FP_ROUND,    MVT::v4f32,  MVT::v4f64,  1 },
2098   };
2099 
2100   static const TypeConversionCostTblEntry SSE41ConversionTbl[] = {
2101     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v16i8,   1 },
2102     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v16i8,   1 },
2103     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v16i8,   1 },
2104     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v16i8,   1 },
2105     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v16i8,   1 },
2106     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v16i8,   1 },
2107     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v8i16,   1 },
2108     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v8i16,   1 },
2109     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v8i16,   1 },
2110     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v8i16,   1 },
2111     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v4i32,   1 },
2112     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v4i32,   1 },
2113 
2114     // These truncates end up widening elements.
2115     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   1 }, // PMOVXZBQ
2116     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  1 }, // PMOVXZWQ
2117     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   1 }, // PMOVXZBD
2118 
2119     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i32,  2 },
2120     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i32,  2 },
2121     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v2i64,  2 },
2122 
2123     { ISD::SINT_TO_FP,  MVT::f32,    MVT::i32,    1 },
2124     { ISD::SINT_TO_FP,  MVT::f64,    MVT::i32,    1 },
2125     { ISD::SINT_TO_FP,  MVT::f32,    MVT::i64,    1 },
2126     { ISD::SINT_TO_FP,  MVT::f64,    MVT::i64,    1 },
2127     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v16i8,  1 },
2128     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  1 },
2129     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v8i16,  1 },
2130     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  1 },
2131     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  1 },
2132     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v4i32,  1 },
2133     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  2 },
2134 
2135     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i32,    1 },
2136     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i32,    1 },
2137     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i64,    4 },
2138     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i64,    4 },
2139     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v16i8,  1 },
2140     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  1 },
2141     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v8i16,  1 },
2142     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  1 },
2143     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  3 },
2144     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  3 },
2145     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v4i32,  2 },
2146     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v2i64, 12 },
2147     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i64, 22 },
2148     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  4 },
2149 
2150     { ISD::FP_TO_SINT,  MVT::i32,    MVT::f32,    1 },
2151     { ISD::FP_TO_SINT,  MVT::i64,    MVT::f32,    1 },
2152     { ISD::FP_TO_SINT,  MVT::i32,    MVT::f64,    1 },
2153     { ISD::FP_TO_SINT,  MVT::i64,    MVT::f64,    1 },
2154     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v4f32,  2 },
2155     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v2f64,  2 },
2156     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v4f32,  1 },
2157     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v2f64,  1 },
2158     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v4f32,  1 },
2159     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v2f64,  1 },
2160 
2161     { ISD::FP_TO_UINT,  MVT::i32,    MVT::f32,    1 },
2162     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    4 },
2163     { ISD::FP_TO_UINT,  MVT::i32,    MVT::f64,    1 },
2164     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,    4 },
2165     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v4f32,  2 },
2166     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v2f64,  2 },
2167     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v4f32,  1 },
2168     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v2f64,  1 },
2169     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  4 },
2170     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  4 },
2171   };
2172 
2173   static const TypeConversionCostTblEntry SSE2ConversionTbl[] = {
2174     // These are somewhat magic numbers justified by comparing the
2175     // output of llvm-mca for our various supported scheduler models
2176     // and basing it off the worst case scenario.
2177     { ISD::SINT_TO_FP,  MVT::f32,    MVT::i32,    3 },
2178     { ISD::SINT_TO_FP,  MVT::f64,    MVT::i32,    3 },
2179     { ISD::SINT_TO_FP,  MVT::f32,    MVT::i64,    3 },
2180     { ISD::SINT_TO_FP,  MVT::f64,    MVT::i64,    3 },
2181     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v16i8,  3 },
2182     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  4 },
2183     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v8i16,  3 },
2184     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  4 },
2185     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  3 },
2186     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v4i32,  4 },
2187     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v2i64,  8 },
2188     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  8 },
2189 
2190     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i32,    3 },
2191     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i32,    3 },
2192     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i64,    8 },
2193     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i64,    9 },
2194     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  4 },
2195     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v16i8,  4 },
2196     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v8i16,  4 },
2197     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  4 },
2198     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  7 },
2199     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v4i32,  7 },
2200     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  5 },
2201     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64, 15 },
2202     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v2i64, 18 },
2203 
2204     { ISD::FP_TO_SINT,  MVT::i32,    MVT::f32,    4 },
2205     { ISD::FP_TO_SINT,  MVT::i64,    MVT::f32,    4 },
2206     { ISD::FP_TO_SINT,  MVT::i32,    MVT::f64,    4 },
2207     { ISD::FP_TO_SINT,  MVT::i64,    MVT::f64,    4 },
2208     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v4f32,  6 },
2209     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v2f64,  6 },
2210     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v4f32,  5 },
2211     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v2f64,  5 },
2212     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v4f32,  4 },
2213     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v2f64,  4 },
2214 
2215     { ISD::FP_TO_UINT,  MVT::i32,    MVT::f32,    4 },
2216     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    4 },
2217     { ISD::FP_TO_UINT,  MVT::i32,    MVT::f64,    4 },
2218     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,   15 },
2219     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v4f32,  6 },
2220     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v2f64,  6 },
2221     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v4f32,  5 },
2222     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v2f64,  5 },
2223     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  8 },
2224     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  8 },
2225 
2226     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v16i8,  4 },
2227     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v16i8,  4 },
2228     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v16i8,  2 },
2229     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v16i8,  3 },
2230     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v16i8,  1 },
2231     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v16i8,  2 },
2232     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v8i16,  2 },
2233     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v8i16,  3 },
2234     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v8i16,  1 },
2235     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v8i16,  2 },
2236     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v4i32,  1 },
2237     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v4i32,  2 },
2238 
2239     // These truncates are really widening elements.
2240     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i32,  1 }, // PSHUFD
2241     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  2 }, // PUNPCKLWD+DQ
2242     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   3 }, // PUNPCKLBW+WD+PSHUFD
2243     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i16,  1 }, // PUNPCKLWD
2244     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   2 }, // PUNPCKLBW+WD
2245     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i8,   1 }, // PUNPCKLBW
2246 
2247     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v8i16,  2 }, // PAND+PACKUSWB
2248     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 3 },
2249     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i32,  3 }, // PAND+2*PACKUSWB
2250     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i32, 7 },
2251     { ISD::TRUNCATE,    MVT::v2i16,  MVT::v2i32,  1 },
2252     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i32,  3 },
2253     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  5 },
2254     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32,10 },
2255     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v2i64,  4 }, // PAND+3*PACKUSWB
2256     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v2i64,  2 }, // PSHUFD+PSHUFLW
2257     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v2i64,  1 }, // PSHUFD
2258   };
2259 
2260   // Attempt to map directly to (simple) MVT types to let us match custom entries.
2261   EVT SrcTy = TLI->getValueType(DL, Src);
2262   EVT DstTy = TLI->getValueType(DL, Dst);
2263 
2264   // The function getSimpleVT only handles simple value types.
2265   if (SrcTy.isSimple() && DstTy.isSimple()) {
2266     MVT SimpleSrcTy = SrcTy.getSimpleVT();
2267     MVT SimpleDstTy = DstTy.getSimpleVT();
2268 
2269     if (ST->useAVX512Regs()) {
2270       if (ST->hasBWI())
2271         if (const auto *Entry = ConvertCostTableLookup(
2272                 AVX512BWConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2273           return AdjustCost(Entry->Cost);
2274 
2275       if (ST->hasDQI())
2276         if (const auto *Entry = ConvertCostTableLookup(
2277                 AVX512DQConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2278           return AdjustCost(Entry->Cost);
2279 
2280       if (ST->hasAVX512())
2281         if (const auto *Entry = ConvertCostTableLookup(
2282                 AVX512FConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2283           return AdjustCost(Entry->Cost);
2284     }
2285 
2286     if (ST->hasBWI())
2287       if (const auto *Entry = ConvertCostTableLookup(
2288               AVX512BWVLConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2289         return AdjustCost(Entry->Cost);
2290 
2291     if (ST->hasDQI())
2292       if (const auto *Entry = ConvertCostTableLookup(
2293               AVX512DQVLConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2294         return AdjustCost(Entry->Cost);
2295 
2296     if (ST->hasAVX512())
2297       if (const auto *Entry = ConvertCostTableLookup(AVX512VLConversionTbl, ISD,
2298                                                      SimpleDstTy, SimpleSrcTy))
2299         return AdjustCost(Entry->Cost);
2300 
2301     if (ST->hasAVX2()) {
2302       if (const auto *Entry = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
2303                                                      SimpleDstTy, SimpleSrcTy))
2304         return AdjustCost(Entry->Cost);
2305     }
2306 
2307     if (ST->hasAVX()) {
2308       if (const auto *Entry = ConvertCostTableLookup(AVXConversionTbl, ISD,
2309                                                      SimpleDstTy, SimpleSrcTy))
2310         return AdjustCost(Entry->Cost);
2311     }
2312 
2313     if (ST->hasSSE41()) {
2314       if (const auto *Entry = ConvertCostTableLookup(SSE41ConversionTbl, ISD,
2315                                                      SimpleDstTy, SimpleSrcTy))
2316         return AdjustCost(Entry->Cost);
2317     }
2318 
2319     if (ST->hasSSE2()) {
2320       if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
2321                                                      SimpleDstTy, SimpleSrcTy))
2322         return AdjustCost(Entry->Cost);
2323     }
2324   }
2325 
2326   // Fall back to legalized types.
2327   std::pair<InstructionCost, MVT> LTSrc = TLI->getTypeLegalizationCost(DL, Src);
2328   std::pair<InstructionCost, MVT> LTDest =
2329       TLI->getTypeLegalizationCost(DL, Dst);
2330 
2331   if (ST->useAVX512Regs()) {
2332     if (ST->hasBWI())
2333       if (const auto *Entry = ConvertCostTableLookup(
2334               AVX512BWConversionTbl, ISD, LTDest.second, LTSrc.second))
2335         return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2336 
2337     if (ST->hasDQI())
2338       if (const auto *Entry = ConvertCostTableLookup(
2339               AVX512DQConversionTbl, ISD, LTDest.second, LTSrc.second))
2340         return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2341 
2342     if (ST->hasAVX512())
2343       if (const auto *Entry = ConvertCostTableLookup(
2344               AVX512FConversionTbl, ISD, LTDest.second, LTSrc.second))
2345         return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2346   }
2347 
2348   if (ST->hasBWI())
2349     if (const auto *Entry = ConvertCostTableLookup(AVX512BWVLConversionTbl, ISD,
2350                                                    LTDest.second, LTSrc.second))
2351       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2352 
2353   if (ST->hasDQI())
2354     if (const auto *Entry = ConvertCostTableLookup(AVX512DQVLConversionTbl, ISD,
2355                                                    LTDest.second, LTSrc.second))
2356       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2357 
2358   if (ST->hasAVX512())
2359     if (const auto *Entry = ConvertCostTableLookup(AVX512VLConversionTbl, ISD,
2360                                                    LTDest.second, LTSrc.second))
2361       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2362 
2363   if (ST->hasAVX2())
2364     if (const auto *Entry = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
2365                                                    LTDest.second, LTSrc.second))
2366       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2367 
2368   if (ST->hasAVX())
2369     if (const auto *Entry = ConvertCostTableLookup(AVXConversionTbl, ISD,
2370                                                    LTDest.second, LTSrc.second))
2371       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2372 
2373   if (ST->hasSSE41())
2374     if (const auto *Entry = ConvertCostTableLookup(SSE41ConversionTbl, ISD,
2375                                                    LTDest.second, LTSrc.second))
2376       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2377 
2378   if (ST->hasSSE2())
2379     if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
2380                                                    LTDest.second, LTSrc.second))
2381       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2382 
2383   // Fallback, for i8/i16 sitofp/uitofp cases we need to extend to i32 for
2384   // sitofp.
2385   if ((ISD == ISD::SINT_TO_FP || ISD == ISD::UINT_TO_FP) &&
2386       1 < Src->getScalarSizeInBits() && Src->getScalarSizeInBits() < 32) {
2387     Type *ExtSrc = Src->getWithNewBitWidth(32);
2388     unsigned ExtOpc =
2389         (ISD == ISD::SINT_TO_FP) ? Instruction::SExt : Instruction::ZExt;
2390 
2391     // For scalar loads the extend would be free.
2392     InstructionCost ExtCost = 0;
2393     if (!(Src->isIntegerTy() && I && isa<LoadInst>(I->getOperand(0))))
2394       ExtCost = getCastInstrCost(ExtOpc, ExtSrc, Src, CCH, CostKind);
2395 
2396     return ExtCost + getCastInstrCost(Instruction::SIToFP, Dst, ExtSrc,
2397                                       TTI::CastContextHint::None, CostKind);
2398   }
2399 
2400   // Fallback for fptosi/fptoui i8/i16 cases we need to truncate from fptosi
2401   // i32.
2402   if ((ISD == ISD::FP_TO_SINT || ISD == ISD::FP_TO_UINT) &&
2403       1 < Dst->getScalarSizeInBits() && Dst->getScalarSizeInBits() < 32) {
2404     Type *TruncDst = Dst->getWithNewBitWidth(32);
2405     return getCastInstrCost(Instruction::FPToSI, TruncDst, Src, CCH, CostKind) +
2406            getCastInstrCost(Instruction::Trunc, Dst, TruncDst,
2407                             TTI::CastContextHint::None, CostKind);
2408   }
2409 
2410   return AdjustCost(
2411       BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
2412 }
2413 
2414 InstructionCost X86TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
2415                                                Type *CondTy,
2416                                                CmpInst::Predicate VecPred,
2417                                                TTI::TargetCostKind CostKind,
2418                                                const Instruction *I) {
2419   // TODO: Handle other cost kinds.
2420   if (CostKind != TTI::TCK_RecipThroughput)
2421     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
2422                                      I);
2423 
2424   // Legalize the type.
2425   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
2426 
2427   MVT MTy = LT.second;
2428 
2429   int ISD = TLI->InstructionOpcodeToISD(Opcode);
2430   assert(ISD && "Invalid opcode");
2431 
2432   unsigned ExtraCost = 0;
2433   if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) {
2434     // Some vector comparison predicates cost extra instructions.
2435     // TODO: Should we invert this and assume worst case cmp costs
2436     // and reduce for particular predicates?
2437     if (MTy.isVector() &&
2438         !((ST->hasXOP() && (!ST->hasAVX2() || MTy.is128BitVector())) ||
2439           (ST->hasAVX512() && 32 <= MTy.getScalarSizeInBits()) ||
2440           ST->hasBWI())) {
2441       // Fallback to I if a specific predicate wasn't specified.
2442       CmpInst::Predicate Pred = VecPred;
2443       if (I && (Pred == CmpInst::BAD_ICMP_PREDICATE ||
2444                 Pred == CmpInst::BAD_FCMP_PREDICATE))
2445         Pred = cast<CmpInst>(I)->getPredicate();
2446 
2447       switch (Pred) {
2448       case CmpInst::Predicate::ICMP_NE:
2449         // xor(cmpeq(x,y),-1)
2450         ExtraCost = 1;
2451         break;
2452       case CmpInst::Predicate::ICMP_SGE:
2453       case CmpInst::Predicate::ICMP_SLE:
2454         // xor(cmpgt(x,y),-1)
2455         ExtraCost = 1;
2456         break;
2457       case CmpInst::Predicate::ICMP_ULT:
2458       case CmpInst::Predicate::ICMP_UGT:
2459         // cmpgt(xor(x,signbit),xor(y,signbit))
2460         // xor(cmpeq(pmaxu(x,y),x),-1)
2461         ExtraCost = 2;
2462         break;
2463       case CmpInst::Predicate::ICMP_ULE:
2464       case CmpInst::Predicate::ICMP_UGE:
2465         if ((ST->hasSSE41() && MTy.getScalarSizeInBits() == 32) ||
2466             (ST->hasSSE2() && MTy.getScalarSizeInBits() < 32)) {
2467           // cmpeq(psubus(x,y),0)
2468           // cmpeq(pminu(x,y),x)
2469           ExtraCost = 1;
2470         } else {
2471           // xor(cmpgt(xor(x,signbit),xor(y,signbit)),-1)
2472           ExtraCost = 3;
2473         }
2474         break;
2475       case CmpInst::Predicate::BAD_ICMP_PREDICATE:
2476       case CmpInst::Predicate::BAD_FCMP_PREDICATE:
2477         // Assume worst case scenario and add the maximum extra cost.
2478         ExtraCost = 3;
2479         break;
2480       default:
2481         break;
2482       }
2483     }
2484   }
2485 
2486   static const CostTblEntry SLMCostTbl[] = {
2487     // slm pcmpeq/pcmpgt throughput is 2
2488     { ISD::SETCC,   MVT::v2i64,   2 },
2489   };
2490 
2491   static const CostTblEntry AVX512BWCostTbl[] = {
2492     { ISD::SETCC,   MVT::v32i16,  1 },
2493     { ISD::SETCC,   MVT::v64i8,   1 },
2494 
2495     { ISD::SELECT,  MVT::v32i16,  1 },
2496     { ISD::SELECT,  MVT::v64i8,   1 },
2497   };
2498 
2499   static const CostTblEntry AVX512CostTbl[] = {
2500     { ISD::SETCC,   MVT::v8i64,   1 },
2501     { ISD::SETCC,   MVT::v16i32,  1 },
2502     { ISD::SETCC,   MVT::v8f64,   1 },
2503     { ISD::SETCC,   MVT::v16f32,  1 },
2504 
2505     { ISD::SELECT,  MVT::v8i64,   1 },
2506     { ISD::SELECT,  MVT::v16i32,  1 },
2507     { ISD::SELECT,  MVT::v8f64,   1 },
2508     { ISD::SELECT,  MVT::v16f32,  1 },
2509 
2510     { ISD::SETCC,   MVT::v32i16,  2 }, // FIXME: should probably be 4
2511     { ISD::SETCC,   MVT::v64i8,   2 }, // FIXME: should probably be 4
2512 
2513     { ISD::SELECT,  MVT::v32i16,  2 }, // FIXME: should be 3
2514     { ISD::SELECT,  MVT::v64i8,   2 }, // FIXME: should be 3
2515   };
2516 
2517   static const CostTblEntry AVX2CostTbl[] = {
2518     { ISD::SETCC,   MVT::v4i64,   1 },
2519     { ISD::SETCC,   MVT::v8i32,   1 },
2520     { ISD::SETCC,   MVT::v16i16,  1 },
2521     { ISD::SETCC,   MVT::v32i8,   1 },
2522 
2523     { ISD::SELECT,  MVT::v4i64,   1 }, // pblendvb
2524     { ISD::SELECT,  MVT::v8i32,   1 }, // pblendvb
2525     { ISD::SELECT,  MVT::v16i16,  1 }, // pblendvb
2526     { ISD::SELECT,  MVT::v32i8,   1 }, // pblendvb
2527   };
2528 
2529   static const CostTblEntry AVX1CostTbl[] = {
2530     { ISD::SETCC,   MVT::v4f64,   1 },
2531     { ISD::SETCC,   MVT::v8f32,   1 },
2532     // AVX1 does not support 8-wide integer compare.
2533     { ISD::SETCC,   MVT::v4i64,   4 },
2534     { ISD::SETCC,   MVT::v8i32,   4 },
2535     { ISD::SETCC,   MVT::v16i16,  4 },
2536     { ISD::SETCC,   MVT::v32i8,   4 },
2537 
2538     { ISD::SELECT,  MVT::v4f64,   1 }, // vblendvpd
2539     { ISD::SELECT,  MVT::v8f32,   1 }, // vblendvps
2540     { ISD::SELECT,  MVT::v4i64,   1 }, // vblendvpd
2541     { ISD::SELECT,  MVT::v8i32,   1 }, // vblendvps
2542     { ISD::SELECT,  MVT::v16i16,  3 }, // vandps + vandnps + vorps
2543     { ISD::SELECT,  MVT::v32i8,   3 }, // vandps + vandnps + vorps
2544   };
2545 
2546   static const CostTblEntry SSE42CostTbl[] = {
2547     { ISD::SETCC,   MVT::v2f64,   1 },
2548     { ISD::SETCC,   MVT::v4f32,   1 },
2549     { ISD::SETCC,   MVT::v2i64,   1 },
2550   };
2551 
2552   static const CostTblEntry SSE41CostTbl[] = {
2553     { ISD::SELECT,  MVT::v2f64,   1 }, // blendvpd
2554     { ISD::SELECT,  MVT::v4f32,   1 }, // blendvps
2555     { ISD::SELECT,  MVT::v2i64,   1 }, // pblendvb
2556     { ISD::SELECT,  MVT::v4i32,   1 }, // pblendvb
2557     { ISD::SELECT,  MVT::v8i16,   1 }, // pblendvb
2558     { ISD::SELECT,  MVT::v16i8,   1 }, // pblendvb
2559   };
2560 
2561   static const CostTblEntry SSE2CostTbl[] = {
2562     { ISD::SETCC,   MVT::v2f64,   2 },
2563     { ISD::SETCC,   MVT::f64,     1 },
2564     { ISD::SETCC,   MVT::v2i64,   8 },
2565     { ISD::SETCC,   MVT::v4i32,   1 },
2566     { ISD::SETCC,   MVT::v8i16,   1 },
2567     { ISD::SETCC,   MVT::v16i8,   1 },
2568 
2569     { ISD::SELECT,  MVT::v2f64,   3 }, // andpd + andnpd + orpd
2570     { ISD::SELECT,  MVT::v2i64,   3 }, // pand + pandn + por
2571     { ISD::SELECT,  MVT::v4i32,   3 }, // pand + pandn + por
2572     { ISD::SELECT,  MVT::v8i16,   3 }, // pand + pandn + por
2573     { ISD::SELECT,  MVT::v16i8,   3 }, // pand + pandn + por
2574   };
2575 
2576   static const CostTblEntry SSE1CostTbl[] = {
2577     { ISD::SETCC,   MVT::v4f32,   2 },
2578     { ISD::SETCC,   MVT::f32,     1 },
2579 
2580     { ISD::SELECT,  MVT::v4f32,   3 }, // andps + andnps + orps
2581   };
2582 
2583   if (ST->useSLMArithCosts())
2584     if (const auto *Entry = CostTableLookup(SLMCostTbl, ISD, MTy))
2585       return LT.first * (ExtraCost + Entry->Cost);
2586 
2587   if (ST->hasBWI())
2588     if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
2589       return LT.first * (ExtraCost + Entry->Cost);
2590 
2591   if (ST->hasAVX512())
2592     if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
2593       return LT.first * (ExtraCost + Entry->Cost);
2594 
2595   if (ST->hasAVX2())
2596     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
2597       return LT.first * (ExtraCost + Entry->Cost);
2598 
2599   if (ST->hasAVX())
2600     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
2601       return LT.first * (ExtraCost + Entry->Cost);
2602 
2603   if (ST->hasSSE42())
2604     if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
2605       return LT.first * (ExtraCost + Entry->Cost);
2606 
2607   if (ST->hasSSE41())
2608     if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
2609       return LT.first * (ExtraCost + Entry->Cost);
2610 
2611   if (ST->hasSSE2())
2612     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
2613       return LT.first * (ExtraCost + Entry->Cost);
2614 
2615   if (ST->hasSSE1())
2616     if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
2617       return LT.first * (ExtraCost + Entry->Cost);
2618 
2619   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
2620 }
2621 
2622 unsigned X86TTIImpl::getAtomicMemIntrinsicMaxElementSize() const { return 16; }
2623 
2624 InstructionCost
2625 X86TTIImpl::getTypeBasedIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
2626                                            TTI::TargetCostKind CostKind) {
2627 
2628   // Costs should match the codegen from:
2629   // BITREVERSE: llvm\test\CodeGen\X86\vector-bitreverse.ll
2630   // BSWAP: llvm\test\CodeGen\X86\bswap-vector.ll
2631   // CTLZ: llvm\test\CodeGen\X86\vector-lzcnt-*.ll
2632   // CTPOP: llvm\test\CodeGen\X86\vector-popcnt-*.ll
2633   // CTTZ: llvm\test\CodeGen\X86\vector-tzcnt-*.ll
2634 
2635   // TODO: Overflow intrinsics (*ADDO, *SUBO, *MULO) with vector types are not
2636   //       specialized in these tables yet.
2637   static const CostTblEntry AVX512BITALGCostTbl[] = {
2638     { ISD::CTPOP,      MVT::v32i16,  1 },
2639     { ISD::CTPOP,      MVT::v64i8,   1 },
2640     { ISD::CTPOP,      MVT::v16i16,  1 },
2641     { ISD::CTPOP,      MVT::v32i8,   1 },
2642     { ISD::CTPOP,      MVT::v8i16,   1 },
2643     { ISD::CTPOP,      MVT::v16i8,   1 },
2644   };
2645   static const CostTblEntry AVX512VPOPCNTDQCostTbl[] = {
2646     { ISD::CTPOP,      MVT::v8i64,   1 },
2647     { ISD::CTPOP,      MVT::v16i32,  1 },
2648     { ISD::CTPOP,      MVT::v4i64,   1 },
2649     { ISD::CTPOP,      MVT::v8i32,   1 },
2650     { ISD::CTPOP,      MVT::v2i64,   1 },
2651     { ISD::CTPOP,      MVT::v4i32,   1 },
2652   };
2653   static const CostTblEntry AVX512CDCostTbl[] = {
2654     { ISD::CTLZ,       MVT::v8i64,   1 },
2655     { ISD::CTLZ,       MVT::v16i32,  1 },
2656     { ISD::CTLZ,       MVT::v32i16,  8 },
2657     { ISD::CTLZ,       MVT::v64i8,  20 },
2658     { ISD::CTLZ,       MVT::v4i64,   1 },
2659     { ISD::CTLZ,       MVT::v8i32,   1 },
2660     { ISD::CTLZ,       MVT::v16i16,  4 },
2661     { ISD::CTLZ,       MVT::v32i8,  10 },
2662     { ISD::CTLZ,       MVT::v2i64,   1 },
2663     { ISD::CTLZ,       MVT::v4i32,   1 },
2664     { ISD::CTLZ,       MVT::v8i16,   4 },
2665     { ISD::CTLZ,       MVT::v16i8,   4 },
2666   };
2667   static const CostTblEntry AVX512BWCostTbl[] = {
2668     { ISD::ABS,        MVT::v32i16,  1 },
2669     { ISD::ABS,        MVT::v64i8,   1 },
2670     { ISD::BITREVERSE, MVT::v8i64,   3 },
2671     { ISD::BITREVERSE, MVT::v16i32,  3 },
2672     { ISD::BITREVERSE, MVT::v32i16,  3 },
2673     { ISD::BITREVERSE, MVT::v64i8,   2 },
2674     { ISD::BSWAP,      MVT::v8i64,   1 },
2675     { ISD::BSWAP,      MVT::v16i32,  1 },
2676     { ISD::BSWAP,      MVT::v32i16,  1 },
2677     { ISD::CTLZ,       MVT::v8i64,  23 },
2678     { ISD::CTLZ,       MVT::v16i32, 22 },
2679     { ISD::CTLZ,       MVT::v32i16, 18 },
2680     { ISD::CTLZ,       MVT::v64i8,  17 },
2681     { ISD::CTPOP,      MVT::v8i64,   7 },
2682     { ISD::CTPOP,      MVT::v16i32, 11 },
2683     { ISD::CTPOP,      MVT::v32i16,  9 },
2684     { ISD::CTPOP,      MVT::v64i8,   6 },
2685     { ISD::CTTZ,       MVT::v8i64,  10 },
2686     { ISD::CTTZ,       MVT::v16i32, 14 },
2687     { ISD::CTTZ,       MVT::v32i16, 12 },
2688     { ISD::CTTZ,       MVT::v64i8,   9 },
2689     { ISD::SADDSAT,    MVT::v32i16,  1 },
2690     { ISD::SADDSAT,    MVT::v64i8,   1 },
2691     { ISD::SMAX,       MVT::v32i16,  1 },
2692     { ISD::SMAX,       MVT::v64i8,   1 },
2693     { ISD::SMIN,       MVT::v32i16,  1 },
2694     { ISD::SMIN,       MVT::v64i8,   1 },
2695     { ISD::SSUBSAT,    MVT::v32i16,  1 },
2696     { ISD::SSUBSAT,    MVT::v64i8,   1 },
2697     { ISD::UADDSAT,    MVT::v32i16,  1 },
2698     { ISD::UADDSAT,    MVT::v64i8,   1 },
2699     { ISD::UMAX,       MVT::v32i16,  1 },
2700     { ISD::UMAX,       MVT::v64i8,   1 },
2701     { ISD::UMIN,       MVT::v32i16,  1 },
2702     { ISD::UMIN,       MVT::v64i8,   1 },
2703     { ISD::USUBSAT,    MVT::v32i16,  1 },
2704     { ISD::USUBSAT,    MVT::v64i8,   1 },
2705   };
2706   static const CostTblEntry AVX512CostTbl[] = {
2707     { ISD::ABS,        MVT::v8i64,   1 },
2708     { ISD::ABS,        MVT::v16i32,  1 },
2709     { ISD::ABS,        MVT::v32i16,  2 },
2710     { ISD::ABS,        MVT::v64i8,   2 },
2711     { ISD::ABS,        MVT::v4i64,   1 },
2712     { ISD::ABS,        MVT::v2i64,   1 },
2713     { ISD::BITREVERSE, MVT::v8i64,  36 },
2714     { ISD::BITREVERSE, MVT::v16i32, 24 },
2715     { ISD::BITREVERSE, MVT::v32i16, 10 },
2716     { ISD::BITREVERSE, MVT::v64i8,  10 },
2717     { ISD::BSWAP,      MVT::v8i64,   4 },
2718     { ISD::BSWAP,      MVT::v16i32,  4 },
2719     { ISD::BSWAP,      MVT::v32i16,  4 },
2720     { ISD::CTLZ,       MVT::v8i64,  29 },
2721     { ISD::CTLZ,       MVT::v16i32, 35 },
2722     { ISD::CTLZ,       MVT::v32i16, 28 },
2723     { ISD::CTLZ,       MVT::v64i8,  18 },
2724     { ISD::CTPOP,      MVT::v8i64,  16 },
2725     { ISD::CTPOP,      MVT::v16i32, 24 },
2726     { ISD::CTPOP,      MVT::v32i16, 18 },
2727     { ISD::CTPOP,      MVT::v64i8,  12 },
2728     { ISD::CTTZ,       MVT::v8i64,  20 },
2729     { ISD::CTTZ,       MVT::v16i32, 28 },
2730     { ISD::CTTZ,       MVT::v32i16, 24 },
2731     { ISD::CTTZ,       MVT::v64i8,  18 },
2732     { ISD::SMAX,       MVT::v8i64,   1 },
2733     { ISD::SMAX,       MVT::v16i32,  1 },
2734     { ISD::SMAX,       MVT::v32i16,  2 },
2735     { ISD::SMAX,       MVT::v64i8,   2 },
2736     { ISD::SMAX,       MVT::v4i64,   1 },
2737     { ISD::SMAX,       MVT::v2i64,   1 },
2738     { ISD::SMIN,       MVT::v8i64,   1 },
2739     { ISD::SMIN,       MVT::v16i32,  1 },
2740     { ISD::SMIN,       MVT::v32i16,  2 },
2741     { ISD::SMIN,       MVT::v64i8,   2 },
2742     { ISD::SMIN,       MVT::v4i64,   1 },
2743     { ISD::SMIN,       MVT::v2i64,   1 },
2744     { ISD::UMAX,       MVT::v8i64,   1 },
2745     { ISD::UMAX,       MVT::v16i32,  1 },
2746     { ISD::UMAX,       MVT::v32i16,  2 },
2747     { ISD::UMAX,       MVT::v64i8,   2 },
2748     { ISD::UMAX,       MVT::v4i64,   1 },
2749     { ISD::UMAX,       MVT::v2i64,   1 },
2750     { ISD::UMIN,       MVT::v8i64,   1 },
2751     { ISD::UMIN,       MVT::v16i32,  1 },
2752     { ISD::UMIN,       MVT::v32i16,  2 },
2753     { ISD::UMIN,       MVT::v64i8,   2 },
2754     { ISD::UMIN,       MVT::v4i64,   1 },
2755     { ISD::UMIN,       MVT::v2i64,   1 },
2756     { ISD::USUBSAT,    MVT::v16i32,  2 }, // pmaxud + psubd
2757     { ISD::USUBSAT,    MVT::v2i64,   2 }, // pmaxuq + psubq
2758     { ISD::USUBSAT,    MVT::v4i64,   2 }, // pmaxuq + psubq
2759     { ISD::USUBSAT,    MVT::v8i64,   2 }, // pmaxuq + psubq
2760     { ISD::UADDSAT,    MVT::v16i32,  3 }, // not + pminud + paddd
2761     { ISD::UADDSAT,    MVT::v2i64,   3 }, // not + pminuq + paddq
2762     { ISD::UADDSAT,    MVT::v4i64,   3 }, // not + pminuq + paddq
2763     { ISD::UADDSAT,    MVT::v8i64,   3 }, // not + pminuq + paddq
2764     { ISD::SADDSAT,    MVT::v32i16,  2 },
2765     { ISD::SADDSAT,    MVT::v64i8,   2 },
2766     { ISD::SSUBSAT,    MVT::v32i16,  2 },
2767     { ISD::SSUBSAT,    MVT::v64i8,   2 },
2768     { ISD::UADDSAT,    MVT::v32i16,  2 },
2769     { ISD::UADDSAT,    MVT::v64i8,   2 },
2770     { ISD::USUBSAT,    MVT::v32i16,  2 },
2771     { ISD::USUBSAT,    MVT::v64i8,   2 },
2772     { ISD::FMAXNUM,    MVT::f32,     2 },
2773     { ISD::FMAXNUM,    MVT::v4f32,   2 },
2774     { ISD::FMAXNUM,    MVT::v8f32,   2 },
2775     { ISD::FMAXNUM,    MVT::v16f32,  2 },
2776     { ISD::FMAXNUM,    MVT::f64,     2 },
2777     { ISD::FMAXNUM,    MVT::v2f64,   2 },
2778     { ISD::FMAXNUM,    MVT::v4f64,   2 },
2779     { ISD::FMAXNUM,    MVT::v8f64,   2 },
2780   };
2781   static const CostTblEntry XOPCostTbl[] = {
2782     { ISD::BITREVERSE, MVT::v4i64,   4 },
2783     { ISD::BITREVERSE, MVT::v8i32,   4 },
2784     { ISD::BITREVERSE, MVT::v16i16,  4 },
2785     { ISD::BITREVERSE, MVT::v32i8,   4 },
2786     { ISD::BITREVERSE, MVT::v2i64,   1 },
2787     { ISD::BITREVERSE, MVT::v4i32,   1 },
2788     { ISD::BITREVERSE, MVT::v8i16,   1 },
2789     { ISD::BITREVERSE, MVT::v16i8,   1 },
2790     { ISD::BITREVERSE, MVT::i64,     3 },
2791     { ISD::BITREVERSE, MVT::i32,     3 },
2792     { ISD::BITREVERSE, MVT::i16,     3 },
2793     { ISD::BITREVERSE, MVT::i8,      3 }
2794   };
2795   static const CostTblEntry AVX2CostTbl[] = {
2796     { ISD::ABS,        MVT::v4i64,   2 }, // VBLENDVPD(X,VPSUBQ(0,X),X)
2797     { ISD::ABS,        MVT::v8i32,   1 },
2798     { ISD::ABS,        MVT::v16i16,  1 },
2799     { ISD::ABS,        MVT::v32i8,   1 },
2800     { ISD::BITREVERSE, MVT::v2i64,   3 },
2801     { ISD::BITREVERSE, MVT::v4i64,   3 },
2802     { ISD::BITREVERSE, MVT::v4i32,   3 },
2803     { ISD::BITREVERSE, MVT::v8i32,   3 },
2804     { ISD::BITREVERSE, MVT::v8i16,   3 },
2805     { ISD::BITREVERSE, MVT::v16i16,  3 },
2806     { ISD::BITREVERSE, MVT::v16i8,   3 },
2807     { ISD::BITREVERSE, MVT::v32i8,   3 },
2808     { ISD::BSWAP,      MVT::v4i64,   1 },
2809     { ISD::BSWAP,      MVT::v8i32,   1 },
2810     { ISD::BSWAP,      MVT::v16i16,  1 },
2811     { ISD::CTLZ,       MVT::v2i64,   7 },
2812     { ISD::CTLZ,       MVT::v4i64,   7 },
2813     { ISD::CTLZ,       MVT::v4i32,   5 },
2814     { ISD::CTLZ,       MVT::v8i32,   5 },
2815     { ISD::CTLZ,       MVT::v8i16,   4 },
2816     { ISD::CTLZ,       MVT::v16i16,  4 },
2817     { ISD::CTLZ,       MVT::v16i8,   3 },
2818     { ISD::CTLZ,       MVT::v32i8,   3 },
2819     { ISD::CTPOP,      MVT::v2i64,   3 },
2820     { ISD::CTPOP,      MVT::v4i64,   3 },
2821     { ISD::CTPOP,      MVT::v4i32,   7 },
2822     { ISD::CTPOP,      MVT::v8i32,   7 },
2823     { ISD::CTPOP,      MVT::v8i16,   3 },
2824     { ISD::CTPOP,      MVT::v16i16,  3 },
2825     { ISD::CTPOP,      MVT::v16i8,   2 },
2826     { ISD::CTPOP,      MVT::v32i8,   2 },
2827     { ISD::CTTZ,       MVT::v2i64,   4 },
2828     { ISD::CTTZ,       MVT::v4i64,   4 },
2829     { ISD::CTTZ,       MVT::v4i32,   7 },
2830     { ISD::CTTZ,       MVT::v8i32,   7 },
2831     { ISD::CTTZ,       MVT::v8i16,   4 },
2832     { ISD::CTTZ,       MVT::v16i16,  4 },
2833     { ISD::CTTZ,       MVT::v16i8,   3 },
2834     { ISD::CTTZ,       MVT::v32i8,   3 },
2835     { ISD::SADDSAT,    MVT::v16i16,  1 },
2836     { ISD::SADDSAT,    MVT::v32i8,   1 },
2837     { ISD::SMAX,       MVT::v8i32,   1 },
2838     { ISD::SMAX,       MVT::v16i16,  1 },
2839     { ISD::SMAX,       MVT::v32i8,   1 },
2840     { ISD::SMIN,       MVT::v8i32,   1 },
2841     { ISD::SMIN,       MVT::v16i16,  1 },
2842     { ISD::SMIN,       MVT::v32i8,   1 },
2843     { ISD::SSUBSAT,    MVT::v16i16,  1 },
2844     { ISD::SSUBSAT,    MVT::v32i8,   1 },
2845     { ISD::UADDSAT,    MVT::v16i16,  1 },
2846     { ISD::UADDSAT,    MVT::v32i8,   1 },
2847     { ISD::UADDSAT,    MVT::v8i32,   3 }, // not + pminud + paddd
2848     { ISD::UMAX,       MVT::v8i32,   1 },
2849     { ISD::UMAX,       MVT::v16i16,  1 },
2850     { ISD::UMAX,       MVT::v32i8,   1 },
2851     { ISD::UMIN,       MVT::v8i32,   1 },
2852     { ISD::UMIN,       MVT::v16i16,  1 },
2853     { ISD::UMIN,       MVT::v32i8,   1 },
2854     { ISD::USUBSAT,    MVT::v16i16,  1 },
2855     { ISD::USUBSAT,    MVT::v32i8,   1 },
2856     { ISD::USUBSAT,    MVT::v8i32,   2 }, // pmaxud + psubd
2857     { ISD::FMAXNUM,    MVT::v8f32,   3 }, // MAXPS + CMPUNORDPS + BLENDVPS
2858     { ISD::FMAXNUM,    MVT::v4f64,   3 }, // MAXPD + CMPUNORDPD + BLENDVPD
2859     { ISD::FSQRT,      MVT::f32,     7 }, // Haswell from http://www.agner.org/
2860     { ISD::FSQRT,      MVT::v4f32,   7 }, // Haswell from http://www.agner.org/
2861     { ISD::FSQRT,      MVT::v8f32,  14 }, // Haswell from http://www.agner.org/
2862     { ISD::FSQRT,      MVT::f64,    14 }, // Haswell from http://www.agner.org/
2863     { ISD::FSQRT,      MVT::v2f64,  14 }, // Haswell from http://www.agner.org/
2864     { ISD::FSQRT,      MVT::v4f64,  28 }, // Haswell from http://www.agner.org/
2865   };
2866   static const CostTblEntry AVX1CostTbl[] = {
2867     { ISD::ABS,        MVT::v4i64,   5 }, // VBLENDVPD(X,VPSUBQ(0,X),X)
2868     { ISD::ABS,        MVT::v8i32,   3 },
2869     { ISD::ABS,        MVT::v16i16,  3 },
2870     { ISD::ABS,        MVT::v32i8,   3 },
2871     { ISD::BITREVERSE, MVT::v4i64,  12 }, // 2 x 128-bit Op + extract/insert
2872     { ISD::BITREVERSE, MVT::v8i32,  12 }, // 2 x 128-bit Op + extract/insert
2873     { ISD::BITREVERSE, MVT::v16i16, 12 }, // 2 x 128-bit Op + extract/insert
2874     { ISD::BITREVERSE, MVT::v32i8,  12 }, // 2 x 128-bit Op + extract/insert
2875     { ISD::BSWAP,      MVT::v4i64,   4 },
2876     { ISD::BSWAP,      MVT::v8i32,   4 },
2877     { ISD::BSWAP,      MVT::v16i16,  4 },
2878     { ISD::CTLZ,       MVT::v4i64,  48 }, // 2 x 128-bit Op + extract/insert
2879     { ISD::CTLZ,       MVT::v8i32,  38 }, // 2 x 128-bit Op + extract/insert
2880     { ISD::CTLZ,       MVT::v16i16, 30 }, // 2 x 128-bit Op + extract/insert
2881     { ISD::CTLZ,       MVT::v32i8,  20 }, // 2 x 128-bit Op + extract/insert
2882     { ISD::CTPOP,      MVT::v4i64,  16 }, // 2 x 128-bit Op + extract/insert
2883     { ISD::CTPOP,      MVT::v8i32,  24 }, // 2 x 128-bit Op + extract/insert
2884     { ISD::CTPOP,      MVT::v16i16, 20 }, // 2 x 128-bit Op + extract/insert
2885     { ISD::CTPOP,      MVT::v32i8,  14 }, // 2 x 128-bit Op + extract/insert
2886     { ISD::CTTZ,       MVT::v4i64,  22 }, // 2 x 128-bit Op + extract/insert
2887     { ISD::CTTZ,       MVT::v8i32,  30 }, // 2 x 128-bit Op + extract/insert
2888     { ISD::CTTZ,       MVT::v16i16, 26 }, // 2 x 128-bit Op + extract/insert
2889     { ISD::CTTZ,       MVT::v32i8,  20 }, // 2 x 128-bit Op + extract/insert
2890     { ISD::SADDSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2891     { ISD::SADDSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2892     { ISD::SMAX,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2893     { ISD::SMAX,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2894     { ISD::SMAX,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2895     { ISD::SMIN,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2896     { ISD::SMIN,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2897     { ISD::SMIN,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2898     { ISD::SSUBSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2899     { ISD::SSUBSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2900     { ISD::UADDSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2901     { ISD::UADDSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2902     { ISD::UADDSAT,    MVT::v8i32,   8 }, // 2 x 128-bit Op + extract/insert
2903     { ISD::UMAX,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2904     { ISD::UMAX,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2905     { ISD::UMAX,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2906     { ISD::UMIN,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2907     { ISD::UMIN,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2908     { ISD::UMIN,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2909     { ISD::USUBSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2910     { ISD::USUBSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2911     { ISD::USUBSAT,    MVT::v8i32,   6 }, // 2 x 128-bit Op + extract/insert
2912     { ISD::FMAXNUM,    MVT::f32,     3 }, // MAXSS + CMPUNORDSS + BLENDVPS
2913     { ISD::FMAXNUM,    MVT::v4f32,   3 }, // MAXPS + CMPUNORDPS + BLENDVPS
2914     { ISD::FMAXNUM,    MVT::v8f32,   5 }, // MAXPS + CMPUNORDPS + BLENDVPS + ?
2915     { ISD::FMAXNUM,    MVT::f64,     3 }, // MAXSD + CMPUNORDSD + BLENDVPD
2916     { ISD::FMAXNUM,    MVT::v2f64,   3 }, // MAXPD + CMPUNORDPD + BLENDVPD
2917     { ISD::FMAXNUM,    MVT::v4f64,   5 }, // MAXPD + CMPUNORDPD + BLENDVPD + ?
2918     { ISD::FSQRT,      MVT::f32,    14 }, // SNB from http://www.agner.org/
2919     { ISD::FSQRT,      MVT::v4f32,  14 }, // SNB from http://www.agner.org/
2920     { ISD::FSQRT,      MVT::v8f32,  28 }, // SNB from http://www.agner.org/
2921     { ISD::FSQRT,      MVT::f64,    21 }, // SNB from http://www.agner.org/
2922     { ISD::FSQRT,      MVT::v2f64,  21 }, // SNB from http://www.agner.org/
2923     { ISD::FSQRT,      MVT::v4f64,  43 }, // SNB from http://www.agner.org/
2924   };
2925   static const CostTblEntry GLMCostTbl[] = {
2926     { ISD::FSQRT, MVT::f32,   19 }, // sqrtss
2927     { ISD::FSQRT, MVT::v4f32, 37 }, // sqrtps
2928     { ISD::FSQRT, MVT::f64,   34 }, // sqrtsd
2929     { ISD::FSQRT, MVT::v2f64, 67 }, // sqrtpd
2930   };
2931   static const CostTblEntry SLMCostTbl[] = {
2932     { ISD::FSQRT, MVT::f32,   20 }, // sqrtss
2933     { ISD::FSQRT, MVT::v4f32, 40 }, // sqrtps
2934     { ISD::FSQRT, MVT::f64,   35 }, // sqrtsd
2935     { ISD::FSQRT, MVT::v2f64, 70 }, // sqrtpd
2936   };
2937   static const CostTblEntry SSE42CostTbl[] = {
2938     { ISD::USUBSAT,    MVT::v4i32,   2 }, // pmaxud + psubd
2939     { ISD::UADDSAT,    MVT::v4i32,   3 }, // not + pminud + paddd
2940     { ISD::FSQRT,      MVT::f32,    18 }, // Nehalem from http://www.agner.org/
2941     { ISD::FSQRT,      MVT::v4f32,  18 }, // Nehalem from http://www.agner.org/
2942   };
2943   static const CostTblEntry SSE41CostTbl[] = {
2944     { ISD::ABS,        MVT::v2i64,   2 }, // BLENDVPD(X,PSUBQ(0,X),X)
2945     { ISD::SMAX,       MVT::v4i32,   1 },
2946     { ISD::SMAX,       MVT::v16i8,   1 },
2947     { ISD::SMIN,       MVT::v4i32,   1 },
2948     { ISD::SMIN,       MVT::v16i8,   1 },
2949     { ISD::UMAX,       MVT::v4i32,   1 },
2950     { ISD::UMAX,       MVT::v8i16,   1 },
2951     { ISD::UMIN,       MVT::v4i32,   1 },
2952     { ISD::UMIN,       MVT::v8i16,   1 },
2953   };
2954   static const CostTblEntry SSSE3CostTbl[] = {
2955     { ISD::ABS,        MVT::v4i32,   1 },
2956     { ISD::ABS,        MVT::v8i16,   1 },
2957     { ISD::ABS,        MVT::v16i8,   1 },
2958     { ISD::BITREVERSE, MVT::v2i64,   5 },
2959     { ISD::BITREVERSE, MVT::v4i32,   5 },
2960     { ISD::BITREVERSE, MVT::v8i16,   5 },
2961     { ISD::BITREVERSE, MVT::v16i8,   5 },
2962     { ISD::BSWAP,      MVT::v2i64,   1 },
2963     { ISD::BSWAP,      MVT::v4i32,   1 },
2964     { ISD::BSWAP,      MVT::v8i16,   1 },
2965     { ISD::CTLZ,       MVT::v2i64,  23 },
2966     { ISD::CTLZ,       MVT::v4i32,  18 },
2967     { ISD::CTLZ,       MVT::v8i16,  14 },
2968     { ISD::CTLZ,       MVT::v16i8,   9 },
2969     { ISD::CTPOP,      MVT::v2i64,   7 },
2970     { ISD::CTPOP,      MVT::v4i32,  11 },
2971     { ISD::CTPOP,      MVT::v8i16,   9 },
2972     { ISD::CTPOP,      MVT::v16i8,   6 },
2973     { ISD::CTTZ,       MVT::v2i64,  10 },
2974     { ISD::CTTZ,       MVT::v4i32,  14 },
2975     { ISD::CTTZ,       MVT::v8i16,  12 },
2976     { ISD::CTTZ,       MVT::v16i8,   9 }
2977   };
2978   static const CostTblEntry SSE2CostTbl[] = {
2979     { ISD::ABS,        MVT::v2i64,   4 },
2980     { ISD::ABS,        MVT::v4i32,   3 },
2981     { ISD::ABS,        MVT::v8i16,   2 },
2982     { ISD::ABS,        MVT::v16i8,   2 },
2983     { ISD::BITREVERSE, MVT::v2i64,  29 },
2984     { ISD::BITREVERSE, MVT::v4i32,  27 },
2985     { ISD::BITREVERSE, MVT::v8i16,  27 },
2986     { ISD::BITREVERSE, MVT::v16i8,  20 },
2987     { ISD::BSWAP,      MVT::v2i64,   7 },
2988     { ISD::BSWAP,      MVT::v4i32,   7 },
2989     { ISD::BSWAP,      MVT::v8i16,   7 },
2990     { ISD::CTLZ,       MVT::v2i64,  25 },
2991     { ISD::CTLZ,       MVT::v4i32,  26 },
2992     { ISD::CTLZ,       MVT::v8i16,  20 },
2993     { ISD::CTLZ,       MVT::v16i8,  17 },
2994     { ISD::CTPOP,      MVT::v2i64,  12 },
2995     { ISD::CTPOP,      MVT::v4i32,  15 },
2996     { ISD::CTPOP,      MVT::v8i16,  13 },
2997     { ISD::CTPOP,      MVT::v16i8,  10 },
2998     { ISD::CTTZ,       MVT::v2i64,  14 },
2999     { ISD::CTTZ,       MVT::v4i32,  18 },
3000     { ISD::CTTZ,       MVT::v8i16,  16 },
3001     { ISD::CTTZ,       MVT::v16i8,  13 },
3002     { ISD::SADDSAT,    MVT::v8i16,   1 },
3003     { ISD::SADDSAT,    MVT::v16i8,   1 },
3004     { ISD::SMAX,       MVT::v8i16,   1 },
3005     { ISD::SMIN,       MVT::v8i16,   1 },
3006     { ISD::SSUBSAT,    MVT::v8i16,   1 },
3007     { ISD::SSUBSAT,    MVT::v16i8,   1 },
3008     { ISD::UADDSAT,    MVT::v8i16,   1 },
3009     { ISD::UADDSAT,    MVT::v16i8,   1 },
3010     { ISD::UMAX,       MVT::v8i16,   2 },
3011     { ISD::UMAX,       MVT::v16i8,   1 },
3012     { ISD::UMIN,       MVT::v8i16,   2 },
3013     { ISD::UMIN,       MVT::v16i8,   1 },
3014     { ISD::USUBSAT,    MVT::v8i16,   1 },
3015     { ISD::USUBSAT,    MVT::v16i8,   1 },
3016     { ISD::FMAXNUM,    MVT::f64,     4 },
3017     { ISD::FMAXNUM,    MVT::v2f64,   4 },
3018     { ISD::FSQRT,      MVT::f64,    32 }, // Nehalem from http://www.agner.org/
3019     { ISD::FSQRT,      MVT::v2f64,  32 }, // Nehalem from http://www.agner.org/
3020   };
3021   static const CostTblEntry SSE1CostTbl[] = {
3022     { ISD::FMAXNUM,    MVT::f32,     4 },
3023     { ISD::FMAXNUM,    MVT::v4f32,   4 },
3024     { ISD::FSQRT,      MVT::f32,    28 }, // Pentium III from http://www.agner.org/
3025     { ISD::FSQRT,      MVT::v4f32,  56 }, // Pentium III from http://www.agner.org/
3026   };
3027   static const CostTblEntry BMI64CostTbl[] = { // 64-bit targets
3028     { ISD::CTTZ,       MVT::i64,     1 },
3029   };
3030   static const CostTblEntry BMI32CostTbl[] = { // 32 or 64-bit targets
3031     { ISD::CTTZ,       MVT::i32,     1 },
3032     { ISD::CTTZ,       MVT::i16,     1 },
3033     { ISD::CTTZ,       MVT::i8,      1 },
3034   };
3035   static const CostTblEntry LZCNT64CostTbl[] = { // 64-bit targets
3036     { ISD::CTLZ,       MVT::i64,     1 },
3037   };
3038   static const CostTblEntry LZCNT32CostTbl[] = { // 32 or 64-bit targets
3039     { ISD::CTLZ,       MVT::i32,     1 },
3040     { ISD::CTLZ,       MVT::i16,     1 },
3041     { ISD::CTLZ,       MVT::i8,      1 },
3042   };
3043   static const CostTblEntry POPCNT64CostTbl[] = { // 64-bit targets
3044     { ISD::CTPOP,      MVT::i64,     1 },
3045   };
3046   static const CostTblEntry POPCNT32CostTbl[] = { // 32 or 64-bit targets
3047     { ISD::CTPOP,      MVT::i32,     1 },
3048     { ISD::CTPOP,      MVT::i16,     1 },
3049     { ISD::CTPOP,      MVT::i8,      1 },
3050   };
3051   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
3052     { ISD::ABS,        MVT::i64,     2 }, // SUB+CMOV
3053     { ISD::BITREVERSE, MVT::i64,    14 },
3054     { ISD::BSWAP,      MVT::i64,     1 },
3055     { ISD::CTLZ,       MVT::i64,     4 }, // BSR+XOR or BSR+XOR+CMOV
3056     { ISD::CTTZ,       MVT::i64,     3 }, // TEST+BSF+CMOV/BRANCH
3057     { ISD::CTPOP,      MVT::i64,    10 },
3058     { ISD::SADDO,      MVT::i64,     1 },
3059     { ISD::UADDO,      MVT::i64,     1 },
3060     { ISD::UMULO,      MVT::i64,     2 }, // mulq + seto
3061   };
3062   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
3063     { ISD::ABS,        MVT::i32,     2 }, // SUB+CMOV
3064     { ISD::ABS,        MVT::i16,     2 }, // SUB+CMOV
3065     { ISD::BITREVERSE, MVT::i32,    14 },
3066     { ISD::BITREVERSE, MVT::i16,    14 },
3067     { ISD::BITREVERSE, MVT::i8,     11 },
3068     { ISD::BSWAP,      MVT::i32,     1 },
3069     { ISD::BSWAP,      MVT::i16,     1 }, // ROL
3070     { ISD::CTLZ,       MVT::i32,     4 }, // BSR+XOR or BSR+XOR+CMOV
3071     { ISD::CTLZ,       MVT::i16,     4 }, // BSR+XOR or BSR+XOR+CMOV
3072     { ISD::CTLZ,       MVT::i8,      4 }, // BSR+XOR or BSR+XOR+CMOV
3073     { ISD::CTTZ,       MVT::i32,     3 }, // TEST+BSF+CMOV/BRANCH
3074     { ISD::CTTZ,       MVT::i16,     3 }, // TEST+BSF+CMOV/BRANCH
3075     { ISD::CTTZ,       MVT::i8,      3 }, // TEST+BSF+CMOV/BRANCH
3076     { ISD::CTPOP,      MVT::i32,     8 },
3077     { ISD::CTPOP,      MVT::i16,     9 },
3078     { ISD::CTPOP,      MVT::i8,      7 },
3079     { ISD::SADDO,      MVT::i32,     1 },
3080     { ISD::SADDO,      MVT::i16,     1 },
3081     { ISD::SADDO,      MVT::i8,      1 },
3082     { ISD::UADDO,      MVT::i32,     1 },
3083     { ISD::UADDO,      MVT::i16,     1 },
3084     { ISD::UADDO,      MVT::i8,      1 },
3085     { ISD::UMULO,      MVT::i32,     2 }, // mul + seto
3086     { ISD::UMULO,      MVT::i16,     2 },
3087     { ISD::UMULO,      MVT::i8,      2 },
3088   };
3089 
3090   Type *RetTy = ICA.getReturnType();
3091   Type *OpTy = RetTy;
3092   Intrinsic::ID IID = ICA.getID();
3093   unsigned ISD = ISD::DELETED_NODE;
3094   switch (IID) {
3095   default:
3096     break;
3097   case Intrinsic::abs:
3098     ISD = ISD::ABS;
3099     break;
3100   case Intrinsic::bitreverse:
3101     ISD = ISD::BITREVERSE;
3102     break;
3103   case Intrinsic::bswap:
3104     ISD = ISD::BSWAP;
3105     break;
3106   case Intrinsic::ctlz:
3107     ISD = ISD::CTLZ;
3108     break;
3109   case Intrinsic::ctpop:
3110     ISD = ISD::CTPOP;
3111     break;
3112   case Intrinsic::cttz:
3113     ISD = ISD::CTTZ;
3114     break;
3115   case Intrinsic::maxnum:
3116   case Intrinsic::minnum:
3117     // FMINNUM has same costs so don't duplicate.
3118     ISD = ISD::FMAXNUM;
3119     break;
3120   case Intrinsic::sadd_sat:
3121     ISD = ISD::SADDSAT;
3122     break;
3123   case Intrinsic::smax:
3124     ISD = ISD::SMAX;
3125     break;
3126   case Intrinsic::smin:
3127     ISD = ISD::SMIN;
3128     break;
3129   case Intrinsic::ssub_sat:
3130     ISD = ISD::SSUBSAT;
3131     break;
3132   case Intrinsic::uadd_sat:
3133     ISD = ISD::UADDSAT;
3134     break;
3135   case Intrinsic::umax:
3136     ISD = ISD::UMAX;
3137     break;
3138   case Intrinsic::umin:
3139     ISD = ISD::UMIN;
3140     break;
3141   case Intrinsic::usub_sat:
3142     ISD = ISD::USUBSAT;
3143     break;
3144   case Intrinsic::sqrt:
3145     ISD = ISD::FSQRT;
3146     break;
3147   case Intrinsic::sadd_with_overflow:
3148   case Intrinsic::ssub_with_overflow:
3149     // SSUBO has same costs so don't duplicate.
3150     ISD = ISD::SADDO;
3151     OpTy = RetTy->getContainedType(0);
3152     break;
3153   case Intrinsic::uadd_with_overflow:
3154   case Intrinsic::usub_with_overflow:
3155     // USUBO has same costs so don't duplicate.
3156     ISD = ISD::UADDO;
3157     OpTy = RetTy->getContainedType(0);
3158     break;
3159   case Intrinsic::umul_with_overflow:
3160   case Intrinsic::smul_with_overflow:
3161     // SMULO has same costs so don't duplicate.
3162     ISD = ISD::UMULO;
3163     OpTy = RetTy->getContainedType(0);
3164     break;
3165   }
3166 
3167   if (ISD != ISD::DELETED_NODE) {
3168     // Legalize the type.
3169     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, OpTy);
3170     MVT MTy = LT.second;
3171 
3172     // Attempt to lookup cost.
3173     if (ISD == ISD::BITREVERSE && ST->hasGFNI() && ST->hasSSSE3() &&
3174         MTy.isVector()) {
3175       // With PSHUFB the code is very similar for all types. If we have integer
3176       // byte operations, we just need a GF2P8AFFINEQB for vXi8. For other types
3177       // we also need a PSHUFB.
3178       unsigned Cost = MTy.getVectorElementType() == MVT::i8 ? 1 : 2;
3179 
3180       // Without byte operations, we need twice as many GF2P8AFFINEQB and PSHUFB
3181       // instructions. We also need an extract and an insert.
3182       if (!(MTy.is128BitVector() || (ST->hasAVX2() && MTy.is256BitVector()) ||
3183             (ST->hasBWI() && MTy.is512BitVector())))
3184         Cost = Cost * 2 + 2;
3185 
3186       return LT.first * Cost;
3187     }
3188 
3189     auto adjustTableCost = [](const CostTblEntry &Entry,
3190                               InstructionCost LegalizationCost,
3191                               FastMathFlags FMF) {
3192       // If there are no NANs to deal with, then these are reduced to a
3193       // single MIN** or MAX** instruction instead of the MIN/CMP/SELECT that we
3194       // assume is used in the non-fast case.
3195       if (Entry.ISD == ISD::FMAXNUM || Entry.ISD == ISD::FMINNUM) {
3196         if (FMF.noNaNs())
3197           return LegalizationCost * 1;
3198       }
3199       return LegalizationCost * (int)Entry.Cost;
3200     };
3201 
3202     if (ST->useGLMDivSqrtCosts())
3203       if (const auto *Entry = CostTableLookup(GLMCostTbl, ISD, MTy))
3204         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3205 
3206     if (ST->useSLMArithCosts())
3207       if (const auto *Entry = CostTableLookup(SLMCostTbl, ISD, MTy))
3208         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3209 
3210     if (ST->hasBITALG())
3211       if (const auto *Entry = CostTableLookup(AVX512BITALGCostTbl, ISD, MTy))
3212         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3213 
3214     if (ST->hasVPOPCNTDQ())
3215       if (const auto *Entry = CostTableLookup(AVX512VPOPCNTDQCostTbl, ISD, MTy))
3216         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3217 
3218     if (ST->hasCDI())
3219       if (const auto *Entry = CostTableLookup(AVX512CDCostTbl, ISD, MTy))
3220         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3221 
3222     if (ST->hasBWI())
3223       if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
3224         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3225 
3226     if (ST->hasAVX512())
3227       if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
3228         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3229 
3230     if (ST->hasXOP())
3231       if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
3232         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3233 
3234     if (ST->hasAVX2())
3235       if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
3236         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3237 
3238     if (ST->hasAVX())
3239       if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
3240         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3241 
3242     if (ST->hasSSE42())
3243       if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
3244         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3245 
3246     if (ST->hasSSE41())
3247       if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
3248         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3249 
3250     if (ST->hasSSSE3())
3251       if (const auto *Entry = CostTableLookup(SSSE3CostTbl, ISD, MTy))
3252         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3253 
3254     if (ST->hasSSE2())
3255       if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
3256         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3257 
3258     if (ST->hasSSE1())
3259       if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
3260         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3261 
3262     if (ST->hasBMI()) {
3263       if (ST->is64Bit())
3264         if (const auto *Entry = CostTableLookup(BMI64CostTbl, ISD, MTy))
3265           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3266 
3267       if (const auto *Entry = CostTableLookup(BMI32CostTbl, ISD, MTy))
3268         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3269     }
3270 
3271     if (ST->hasLZCNT()) {
3272       if (ST->is64Bit())
3273         if (const auto *Entry = CostTableLookup(LZCNT64CostTbl, ISD, MTy))
3274           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3275 
3276       if (const auto *Entry = CostTableLookup(LZCNT32CostTbl, ISD, MTy))
3277         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3278     }
3279 
3280     if (ST->hasPOPCNT()) {
3281       if (ST->is64Bit())
3282         if (const auto *Entry = CostTableLookup(POPCNT64CostTbl, ISD, MTy))
3283           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3284 
3285       if (const auto *Entry = CostTableLookup(POPCNT32CostTbl, ISD, MTy))
3286         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3287     }
3288 
3289     if (ISD == ISD::BSWAP && ST->hasMOVBE() && ST->hasFastMOVBE()) {
3290       if (const Instruction *II = ICA.getInst()) {
3291         if (II->hasOneUse() && isa<StoreInst>(II->user_back()))
3292           return TTI::TCC_Free;
3293         if (auto *LI = dyn_cast<LoadInst>(II->getOperand(0))) {
3294           if (LI->hasOneUse())
3295             return TTI::TCC_Free;
3296         }
3297       }
3298     }
3299 
3300     if (ST->is64Bit())
3301       if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
3302         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3303 
3304     if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
3305       return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3306   }
3307 
3308   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
3309 }
3310 
3311 InstructionCost
3312 X86TTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
3313                                   TTI::TargetCostKind CostKind) {
3314   if (ICA.isTypeBasedOnly())
3315     return getTypeBasedIntrinsicInstrCost(ICA, CostKind);
3316 
3317   static const CostTblEntry AVX512CostTbl[] = {
3318     { ISD::ROTL,       MVT::v8i64,   1 },
3319     { ISD::ROTL,       MVT::v4i64,   1 },
3320     { ISD::ROTL,       MVT::v2i64,   1 },
3321     { ISD::ROTL,       MVT::v16i32,  1 },
3322     { ISD::ROTL,       MVT::v8i32,   1 },
3323     { ISD::ROTL,       MVT::v4i32,   1 },
3324     { ISD::ROTR,       MVT::v8i64,   1 },
3325     { ISD::ROTR,       MVT::v4i64,   1 },
3326     { ISD::ROTR,       MVT::v2i64,   1 },
3327     { ISD::ROTR,       MVT::v16i32,  1 },
3328     { ISD::ROTR,       MVT::v8i32,   1 },
3329     { ISD::ROTR,       MVT::v4i32,   1 }
3330   };
3331   // XOP: ROTL = VPROT(X,Y), ROTR = VPROT(X,SUB(0,Y))
3332   static const CostTblEntry XOPCostTbl[] = {
3333     { ISD::ROTL,       MVT::v4i64,   4 },
3334     { ISD::ROTL,       MVT::v8i32,   4 },
3335     { ISD::ROTL,       MVT::v16i16,  4 },
3336     { ISD::ROTL,       MVT::v32i8,   4 },
3337     { ISD::ROTL,       MVT::v2i64,   1 },
3338     { ISD::ROTL,       MVT::v4i32,   1 },
3339     { ISD::ROTL,       MVT::v8i16,   1 },
3340     { ISD::ROTL,       MVT::v16i8,   1 },
3341     { ISD::ROTR,       MVT::v4i64,   6 },
3342     { ISD::ROTR,       MVT::v8i32,   6 },
3343     { ISD::ROTR,       MVT::v16i16,  6 },
3344     { ISD::ROTR,       MVT::v32i8,   6 },
3345     { ISD::ROTR,       MVT::v2i64,   2 },
3346     { ISD::ROTR,       MVT::v4i32,   2 },
3347     { ISD::ROTR,       MVT::v8i16,   2 },
3348     { ISD::ROTR,       MVT::v16i8,   2 }
3349   };
3350   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
3351     { ISD::ROTL,       MVT::i64,     1 },
3352     { ISD::ROTR,       MVT::i64,     1 },
3353     { ISD::FSHL,       MVT::i64,     4 }
3354   };
3355   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
3356     { ISD::ROTL,       MVT::i32,     1 },
3357     { ISD::ROTL,       MVT::i16,     1 },
3358     { ISD::ROTL,       MVT::i8,      1 },
3359     { ISD::ROTR,       MVT::i32,     1 },
3360     { ISD::ROTR,       MVT::i16,     1 },
3361     { ISD::ROTR,       MVT::i8,      1 },
3362     { ISD::FSHL,       MVT::i32,     4 },
3363     { ISD::FSHL,       MVT::i16,     4 },
3364     { ISD::FSHL,       MVT::i8,      4 }
3365   };
3366 
3367   Intrinsic::ID IID = ICA.getID();
3368   Type *RetTy = ICA.getReturnType();
3369   const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
3370   unsigned ISD = ISD::DELETED_NODE;
3371   switch (IID) {
3372   default:
3373     break;
3374   case Intrinsic::fshl:
3375     ISD = ISD::FSHL;
3376     if (Args[0] == Args[1])
3377       ISD = ISD::ROTL;
3378     break;
3379   case Intrinsic::fshr:
3380     // FSHR has same costs so don't duplicate.
3381     ISD = ISD::FSHL;
3382     if (Args[0] == Args[1])
3383       ISD = ISD::ROTR;
3384     break;
3385   }
3386 
3387   if (ISD != ISD::DELETED_NODE) {
3388     // Legalize the type.
3389     std::pair<InstructionCost, MVT> LT =
3390         TLI->getTypeLegalizationCost(DL, RetTy);
3391     MVT MTy = LT.second;
3392 
3393     // Attempt to lookup cost.
3394     if (ST->hasAVX512())
3395       if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
3396         return LT.first * Entry->Cost;
3397 
3398     if (ST->hasXOP())
3399       if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
3400         return LT.first * Entry->Cost;
3401 
3402     if (ST->is64Bit())
3403       if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
3404         return LT.first * Entry->Cost;
3405 
3406     if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
3407       return LT.first * Entry->Cost;
3408   }
3409 
3410   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
3411 }
3412 
3413 InstructionCost X86TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
3414                                                unsigned Index) {
3415   static const CostTblEntry SLMCostTbl[] = {
3416      { ISD::EXTRACT_VECTOR_ELT,       MVT::i8,      4 },
3417      { ISD::EXTRACT_VECTOR_ELT,       MVT::i16,     4 },
3418      { ISD::EXTRACT_VECTOR_ELT,       MVT::i32,     4 },
3419      { ISD::EXTRACT_VECTOR_ELT,       MVT::i64,     7 }
3420    };
3421 
3422   assert(Val->isVectorTy() && "This must be a vector type");
3423   Type *ScalarType = Val->getScalarType();
3424   int RegisterFileMoveCost = 0;
3425 
3426   // Non-immediate extraction/insertion can be handled as a sequence of
3427   // aliased loads+stores via the stack.
3428   if (Index == -1U && (Opcode == Instruction::ExtractElement ||
3429                        Opcode == Instruction::InsertElement)) {
3430     // TODO: On some SSE41+ targets, we expand to cmp+splat+select patterns:
3431     // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
3432 
3433     // TODO: Move this to BasicTTIImpl.h? We'd need better gep + index handling.
3434     assert(isa<FixedVectorType>(Val) && "Fixed vector type expected");
3435     Align VecAlign = DL.getPrefTypeAlign(Val);
3436     Align SclAlign = DL.getPrefTypeAlign(ScalarType);
3437 
3438     // Extract - store vector to stack, load scalar.
3439     if (Opcode == Instruction::ExtractElement) {
3440       return getMemoryOpCost(Instruction::Store, Val, VecAlign, 0,
3441                              TTI::TargetCostKind::TCK_RecipThroughput) +
3442              getMemoryOpCost(Instruction::Load, ScalarType, SclAlign, 0,
3443                              TTI::TargetCostKind::TCK_RecipThroughput);
3444     }
3445     // Insert - store vector to stack, store scalar, load vector.
3446     if (Opcode == Instruction::InsertElement) {
3447       return getMemoryOpCost(Instruction::Store, Val, VecAlign, 0,
3448                              TTI::TargetCostKind::TCK_RecipThroughput) +
3449              getMemoryOpCost(Instruction::Store, ScalarType, SclAlign, 0,
3450                              TTI::TargetCostKind::TCK_RecipThroughput) +
3451              getMemoryOpCost(Instruction::Load, Val, VecAlign, 0,
3452                              TTI::TargetCostKind::TCK_RecipThroughput);
3453     }
3454   }
3455 
3456   if (Index != -1U && (Opcode == Instruction::ExtractElement ||
3457                        Opcode == Instruction::InsertElement)) {
3458     // Legalize the type.
3459     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
3460 
3461     // This type is legalized to a scalar type.
3462     if (!LT.second.isVector())
3463       return 0;
3464 
3465     // The type may be split. Normalize the index to the new type.
3466     unsigned NumElts = LT.second.getVectorNumElements();
3467     unsigned SubNumElts = NumElts;
3468     Index = Index % NumElts;
3469 
3470     // For >128-bit vectors, we need to extract higher 128-bit subvectors.
3471     // For inserts, we also need to insert the subvector back.
3472     if (LT.second.getSizeInBits() > 128) {
3473       assert((LT.second.getSizeInBits() % 128) == 0 && "Illegal vector");
3474       unsigned NumSubVecs = LT.second.getSizeInBits() / 128;
3475       SubNumElts = NumElts / NumSubVecs;
3476       if (SubNumElts <= Index) {
3477         RegisterFileMoveCost += (Opcode == Instruction::InsertElement ? 2 : 1);
3478         Index %= SubNumElts;
3479       }
3480     }
3481 
3482     if (Index == 0) {
3483       // Floating point scalars are already located in index #0.
3484       // Many insertions to #0 can fold away for scalar fp-ops, so let's assume
3485       // true for all.
3486       if (ScalarType->isFloatingPointTy())
3487         return RegisterFileMoveCost;
3488 
3489       // Assume movd/movq XMM -> GPR is relatively cheap on all targets.
3490       if (ScalarType->isIntegerTy() && Opcode == Instruction::ExtractElement)
3491         return 1 + RegisterFileMoveCost;
3492     }
3493 
3494     int ISD = TLI->InstructionOpcodeToISD(Opcode);
3495     assert(ISD && "Unexpected vector opcode");
3496     MVT MScalarTy = LT.second.getScalarType();
3497     if (ST->useSLMArithCosts())
3498       if (auto *Entry = CostTableLookup(SLMCostTbl, ISD, MScalarTy))
3499         return Entry->Cost + RegisterFileMoveCost;
3500 
3501     // Assume pinsr/pextr XMM <-> GPR is relatively cheap on all targets.
3502     if ((MScalarTy == MVT::i16 && ST->hasSSE2()) ||
3503         (MScalarTy.isInteger() && ST->hasSSE41()))
3504       return 1 + RegisterFileMoveCost;
3505 
3506     // Assume insertps is relatively cheap on all targets.
3507     if (MScalarTy == MVT::f32 && ST->hasSSE41() &&
3508         Opcode == Instruction::InsertElement)
3509       return 1 + RegisterFileMoveCost;
3510 
3511     // For extractions we just need to shuffle the element to index 0, which
3512     // should be very cheap (assume cost = 1). For insertions we need to shuffle
3513     // the elements to its destination. In both cases we must handle the
3514     // subvector move(s).
3515     // If the vector type is already less than 128-bits then don't reduce it.
3516     // TODO: Under what circumstances should we shuffle using the full width?
3517     InstructionCost ShuffleCost = 1;
3518     if (Opcode == Instruction::InsertElement) {
3519       auto *SubTy = cast<VectorType>(Val);
3520       EVT VT = TLI->getValueType(DL, Val);
3521       if (VT.getScalarType() != MScalarTy || VT.getSizeInBits() >= 128)
3522         SubTy = FixedVectorType::get(ScalarType, SubNumElts);
3523       ShuffleCost =
3524           getShuffleCost(TTI::SK_PermuteTwoSrc, SubTy, None, 0, SubTy);
3525     }
3526     int IntOrFpCost = ScalarType->isFloatingPointTy() ? 0 : 1;
3527     return ShuffleCost + IntOrFpCost + RegisterFileMoveCost;
3528   }
3529 
3530   // Add to the base cost if we know that the extracted element of a vector is
3531   // destined to be moved to and used in the integer register file.
3532   if (Opcode == Instruction::ExtractElement && ScalarType->isPointerTy())
3533     RegisterFileMoveCost += 1;
3534 
3535   return BaseT::getVectorInstrCost(Opcode, Val, Index) + RegisterFileMoveCost;
3536 }
3537 
3538 InstructionCost X86TTIImpl::getScalarizationOverhead(VectorType *Ty,
3539                                                      const APInt &DemandedElts,
3540                                                      bool Insert,
3541                                                      bool Extract) {
3542   InstructionCost Cost = 0;
3543 
3544   // For insertions, a ISD::BUILD_VECTOR style vector initialization can be much
3545   // cheaper than an accumulation of ISD::INSERT_VECTOR_ELT.
3546   if (Insert) {
3547     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
3548     MVT MScalarTy = LT.second.getScalarType();
3549 
3550     if ((MScalarTy == MVT::i16 && ST->hasSSE2()) ||
3551         (MScalarTy.isInteger() && ST->hasSSE41()) ||
3552         (MScalarTy == MVT::f32 && ST->hasSSE41())) {
3553       // For types we can insert directly, insertion into 128-bit sub vectors is
3554       // cheap, followed by a cheap chain of concatenations.
3555       if (LT.second.getSizeInBits() <= 128) {
3556         Cost +=
3557             BaseT::getScalarizationOverhead(Ty, DemandedElts, Insert, false);
3558       } else {
3559         // In each 128-lane, if at least one index is demanded but not all
3560         // indices are demanded and this 128-lane is not the first 128-lane of
3561         // the legalized-vector, then this 128-lane needs a extracti128; If in
3562         // each 128-lane, there is at least one demanded index, this 128-lane
3563         // needs a inserti128.
3564 
3565         // The following cases will help you build a better understanding:
3566         // Assume we insert several elements into a v8i32 vector in avx2,
3567         // Case#1: inserting into 1th index needs vpinsrd + inserti128.
3568         // Case#2: inserting into 5th index needs extracti128 + vpinsrd +
3569         // inserti128.
3570         // Case#3: inserting into 4,5,6,7 index needs 4*vpinsrd + inserti128.
3571         const int CostValue = *LT.first.getValue();
3572         assert(CostValue >= 0 && "Negative cost!");
3573         unsigned Num128Lanes = LT.second.getSizeInBits() / 128 * CostValue;
3574         unsigned NumElts = LT.second.getVectorNumElements() * CostValue;
3575         APInt WidenedDemandedElts = DemandedElts.zextOrSelf(NumElts);
3576         unsigned Scale = NumElts / Num128Lanes;
3577         // We iterate each 128-lane, and check if we need a
3578         // extracti128/inserti128 for this 128-lane.
3579         for (unsigned I = 0; I < NumElts; I += Scale) {
3580           APInt Mask = WidenedDemandedElts.getBitsSet(NumElts, I, I + Scale);
3581           APInt MaskedDE = Mask & WidenedDemandedElts;
3582           unsigned Population = MaskedDE.countPopulation();
3583           Cost += (Population > 0 && Population != Scale &&
3584                    I % LT.second.getVectorNumElements() != 0);
3585           Cost += Population > 0;
3586         }
3587         Cost += DemandedElts.countPopulation();
3588 
3589         // For vXf32 cases, insertion into the 0'th index in each v4f32
3590         // 128-bit vector is free.
3591         // NOTE: This assumes legalization widens vXf32 vectors.
3592         if (MScalarTy == MVT::f32)
3593           for (unsigned i = 0, e = cast<FixedVectorType>(Ty)->getNumElements();
3594                i < e; i += 4)
3595             if (DemandedElts[i])
3596               Cost--;
3597       }
3598     } else if (LT.second.isVector()) {
3599       // Without fast insertion, we need to use MOVD/MOVQ to pass each demanded
3600       // integer element as a SCALAR_TO_VECTOR, then we build the vector as a
3601       // series of UNPCK followed by CONCAT_VECTORS - all of these can be
3602       // considered cheap.
3603       if (Ty->isIntOrIntVectorTy())
3604         Cost += DemandedElts.countPopulation();
3605 
3606       // Get the smaller of the legalized or original pow2-extended number of
3607       // vector elements, which represents the number of unpacks we'll end up
3608       // performing.
3609       unsigned NumElts = LT.second.getVectorNumElements();
3610       unsigned Pow2Elts =
3611           PowerOf2Ceil(cast<FixedVectorType>(Ty)->getNumElements());
3612       Cost += (std::min<unsigned>(NumElts, Pow2Elts) - 1) * LT.first;
3613     }
3614   }
3615 
3616   // TODO: Use default extraction for now, but we should investigate extending this
3617   // to handle repeated subvector extraction.
3618   if (Extract)
3619     Cost += BaseT::getScalarizationOverhead(Ty, DemandedElts, false, Extract);
3620 
3621   return Cost;
3622 }
3623 
3624 InstructionCost X86TTIImpl::getReplicationShuffleCost(
3625     Type *EltTy, int ReplicationFactor, int VF,
3626     const APInt &DemandedReplicatedElts, TTI::TargetCostKind CostKind) {
3627   const unsigned EltTyBits = DL.getTypeSizeInBits(EltTy);
3628 
3629   auto bailout = [&]() {
3630     return BaseT::getReplicationShuffleCost(EltTy, ReplicationFactor, VF,
3631                                             DemandedReplicatedElts, CostKind);
3632   };
3633 
3634   // For now, only deal with AVX512 cases.
3635   if (!ST->hasAVX512())
3636     return bailout();
3637 
3638   switch (EltTyBits) {
3639   case 32:
3640   case 64:
3641     break; // AVX512F.
3642   case 16:
3643     if (!ST->hasBWI())
3644       return bailout();
3645     break;
3646   case 8:
3647     if (!ST->hasVBMI())
3648       return bailout();
3649     break;
3650   default:
3651     return bailout();
3652   }
3653 
3654   auto *SrcVecTy = FixedVectorType::get(EltTy, VF);
3655   int NumReplicatedElements = VF * ReplicationFactor;
3656   auto *ReplicatedVecTy = FixedVectorType::get(EltTy, NumReplicatedElements);
3657 
3658   // Legalize the types.
3659   MVT LegalSrcVecTy = TLI->getTypeLegalizationCost(DL, SrcVecTy).second;
3660   MVT LegalReplicatedVecTy =
3661       TLI->getTypeLegalizationCost(DL, ReplicatedVecTy).second;
3662 
3663   // They both should have legalized into vector types.
3664   if (!LegalSrcVecTy.isVector() || !LegalReplicatedVecTy.isVector())
3665     return bailout();
3666 
3667   assert(LegalSrcVecTy.getScalarSizeInBits() == EltTyBits &&
3668          LegalSrcVecTy.getScalarType() ==
3669              LegalReplicatedVecTy.getScalarType() &&
3670          "We expect that the legalization doesn't affect the element width, "
3671          "doesn't coalesce/split elements.");
3672 
3673   unsigned NumEltsPerReplicatedVec =
3674       LegalReplicatedVecTy.getVectorNumElements();
3675   unsigned NumReplicatedVectors =
3676       divideCeil(ReplicatedVecTy->getNumElements(), NumEltsPerReplicatedVec);
3677 
3678   auto *SingleReplicatedVecTy =
3679       FixedVectorType::get(EltTy, NumEltsPerReplicatedVec);
3680 
3681   APInt DemandedReplicatedVectors = APIntOps::ScaleBitMask(
3682       DemandedReplicatedElts.zextOrSelf(NumReplicatedVectors *
3683                                         NumEltsPerReplicatedVec),
3684       NumReplicatedVectors);
3685   unsigned NumReplicatedVectorsDemanded =
3686       DemandedReplicatedVectors.countPopulation();
3687 
3688   InstructionCost SingleShuffleCost =
3689       getShuffleCost(TTI::SK_PermuteSingleSrc, SingleReplicatedVecTy,
3690                      /*Mask=*/None, /*Index=*/0, /*SubTp=*/nullptr);
3691   return NumReplicatedVectorsDemanded * SingleShuffleCost;
3692 }
3693 
3694 InstructionCost X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
3695                                             MaybeAlign Alignment,
3696                                             unsigned AddressSpace,
3697                                             TTI::TargetCostKind CostKind,
3698                                             const Instruction *I) {
3699   // TODO: Handle other cost kinds.
3700   if (CostKind != TTI::TCK_RecipThroughput) {
3701     if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
3702       // Store instruction with index and scale costs 2 Uops.
3703       // Check the preceding GEP to identify non-const indices.
3704       if (auto *GEP = dyn_cast<GetElementPtrInst>(SI->getPointerOperand())) {
3705         if (!all_of(GEP->indices(), [](Value *V) { return isa<Constant>(V); }))
3706           return TTI::TCC_Basic * 2;
3707       }
3708     }
3709     return TTI::TCC_Basic;
3710   }
3711 
3712   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
3713          "Invalid Opcode");
3714   // Type legalization can't handle structs
3715   if (TLI->getValueType(DL, Src, true) == MVT::Other)
3716     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3717                                   CostKind);
3718 
3719   // Legalize the type.
3720   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
3721 
3722   auto *VTy = dyn_cast<FixedVectorType>(Src);
3723 
3724   // Handle the simple case of non-vectors.
3725   // NOTE: this assumes that legalization never creates vector from scalars!
3726   if (!VTy || !LT.second.isVector())
3727     // Each load/store unit costs 1.
3728     return LT.first * 1;
3729 
3730   bool IsLoad = Opcode == Instruction::Load;
3731 
3732   Type *EltTy = VTy->getElementType();
3733 
3734   const int EltTyBits = DL.getTypeSizeInBits(EltTy);
3735 
3736   InstructionCost Cost = 0;
3737 
3738   // Source of truth: how many elements were there in the original IR vector?
3739   const unsigned SrcNumElt = VTy->getNumElements();
3740 
3741   // How far have we gotten?
3742   int NumEltRemaining = SrcNumElt;
3743   // Note that we intentionally capture by-reference, NumEltRemaining changes.
3744   auto NumEltDone = [&]() { return SrcNumElt - NumEltRemaining; };
3745 
3746   const int MaxLegalOpSizeBytes = divideCeil(LT.second.getSizeInBits(), 8);
3747 
3748   // Note that even if we can store 64 bits of an XMM, we still operate on XMM.
3749   const unsigned XMMBits = 128;
3750   if (XMMBits % EltTyBits != 0)
3751     // Vector size must be a multiple of the element size. I.e. no padding.
3752     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3753                                   CostKind);
3754   const int NumEltPerXMM = XMMBits / EltTyBits;
3755 
3756   auto *XMMVecTy = FixedVectorType::get(EltTy, NumEltPerXMM);
3757 
3758   for (int CurrOpSizeBytes = MaxLegalOpSizeBytes, SubVecEltsLeft = 0;
3759        NumEltRemaining > 0; CurrOpSizeBytes /= 2) {
3760     // How many elements would a single op deal with at once?
3761     if ((8 * CurrOpSizeBytes) % EltTyBits != 0)
3762       // Vector size must be a multiple of the element size. I.e. no padding.
3763       return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3764                                     CostKind);
3765     int CurrNumEltPerOp = (8 * CurrOpSizeBytes) / EltTyBits;
3766 
3767     assert(CurrOpSizeBytes > 0 && CurrNumEltPerOp > 0 && "How'd we get here?");
3768     assert((((NumEltRemaining * EltTyBits) < (2 * 8 * CurrOpSizeBytes)) ||
3769             (CurrOpSizeBytes == MaxLegalOpSizeBytes)) &&
3770            "Unless we haven't halved the op size yet, "
3771            "we have less than two op's sized units of work left.");
3772 
3773     auto *CurrVecTy = CurrNumEltPerOp > NumEltPerXMM
3774                           ? FixedVectorType::get(EltTy, CurrNumEltPerOp)
3775                           : XMMVecTy;
3776 
3777     assert(CurrVecTy->getNumElements() % CurrNumEltPerOp == 0 &&
3778            "After halving sizes, the vector elt count is no longer a multiple "
3779            "of number of elements per operation?");
3780     auto *CoalescedVecTy =
3781         CurrNumEltPerOp == 1
3782             ? CurrVecTy
3783             : FixedVectorType::get(
3784                   IntegerType::get(Src->getContext(),
3785                                    EltTyBits * CurrNumEltPerOp),
3786                   CurrVecTy->getNumElements() / CurrNumEltPerOp);
3787     assert(DL.getTypeSizeInBits(CoalescedVecTy) ==
3788                DL.getTypeSizeInBits(CurrVecTy) &&
3789            "coalesciing elements doesn't change vector width.");
3790 
3791     while (NumEltRemaining > 0) {
3792       assert(SubVecEltsLeft >= 0 && "Subreg element count overconsumtion?");
3793 
3794       // Can we use this vector size, as per the remaining element count?
3795       // Iff the vector is naturally aligned, we can do a wide load regardless.
3796       if (NumEltRemaining < CurrNumEltPerOp &&
3797           (!IsLoad || Alignment.valueOrOne() < CurrOpSizeBytes) &&
3798           CurrOpSizeBytes != 1)
3799         break; // Try smalled vector size.
3800 
3801       bool Is0thSubVec = (NumEltDone() % LT.second.getVectorNumElements()) == 0;
3802 
3803       // If we have fully processed the previous reg, we need to replenish it.
3804       if (SubVecEltsLeft == 0) {
3805         SubVecEltsLeft += CurrVecTy->getNumElements();
3806         // And that's free only for the 0'th subvector of a legalized vector.
3807         if (!Is0thSubVec)
3808           Cost += getShuffleCost(IsLoad ? TTI::ShuffleKind::SK_InsertSubvector
3809                                         : TTI::ShuffleKind::SK_ExtractSubvector,
3810                                  VTy, None, NumEltDone(), CurrVecTy);
3811       }
3812 
3813       // While we can directly load/store ZMM, YMM, and 64-bit halves of XMM,
3814       // for smaller widths (32/16/8) we have to insert/extract them separately.
3815       // Again, it's free for the 0'th subreg (if op is 32/64 bit wide,
3816       // but let's pretend that it is also true for 16/8 bit wide ops...)
3817       if (CurrOpSizeBytes <= 32 / 8 && !Is0thSubVec) {
3818         int NumEltDoneInCurrXMM = NumEltDone() % NumEltPerXMM;
3819         assert(NumEltDoneInCurrXMM % CurrNumEltPerOp == 0 && "");
3820         int CoalescedVecEltIdx = NumEltDoneInCurrXMM / CurrNumEltPerOp;
3821         APInt DemandedElts =
3822             APInt::getBitsSet(CoalescedVecTy->getNumElements(),
3823                               CoalescedVecEltIdx, CoalescedVecEltIdx + 1);
3824         assert(DemandedElts.countPopulation() == 1 && "Inserting single value");
3825         Cost += getScalarizationOverhead(CoalescedVecTy, DemandedElts, IsLoad,
3826                                          !IsLoad);
3827       }
3828 
3829       // This isn't exactly right. We're using slow unaligned 32-byte accesses
3830       // as a proxy for a double-pumped AVX memory interface such as on
3831       // Sandybridge.
3832       if (CurrOpSizeBytes == 32 && ST->isUnalignedMem32Slow())
3833         Cost += 2;
3834       else
3835         Cost += 1;
3836 
3837       SubVecEltsLeft -= CurrNumEltPerOp;
3838       NumEltRemaining -= CurrNumEltPerOp;
3839       Alignment = commonAlignment(Alignment.valueOrOne(), CurrOpSizeBytes);
3840     }
3841   }
3842 
3843   assert(NumEltRemaining <= 0 && "Should have processed all the elements.");
3844 
3845   return Cost;
3846 }
3847 
3848 InstructionCost
3849 X86TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *SrcTy, Align Alignment,
3850                                   unsigned AddressSpace,
3851                                   TTI::TargetCostKind CostKind) {
3852   bool IsLoad = (Instruction::Load == Opcode);
3853   bool IsStore = (Instruction::Store == Opcode);
3854 
3855   auto *SrcVTy = dyn_cast<FixedVectorType>(SrcTy);
3856   if (!SrcVTy)
3857     // To calculate scalar take the regular cost, without mask
3858     return getMemoryOpCost(Opcode, SrcTy, Alignment, AddressSpace, CostKind);
3859 
3860   unsigned NumElem = SrcVTy->getNumElements();
3861   auto *MaskTy =
3862       FixedVectorType::get(Type::getInt8Ty(SrcVTy->getContext()), NumElem);
3863   if ((IsLoad && !isLegalMaskedLoad(SrcVTy, Alignment)) ||
3864       (IsStore && !isLegalMaskedStore(SrcVTy, Alignment))) {
3865     // Scalarization
3866     APInt DemandedElts = APInt::getAllOnes(NumElem);
3867     InstructionCost MaskSplitCost =
3868         getScalarizationOverhead(MaskTy, DemandedElts, false, true);
3869     InstructionCost ScalarCompareCost = getCmpSelInstrCost(
3870         Instruction::ICmp, Type::getInt8Ty(SrcVTy->getContext()), nullptr,
3871         CmpInst::BAD_ICMP_PREDICATE, CostKind);
3872     InstructionCost BranchCost = getCFInstrCost(Instruction::Br, CostKind);
3873     InstructionCost MaskCmpCost = NumElem * (BranchCost + ScalarCompareCost);
3874     InstructionCost ValueSplitCost =
3875         getScalarizationOverhead(SrcVTy, DemandedElts, IsLoad, IsStore);
3876     InstructionCost MemopCost =
3877         NumElem * BaseT::getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
3878                                          Alignment, AddressSpace, CostKind);
3879     return MemopCost + ValueSplitCost + MaskSplitCost + MaskCmpCost;
3880   }
3881 
3882   // Legalize the type.
3883   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, SrcVTy);
3884   auto VT = TLI->getValueType(DL, SrcVTy);
3885   InstructionCost Cost = 0;
3886   if (VT.isSimple() && LT.second != VT.getSimpleVT() &&
3887       LT.second.getVectorNumElements() == NumElem)
3888     // Promotion requires extend/truncate for data and a shuffle for mask.
3889     Cost += getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVTy, None, 0, nullptr) +
3890             getShuffleCost(TTI::SK_PermuteTwoSrc, MaskTy, None, 0, nullptr);
3891 
3892   else if (LT.first * LT.second.getVectorNumElements() > NumElem) {
3893     auto *NewMaskTy = FixedVectorType::get(MaskTy->getElementType(),
3894                                            LT.second.getVectorNumElements());
3895     // Expanding requires fill mask with zeroes
3896     Cost += getShuffleCost(TTI::SK_InsertSubvector, NewMaskTy, None, 0, MaskTy);
3897   }
3898 
3899   // Pre-AVX512 - each maskmov load costs 2 + store costs ~8.
3900   if (!ST->hasAVX512())
3901     return Cost + LT.first * (IsLoad ? 2 : 8);
3902 
3903   // AVX-512 masked load/store is cheapper
3904   return Cost + LT.first;
3905 }
3906 
3907 InstructionCost X86TTIImpl::getAddressComputationCost(Type *Ty,
3908                                                       ScalarEvolution *SE,
3909                                                       const SCEV *Ptr) {
3910   // Address computations in vectorized code with non-consecutive addresses will
3911   // likely result in more instructions compared to scalar code where the
3912   // computation can more often be merged into the index mode. The resulting
3913   // extra micro-ops can significantly decrease throughput.
3914   const unsigned NumVectorInstToHideOverhead = 10;
3915 
3916   // Cost modeling of Strided Access Computation is hidden by the indexing
3917   // modes of X86 regardless of the stride value. We dont believe that there
3918   // is a difference between constant strided access in gerenal and constant
3919   // strided value which is less than or equal to 64.
3920   // Even in the case of (loop invariant) stride whose value is not known at
3921   // compile time, the address computation will not incur more than one extra
3922   // ADD instruction.
3923   if (Ty->isVectorTy() && SE) {
3924     if (!BaseT::isStridedAccess(Ptr))
3925       return NumVectorInstToHideOverhead;
3926     if (!BaseT::getConstantStrideStep(SE, Ptr))
3927       return 1;
3928   }
3929 
3930   return BaseT::getAddressComputationCost(Ty, SE, Ptr);
3931 }
3932 
3933 InstructionCost
3934 X86TTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy,
3935                                        Optional<FastMathFlags> FMF,
3936                                        TTI::TargetCostKind CostKind) {
3937   if (TTI::requiresOrderedReduction(FMF))
3938     return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
3939 
3940   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
3941   // and make it as the cost.
3942 
3943   static const CostTblEntry SLMCostTblNoPairWise[] = {
3944     { ISD::FADD,  MVT::v2f64,   3 },
3945     { ISD::ADD,   MVT::v2i64,   5 },
3946   };
3947 
3948   static const CostTblEntry SSE2CostTblNoPairWise[] = {
3949     { ISD::FADD,  MVT::v2f64,   2 },
3950     { ISD::FADD,  MVT::v2f32,   2 },
3951     { ISD::FADD,  MVT::v4f32,   4 },
3952     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
3953     { ISD::ADD,   MVT::v2i32,   2 }, // FIXME: chosen to be less than v4i32
3954     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.3".
3955     { ISD::ADD,   MVT::v2i16,   2 },      // The data reported by the IACA tool is "4.3".
3956     { ISD::ADD,   MVT::v4i16,   3 },      // The data reported by the IACA tool is "4.3".
3957     { ISD::ADD,   MVT::v8i16,   4 },      // The data reported by the IACA tool is "4.3".
3958     { ISD::ADD,   MVT::v2i8,    2 },
3959     { ISD::ADD,   MVT::v4i8,    2 },
3960     { ISD::ADD,   MVT::v8i8,    2 },
3961     { ISD::ADD,   MVT::v16i8,   3 },
3962   };
3963 
3964   static const CostTblEntry AVX1CostTblNoPairWise[] = {
3965     { ISD::FADD,  MVT::v4f64,   3 },
3966     { ISD::FADD,  MVT::v4f32,   3 },
3967     { ISD::FADD,  MVT::v8f32,   4 },
3968     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
3969     { ISD::ADD,   MVT::v4i64,   3 },
3970     { ISD::ADD,   MVT::v8i32,   5 },
3971     { ISD::ADD,   MVT::v16i16,  5 },
3972     { ISD::ADD,   MVT::v32i8,   4 },
3973   };
3974 
3975   int ISD = TLI->InstructionOpcodeToISD(Opcode);
3976   assert(ISD && "Invalid opcode");
3977 
3978   // Before legalizing the type, give a chance to look up illegal narrow types
3979   // in the table.
3980   // FIXME: Is there a better way to do this?
3981   EVT VT = TLI->getValueType(DL, ValTy);
3982   if (VT.isSimple()) {
3983     MVT MTy = VT.getSimpleVT();
3984     if (ST->useSLMArithCosts())
3985       if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
3986         return Entry->Cost;
3987 
3988     if (ST->hasAVX())
3989       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
3990         return Entry->Cost;
3991 
3992     if (ST->hasSSE2())
3993       if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
3994         return Entry->Cost;
3995   }
3996 
3997   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
3998 
3999   MVT MTy = LT.second;
4000 
4001   auto *ValVTy = cast<FixedVectorType>(ValTy);
4002 
4003   // Special case: vXi8 mul reductions are performed as vXi16.
4004   if (ISD == ISD::MUL && MTy.getScalarType() == MVT::i8) {
4005     auto *WideSclTy = IntegerType::get(ValVTy->getContext(), 16);
4006     auto *WideVecTy = FixedVectorType::get(WideSclTy, ValVTy->getNumElements());
4007     return getCastInstrCost(Instruction::ZExt, WideVecTy, ValTy,
4008                             TargetTransformInfo::CastContextHint::None,
4009                             CostKind) +
4010            getArithmeticReductionCost(Opcode, WideVecTy, FMF, CostKind);
4011   }
4012 
4013   InstructionCost ArithmeticCost = 0;
4014   if (LT.first != 1 && MTy.isVector() &&
4015       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
4016     // Type needs to be split. We need LT.first - 1 arithmetic ops.
4017     auto *SingleOpTy = FixedVectorType::get(ValVTy->getElementType(),
4018                                             MTy.getVectorNumElements());
4019     ArithmeticCost = getArithmeticInstrCost(Opcode, SingleOpTy, CostKind);
4020     ArithmeticCost *= LT.first - 1;
4021   }
4022 
4023   if (ST->useSLMArithCosts())
4024     if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
4025       return ArithmeticCost + Entry->Cost;
4026 
4027   if (ST->hasAVX())
4028     if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
4029       return ArithmeticCost + Entry->Cost;
4030 
4031   if (ST->hasSSE2())
4032     if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
4033       return ArithmeticCost + Entry->Cost;
4034 
4035   // FIXME: These assume a naive kshift+binop lowering, which is probably
4036   // conservative in most cases.
4037   static const CostTblEntry AVX512BoolReduction[] = {
4038     { ISD::AND,  MVT::v2i1,   3 },
4039     { ISD::AND,  MVT::v4i1,   5 },
4040     { ISD::AND,  MVT::v8i1,   7 },
4041     { ISD::AND,  MVT::v16i1,  9 },
4042     { ISD::AND,  MVT::v32i1, 11 },
4043     { ISD::AND,  MVT::v64i1, 13 },
4044     { ISD::OR,   MVT::v2i1,   3 },
4045     { ISD::OR,   MVT::v4i1,   5 },
4046     { ISD::OR,   MVT::v8i1,   7 },
4047     { ISD::OR,   MVT::v16i1,  9 },
4048     { ISD::OR,   MVT::v32i1, 11 },
4049     { ISD::OR,   MVT::v64i1, 13 },
4050   };
4051 
4052   static const CostTblEntry AVX2BoolReduction[] = {
4053     { ISD::AND,  MVT::v16i16,  2 }, // vpmovmskb + cmp
4054     { ISD::AND,  MVT::v32i8,   2 }, // vpmovmskb + cmp
4055     { ISD::OR,   MVT::v16i16,  2 }, // vpmovmskb + cmp
4056     { ISD::OR,   MVT::v32i8,   2 }, // vpmovmskb + cmp
4057   };
4058 
4059   static const CostTblEntry AVX1BoolReduction[] = {
4060     { ISD::AND,  MVT::v4i64,   2 }, // vmovmskpd + cmp
4061     { ISD::AND,  MVT::v8i32,   2 }, // vmovmskps + cmp
4062     { ISD::AND,  MVT::v16i16,  4 }, // vextractf128 + vpand + vpmovmskb + cmp
4063     { ISD::AND,  MVT::v32i8,   4 }, // vextractf128 + vpand + vpmovmskb + cmp
4064     { ISD::OR,   MVT::v4i64,   2 }, // vmovmskpd + cmp
4065     { ISD::OR,   MVT::v8i32,   2 }, // vmovmskps + cmp
4066     { ISD::OR,   MVT::v16i16,  4 }, // vextractf128 + vpor + vpmovmskb + cmp
4067     { ISD::OR,   MVT::v32i8,   4 }, // vextractf128 + vpor + vpmovmskb + cmp
4068   };
4069 
4070   static const CostTblEntry SSE2BoolReduction[] = {
4071     { ISD::AND,  MVT::v2i64,   2 }, // movmskpd + cmp
4072     { ISD::AND,  MVT::v4i32,   2 }, // movmskps + cmp
4073     { ISD::AND,  MVT::v8i16,   2 }, // pmovmskb + cmp
4074     { ISD::AND,  MVT::v16i8,   2 }, // pmovmskb + cmp
4075     { ISD::OR,   MVT::v2i64,   2 }, // movmskpd + cmp
4076     { ISD::OR,   MVT::v4i32,   2 }, // movmskps + cmp
4077     { ISD::OR,   MVT::v8i16,   2 }, // pmovmskb + cmp
4078     { ISD::OR,   MVT::v16i8,   2 }, // pmovmskb + cmp
4079   };
4080 
4081   // Handle bool allof/anyof patterns.
4082   if (ValVTy->getElementType()->isIntegerTy(1)) {
4083     InstructionCost ArithmeticCost = 0;
4084     if (LT.first != 1 && MTy.isVector() &&
4085         MTy.getVectorNumElements() < ValVTy->getNumElements()) {
4086       // Type needs to be split. We need LT.first - 1 arithmetic ops.
4087       auto *SingleOpTy = FixedVectorType::get(ValVTy->getElementType(),
4088                                               MTy.getVectorNumElements());
4089       ArithmeticCost = getArithmeticInstrCost(Opcode, SingleOpTy, CostKind);
4090       ArithmeticCost *= LT.first - 1;
4091     }
4092 
4093     if (ST->hasAVX512())
4094       if (const auto *Entry = CostTableLookup(AVX512BoolReduction, ISD, MTy))
4095         return ArithmeticCost + Entry->Cost;
4096     if (ST->hasAVX2())
4097       if (const auto *Entry = CostTableLookup(AVX2BoolReduction, ISD, MTy))
4098         return ArithmeticCost + Entry->Cost;
4099     if (ST->hasAVX())
4100       if (const auto *Entry = CostTableLookup(AVX1BoolReduction, ISD, MTy))
4101         return ArithmeticCost + Entry->Cost;
4102     if (ST->hasSSE2())
4103       if (const auto *Entry = CostTableLookup(SSE2BoolReduction, ISD, MTy))
4104         return ArithmeticCost + Entry->Cost;
4105 
4106     return BaseT::getArithmeticReductionCost(Opcode, ValVTy, FMF, CostKind);
4107   }
4108 
4109   unsigned NumVecElts = ValVTy->getNumElements();
4110   unsigned ScalarSize = ValVTy->getScalarSizeInBits();
4111 
4112   // Special case power of 2 reductions where the scalar type isn't changed
4113   // by type legalization.
4114   if (!isPowerOf2_32(NumVecElts) || ScalarSize != MTy.getScalarSizeInBits())
4115     return BaseT::getArithmeticReductionCost(Opcode, ValVTy, FMF, CostKind);
4116 
4117   InstructionCost ReductionCost = 0;
4118 
4119   auto *Ty = ValVTy;
4120   if (LT.first != 1 && MTy.isVector() &&
4121       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
4122     // Type needs to be split. We need LT.first - 1 arithmetic ops.
4123     Ty = FixedVectorType::get(ValVTy->getElementType(),
4124                               MTy.getVectorNumElements());
4125     ReductionCost = getArithmeticInstrCost(Opcode, Ty, CostKind);
4126     ReductionCost *= LT.first - 1;
4127     NumVecElts = MTy.getVectorNumElements();
4128   }
4129 
4130   // Now handle reduction with the legal type, taking into account size changes
4131   // at each level.
4132   while (NumVecElts > 1) {
4133     // Determine the size of the remaining vector we need to reduce.
4134     unsigned Size = NumVecElts * ScalarSize;
4135     NumVecElts /= 2;
4136     // If we're reducing from 256/512 bits, use an extract_subvector.
4137     if (Size > 128) {
4138       auto *SubTy = FixedVectorType::get(ValVTy->getElementType(), NumVecElts);
4139       ReductionCost +=
4140           getShuffleCost(TTI::SK_ExtractSubvector, Ty, None, NumVecElts, SubTy);
4141       Ty = SubTy;
4142     } else if (Size == 128) {
4143       // Reducing from 128 bits is a permute of v2f64/v2i64.
4144       FixedVectorType *ShufTy;
4145       if (ValVTy->isFloatingPointTy())
4146         ShufTy =
4147             FixedVectorType::get(Type::getDoubleTy(ValVTy->getContext()), 2);
4148       else
4149         ShufTy =
4150             FixedVectorType::get(Type::getInt64Ty(ValVTy->getContext()), 2);
4151       ReductionCost +=
4152           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4153     } else if (Size == 64) {
4154       // Reducing from 64 bits is a shuffle of v4f32/v4i32.
4155       FixedVectorType *ShufTy;
4156       if (ValVTy->isFloatingPointTy())
4157         ShufTy =
4158             FixedVectorType::get(Type::getFloatTy(ValVTy->getContext()), 4);
4159       else
4160         ShufTy =
4161             FixedVectorType::get(Type::getInt32Ty(ValVTy->getContext()), 4);
4162       ReductionCost +=
4163           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4164     } else {
4165       // Reducing from smaller size is a shift by immediate.
4166       auto *ShiftTy = FixedVectorType::get(
4167           Type::getIntNTy(ValVTy->getContext(), Size), 128 / Size);
4168       ReductionCost += getArithmeticInstrCost(
4169           Instruction::LShr, ShiftTy, CostKind,
4170           TargetTransformInfo::OK_AnyValue,
4171           TargetTransformInfo::OK_UniformConstantValue,
4172           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
4173     }
4174 
4175     // Add the arithmetic op for this level.
4176     ReductionCost += getArithmeticInstrCost(Opcode, Ty, CostKind);
4177   }
4178 
4179   // Add the final extract element to the cost.
4180   return ReductionCost + getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
4181 }
4182 
4183 InstructionCost X86TTIImpl::getMinMaxCost(Type *Ty, Type *CondTy,
4184                                           bool IsUnsigned) {
4185   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
4186 
4187   MVT MTy = LT.second;
4188 
4189   int ISD;
4190   if (Ty->isIntOrIntVectorTy()) {
4191     ISD = IsUnsigned ? ISD::UMIN : ISD::SMIN;
4192   } else {
4193     assert(Ty->isFPOrFPVectorTy() &&
4194            "Expected float point or integer vector type.");
4195     ISD = ISD::FMINNUM;
4196   }
4197 
4198   static const CostTblEntry SSE1CostTbl[] = {
4199     {ISD::FMINNUM, MVT::v4f32, 1},
4200   };
4201 
4202   static const CostTblEntry SSE2CostTbl[] = {
4203     {ISD::FMINNUM, MVT::v2f64, 1},
4204     {ISD::SMIN,    MVT::v8i16, 1},
4205     {ISD::UMIN,    MVT::v16i8, 1},
4206   };
4207 
4208   static const CostTblEntry SSE41CostTbl[] = {
4209     {ISD::SMIN,    MVT::v4i32, 1},
4210     {ISD::UMIN,    MVT::v4i32, 1},
4211     {ISD::UMIN,    MVT::v8i16, 1},
4212     {ISD::SMIN,    MVT::v16i8, 1},
4213   };
4214 
4215   static const CostTblEntry SSE42CostTbl[] = {
4216     {ISD::UMIN,    MVT::v2i64, 3}, // xor+pcmpgtq+blendvpd
4217   };
4218 
4219   static const CostTblEntry AVX1CostTbl[] = {
4220     {ISD::FMINNUM, MVT::v8f32,  1},
4221     {ISD::FMINNUM, MVT::v4f64,  1},
4222     {ISD::SMIN,    MVT::v8i32,  3},
4223     {ISD::UMIN,    MVT::v8i32,  3},
4224     {ISD::SMIN,    MVT::v16i16, 3},
4225     {ISD::UMIN,    MVT::v16i16, 3},
4226     {ISD::SMIN,    MVT::v32i8,  3},
4227     {ISD::UMIN,    MVT::v32i8,  3},
4228   };
4229 
4230   static const CostTblEntry AVX2CostTbl[] = {
4231     {ISD::SMIN,    MVT::v8i32,  1},
4232     {ISD::UMIN,    MVT::v8i32,  1},
4233     {ISD::SMIN,    MVT::v16i16, 1},
4234     {ISD::UMIN,    MVT::v16i16, 1},
4235     {ISD::SMIN,    MVT::v32i8,  1},
4236     {ISD::UMIN,    MVT::v32i8,  1},
4237   };
4238 
4239   static const CostTblEntry AVX512CostTbl[] = {
4240     {ISD::FMINNUM, MVT::v16f32, 1},
4241     {ISD::FMINNUM, MVT::v8f64,  1},
4242     {ISD::SMIN,    MVT::v2i64,  1},
4243     {ISD::UMIN,    MVT::v2i64,  1},
4244     {ISD::SMIN,    MVT::v4i64,  1},
4245     {ISD::UMIN,    MVT::v4i64,  1},
4246     {ISD::SMIN,    MVT::v8i64,  1},
4247     {ISD::UMIN,    MVT::v8i64,  1},
4248     {ISD::SMIN,    MVT::v16i32, 1},
4249     {ISD::UMIN,    MVT::v16i32, 1},
4250   };
4251 
4252   static const CostTblEntry AVX512BWCostTbl[] = {
4253     {ISD::SMIN,    MVT::v32i16, 1},
4254     {ISD::UMIN,    MVT::v32i16, 1},
4255     {ISD::SMIN,    MVT::v64i8,  1},
4256     {ISD::UMIN,    MVT::v64i8,  1},
4257   };
4258 
4259   // If we have a native MIN/MAX instruction for this type, use it.
4260   if (ST->hasBWI())
4261     if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
4262       return LT.first * Entry->Cost;
4263 
4264   if (ST->hasAVX512())
4265     if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
4266       return LT.first * Entry->Cost;
4267 
4268   if (ST->hasAVX2())
4269     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
4270       return LT.first * Entry->Cost;
4271 
4272   if (ST->hasAVX())
4273     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
4274       return LT.first * Entry->Cost;
4275 
4276   if (ST->hasSSE42())
4277     if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
4278       return LT.first * Entry->Cost;
4279 
4280   if (ST->hasSSE41())
4281     if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
4282       return LT.first * Entry->Cost;
4283 
4284   if (ST->hasSSE2())
4285     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
4286       return LT.first * Entry->Cost;
4287 
4288   if (ST->hasSSE1())
4289     if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
4290       return LT.first * Entry->Cost;
4291 
4292   unsigned CmpOpcode;
4293   if (Ty->isFPOrFPVectorTy()) {
4294     CmpOpcode = Instruction::FCmp;
4295   } else {
4296     assert(Ty->isIntOrIntVectorTy() &&
4297            "expecting floating point or integer type for min/max reduction");
4298     CmpOpcode = Instruction::ICmp;
4299   }
4300 
4301   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4302   // Otherwise fall back to cmp+select.
4303   InstructionCost Result =
4304       getCmpSelInstrCost(CmpOpcode, Ty, CondTy, CmpInst::BAD_ICMP_PREDICATE,
4305                          CostKind) +
4306       getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
4307                          CmpInst::BAD_ICMP_PREDICATE, CostKind);
4308   return Result;
4309 }
4310 
4311 InstructionCost
4312 X86TTIImpl::getMinMaxReductionCost(VectorType *ValTy, VectorType *CondTy,
4313                                    bool IsUnsigned,
4314                                    TTI::TargetCostKind CostKind) {
4315   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
4316 
4317   MVT MTy = LT.second;
4318 
4319   int ISD;
4320   if (ValTy->isIntOrIntVectorTy()) {
4321     ISD = IsUnsigned ? ISD::UMIN : ISD::SMIN;
4322   } else {
4323     assert(ValTy->isFPOrFPVectorTy() &&
4324            "Expected float point or integer vector type.");
4325     ISD = ISD::FMINNUM;
4326   }
4327 
4328   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
4329   // and make it as the cost.
4330 
4331   static const CostTblEntry SSE2CostTblNoPairWise[] = {
4332       {ISD::UMIN, MVT::v2i16, 5}, // need pxors to use pminsw/pmaxsw
4333       {ISD::UMIN, MVT::v4i16, 7}, // need pxors to use pminsw/pmaxsw
4334       {ISD::UMIN, MVT::v8i16, 9}, // need pxors to use pminsw/pmaxsw
4335   };
4336 
4337   static const CostTblEntry SSE41CostTblNoPairWise[] = {
4338       {ISD::SMIN, MVT::v2i16, 3}, // same as sse2
4339       {ISD::SMIN, MVT::v4i16, 5}, // same as sse2
4340       {ISD::UMIN, MVT::v2i16, 5}, // same as sse2
4341       {ISD::UMIN, MVT::v4i16, 7}, // same as sse2
4342       {ISD::SMIN, MVT::v8i16, 4}, // phminposuw+xor
4343       {ISD::UMIN, MVT::v8i16, 4}, // FIXME: umin is cheaper than umax
4344       {ISD::SMIN, MVT::v2i8,  3}, // pminsb
4345       {ISD::SMIN, MVT::v4i8,  5}, // pminsb
4346       {ISD::SMIN, MVT::v8i8,  7}, // pminsb
4347       {ISD::SMIN, MVT::v16i8, 6},
4348       {ISD::UMIN, MVT::v2i8,  3}, // same as sse2
4349       {ISD::UMIN, MVT::v4i8,  5}, // same as sse2
4350       {ISD::UMIN, MVT::v8i8,  7}, // same as sse2
4351       {ISD::UMIN, MVT::v16i8, 6}, // FIXME: umin is cheaper than umax
4352   };
4353 
4354   static const CostTblEntry AVX1CostTblNoPairWise[] = {
4355       {ISD::SMIN, MVT::v16i16, 6},
4356       {ISD::UMIN, MVT::v16i16, 6}, // FIXME: umin is cheaper than umax
4357       {ISD::SMIN, MVT::v32i8, 8},
4358       {ISD::UMIN, MVT::v32i8, 8},
4359   };
4360 
4361   static const CostTblEntry AVX512BWCostTblNoPairWise[] = {
4362       {ISD::SMIN, MVT::v32i16, 8},
4363       {ISD::UMIN, MVT::v32i16, 8}, // FIXME: umin is cheaper than umax
4364       {ISD::SMIN, MVT::v64i8, 10},
4365       {ISD::UMIN, MVT::v64i8, 10},
4366   };
4367 
4368   // Before legalizing the type, give a chance to look up illegal narrow types
4369   // in the table.
4370   // FIXME: Is there a better way to do this?
4371   EVT VT = TLI->getValueType(DL, ValTy);
4372   if (VT.isSimple()) {
4373     MVT MTy = VT.getSimpleVT();
4374     if (ST->hasBWI())
4375       if (const auto *Entry = CostTableLookup(AVX512BWCostTblNoPairWise, ISD, MTy))
4376         return Entry->Cost;
4377 
4378     if (ST->hasAVX())
4379       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
4380         return Entry->Cost;
4381 
4382     if (ST->hasSSE41())
4383       if (const auto *Entry = CostTableLookup(SSE41CostTblNoPairWise, ISD, MTy))
4384         return Entry->Cost;
4385 
4386     if (ST->hasSSE2())
4387       if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
4388         return Entry->Cost;
4389   }
4390 
4391   auto *ValVTy = cast<FixedVectorType>(ValTy);
4392   unsigned NumVecElts = ValVTy->getNumElements();
4393 
4394   auto *Ty = ValVTy;
4395   InstructionCost MinMaxCost = 0;
4396   if (LT.first != 1 && MTy.isVector() &&
4397       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
4398     // Type needs to be split. We need LT.first - 1 operations ops.
4399     Ty = FixedVectorType::get(ValVTy->getElementType(),
4400                               MTy.getVectorNumElements());
4401     auto *SubCondTy = FixedVectorType::get(CondTy->getElementType(),
4402                                            MTy.getVectorNumElements());
4403     MinMaxCost = getMinMaxCost(Ty, SubCondTy, IsUnsigned);
4404     MinMaxCost *= LT.first - 1;
4405     NumVecElts = MTy.getVectorNumElements();
4406   }
4407 
4408   if (ST->hasBWI())
4409     if (const auto *Entry = CostTableLookup(AVX512BWCostTblNoPairWise, ISD, MTy))
4410       return MinMaxCost + Entry->Cost;
4411 
4412   if (ST->hasAVX())
4413     if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
4414       return MinMaxCost + Entry->Cost;
4415 
4416   if (ST->hasSSE41())
4417     if (const auto *Entry = CostTableLookup(SSE41CostTblNoPairWise, ISD, MTy))
4418       return MinMaxCost + Entry->Cost;
4419 
4420   if (ST->hasSSE2())
4421     if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
4422       return MinMaxCost + Entry->Cost;
4423 
4424   unsigned ScalarSize = ValTy->getScalarSizeInBits();
4425 
4426   // Special case power of 2 reductions where the scalar type isn't changed
4427   // by type legalization.
4428   if (!isPowerOf2_32(ValVTy->getNumElements()) ||
4429       ScalarSize != MTy.getScalarSizeInBits())
4430     return BaseT::getMinMaxReductionCost(ValTy, CondTy, IsUnsigned, CostKind);
4431 
4432   // Now handle reduction with the legal type, taking into account size changes
4433   // at each level.
4434   while (NumVecElts > 1) {
4435     // Determine the size of the remaining vector we need to reduce.
4436     unsigned Size = NumVecElts * ScalarSize;
4437     NumVecElts /= 2;
4438     // If we're reducing from 256/512 bits, use an extract_subvector.
4439     if (Size > 128) {
4440       auto *SubTy = FixedVectorType::get(ValVTy->getElementType(), NumVecElts);
4441       MinMaxCost +=
4442           getShuffleCost(TTI::SK_ExtractSubvector, Ty, None, NumVecElts, SubTy);
4443       Ty = SubTy;
4444     } else if (Size == 128) {
4445       // Reducing from 128 bits is a permute of v2f64/v2i64.
4446       VectorType *ShufTy;
4447       if (ValTy->isFloatingPointTy())
4448         ShufTy =
4449             FixedVectorType::get(Type::getDoubleTy(ValTy->getContext()), 2);
4450       else
4451         ShufTy = FixedVectorType::get(Type::getInt64Ty(ValTy->getContext()), 2);
4452       MinMaxCost +=
4453           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4454     } else if (Size == 64) {
4455       // Reducing from 64 bits is a shuffle of v4f32/v4i32.
4456       FixedVectorType *ShufTy;
4457       if (ValTy->isFloatingPointTy())
4458         ShufTy = FixedVectorType::get(Type::getFloatTy(ValTy->getContext()), 4);
4459       else
4460         ShufTy = FixedVectorType::get(Type::getInt32Ty(ValTy->getContext()), 4);
4461       MinMaxCost +=
4462           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4463     } else {
4464       // Reducing from smaller size is a shift by immediate.
4465       auto *ShiftTy = FixedVectorType::get(
4466           Type::getIntNTy(ValTy->getContext(), Size), 128 / Size);
4467       MinMaxCost += getArithmeticInstrCost(
4468           Instruction::LShr, ShiftTy, TTI::TCK_RecipThroughput,
4469           TargetTransformInfo::OK_AnyValue,
4470           TargetTransformInfo::OK_UniformConstantValue,
4471           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
4472     }
4473 
4474     // Add the arithmetic op for this level.
4475     auto *SubCondTy =
4476         FixedVectorType::get(CondTy->getElementType(), Ty->getNumElements());
4477     MinMaxCost += getMinMaxCost(Ty, SubCondTy, IsUnsigned);
4478   }
4479 
4480   // Add the final extract element to the cost.
4481   return MinMaxCost + getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
4482 }
4483 
4484 /// Calculate the cost of materializing a 64-bit value. This helper
4485 /// method might only calculate a fraction of a larger immediate. Therefore it
4486 /// is valid to return a cost of ZERO.
4487 InstructionCost X86TTIImpl::getIntImmCost(int64_t Val) {
4488   if (Val == 0)
4489     return TTI::TCC_Free;
4490 
4491   if (isInt<32>(Val))
4492     return TTI::TCC_Basic;
4493 
4494   return 2 * TTI::TCC_Basic;
4495 }
4496 
4497 InstructionCost X86TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
4498                                           TTI::TargetCostKind CostKind) {
4499   assert(Ty->isIntegerTy());
4500 
4501   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4502   if (BitSize == 0)
4503     return ~0U;
4504 
4505   // Never hoist constants larger than 128bit, because this might lead to
4506   // incorrect code generation or assertions in codegen.
4507   // Fixme: Create a cost model for types larger than i128 once the codegen
4508   // issues have been fixed.
4509   if (BitSize > 128)
4510     return TTI::TCC_Free;
4511 
4512   if (Imm == 0)
4513     return TTI::TCC_Free;
4514 
4515   // Sign-extend all constants to a multiple of 64-bit.
4516   APInt ImmVal = Imm;
4517   if (BitSize % 64 != 0)
4518     ImmVal = Imm.sext(alignTo(BitSize, 64));
4519 
4520   // Split the constant into 64-bit chunks and calculate the cost for each
4521   // chunk.
4522   InstructionCost Cost = 0;
4523   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
4524     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
4525     int64_t Val = Tmp.getSExtValue();
4526     Cost += getIntImmCost(Val);
4527   }
4528   // We need at least one instruction to materialize the constant.
4529   return std::max<InstructionCost>(1, Cost);
4530 }
4531 
4532 InstructionCost X86TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
4533                                               const APInt &Imm, Type *Ty,
4534                                               TTI::TargetCostKind CostKind,
4535                                               Instruction *Inst) {
4536   assert(Ty->isIntegerTy());
4537 
4538   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4539   // There is no cost model for constants with a bit size of 0. Return TCC_Free
4540   // here, so that constant hoisting will ignore this constant.
4541   if (BitSize == 0)
4542     return TTI::TCC_Free;
4543 
4544   unsigned ImmIdx = ~0U;
4545   switch (Opcode) {
4546   default:
4547     return TTI::TCC_Free;
4548   case Instruction::GetElementPtr:
4549     // Always hoist the base address of a GetElementPtr. This prevents the
4550     // creation of new constants for every base constant that gets constant
4551     // folded with the offset.
4552     if (Idx == 0)
4553       return 2 * TTI::TCC_Basic;
4554     return TTI::TCC_Free;
4555   case Instruction::Store:
4556     ImmIdx = 0;
4557     break;
4558   case Instruction::ICmp:
4559     // This is an imperfect hack to prevent constant hoisting of
4560     // compares that might be trying to check if a 64-bit value fits in
4561     // 32-bits. The backend can optimize these cases using a right shift by 32.
4562     // Ideally we would check the compare predicate here. There also other
4563     // similar immediates the backend can use shifts for.
4564     if (Idx == 1 && Imm.getBitWidth() == 64) {
4565       uint64_t ImmVal = Imm.getZExtValue();
4566       if (ImmVal == 0x100000000ULL || ImmVal == 0xffffffff)
4567         return TTI::TCC_Free;
4568     }
4569     ImmIdx = 1;
4570     break;
4571   case Instruction::And:
4572     // We support 64-bit ANDs with immediates with 32-bits of leading zeroes
4573     // by using a 32-bit operation with implicit zero extension. Detect such
4574     // immediates here as the normal path expects bit 31 to be sign extended.
4575     if (Idx == 1 && Imm.getBitWidth() == 64 && isUInt<32>(Imm.getZExtValue()))
4576       return TTI::TCC_Free;
4577     ImmIdx = 1;
4578     break;
4579   case Instruction::Add:
4580   case Instruction::Sub:
4581     // For add/sub, we can use the opposite instruction for INT32_MIN.
4582     if (Idx == 1 && Imm.getBitWidth() == 64 && Imm.getZExtValue() == 0x80000000)
4583       return TTI::TCC_Free;
4584     ImmIdx = 1;
4585     break;
4586   case Instruction::UDiv:
4587   case Instruction::SDiv:
4588   case Instruction::URem:
4589   case Instruction::SRem:
4590     // Division by constant is typically expanded later into a different
4591     // instruction sequence. This completely changes the constants.
4592     // Report them as "free" to stop ConstantHoist from marking them as opaque.
4593     return TTI::TCC_Free;
4594   case Instruction::Mul:
4595   case Instruction::Or:
4596   case Instruction::Xor:
4597     ImmIdx = 1;
4598     break;
4599   // Always return TCC_Free for the shift value of a shift instruction.
4600   case Instruction::Shl:
4601   case Instruction::LShr:
4602   case Instruction::AShr:
4603     if (Idx == 1)
4604       return TTI::TCC_Free;
4605     break;
4606   case Instruction::Trunc:
4607   case Instruction::ZExt:
4608   case Instruction::SExt:
4609   case Instruction::IntToPtr:
4610   case Instruction::PtrToInt:
4611   case Instruction::BitCast:
4612   case Instruction::PHI:
4613   case Instruction::Call:
4614   case Instruction::Select:
4615   case Instruction::Ret:
4616   case Instruction::Load:
4617     break;
4618   }
4619 
4620   if (Idx == ImmIdx) {
4621     int NumConstants = divideCeil(BitSize, 64);
4622     InstructionCost Cost = X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4623     return (Cost <= NumConstants * TTI::TCC_Basic)
4624                ? static_cast<int>(TTI::TCC_Free)
4625                : Cost;
4626   }
4627 
4628   return X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4629 }
4630 
4631 InstructionCost X86TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
4632                                                 const APInt &Imm, Type *Ty,
4633                                                 TTI::TargetCostKind CostKind) {
4634   assert(Ty->isIntegerTy());
4635 
4636   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4637   // There is no cost model for constants with a bit size of 0. Return TCC_Free
4638   // here, so that constant hoisting will ignore this constant.
4639   if (BitSize == 0)
4640     return TTI::TCC_Free;
4641 
4642   switch (IID) {
4643   default:
4644     return TTI::TCC_Free;
4645   case Intrinsic::sadd_with_overflow:
4646   case Intrinsic::uadd_with_overflow:
4647   case Intrinsic::ssub_with_overflow:
4648   case Intrinsic::usub_with_overflow:
4649   case Intrinsic::smul_with_overflow:
4650   case Intrinsic::umul_with_overflow:
4651     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<32>(Imm.getSExtValue()))
4652       return TTI::TCC_Free;
4653     break;
4654   case Intrinsic::experimental_stackmap:
4655     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
4656       return TTI::TCC_Free;
4657     break;
4658   case Intrinsic::experimental_patchpoint_void:
4659   case Intrinsic::experimental_patchpoint_i64:
4660     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
4661       return TTI::TCC_Free;
4662     break;
4663   }
4664   return X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4665 }
4666 
4667 InstructionCost X86TTIImpl::getCFInstrCost(unsigned Opcode,
4668                                            TTI::TargetCostKind CostKind,
4669                                            const Instruction *I) {
4670   if (CostKind != TTI::TCK_RecipThroughput)
4671     return Opcode == Instruction::PHI ? 0 : 1;
4672   // Branches are assumed to be predicted.
4673   return 0;
4674 }
4675 
4676 int X86TTIImpl::getGatherOverhead() const {
4677   // Some CPUs have more overhead for gather. The specified overhead is relative
4678   // to the Load operation. "2" is the number provided by Intel architects. This
4679   // parameter is used for cost estimation of Gather Op and comparison with
4680   // other alternatives.
4681   // TODO: Remove the explicit hasAVX512()?, That would mean we would only
4682   // enable gather with a -march.
4683   if (ST->hasAVX512() || (ST->hasAVX2() && ST->hasFastGather()))
4684     return 2;
4685 
4686   return 1024;
4687 }
4688 
4689 int X86TTIImpl::getScatterOverhead() const {
4690   if (ST->hasAVX512())
4691     return 2;
4692 
4693   return 1024;
4694 }
4695 
4696 // Return an average cost of Gather / Scatter instruction, maybe improved later.
4697 // FIXME: Add TargetCostKind support.
4698 InstructionCost X86TTIImpl::getGSVectorCost(unsigned Opcode, Type *SrcVTy,
4699                                             const Value *Ptr, Align Alignment,
4700                                             unsigned AddressSpace) {
4701 
4702   assert(isa<VectorType>(SrcVTy) && "Unexpected type in getGSVectorCost");
4703   unsigned VF = cast<FixedVectorType>(SrcVTy)->getNumElements();
4704 
4705   // Try to reduce index size from 64 bit (default for GEP)
4706   // to 32. It is essential for VF 16. If the index can't be reduced to 32, the
4707   // operation will use 16 x 64 indices which do not fit in a zmm and needs
4708   // to split. Also check that the base pointer is the same for all lanes,
4709   // and that there's at most one variable index.
4710   auto getIndexSizeInBits = [](const Value *Ptr, const DataLayout &DL) {
4711     unsigned IndexSize = DL.getPointerSizeInBits();
4712     const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4713     if (IndexSize < 64 || !GEP)
4714       return IndexSize;
4715 
4716     unsigned NumOfVarIndices = 0;
4717     const Value *Ptrs = GEP->getPointerOperand();
4718     if (Ptrs->getType()->isVectorTy() && !getSplatValue(Ptrs))
4719       return IndexSize;
4720     for (unsigned i = 1; i < GEP->getNumOperands(); ++i) {
4721       if (isa<Constant>(GEP->getOperand(i)))
4722         continue;
4723       Type *IndxTy = GEP->getOperand(i)->getType();
4724       if (auto *IndexVTy = dyn_cast<VectorType>(IndxTy))
4725         IndxTy = IndexVTy->getElementType();
4726       if ((IndxTy->getPrimitiveSizeInBits() == 64 &&
4727           !isa<SExtInst>(GEP->getOperand(i))) ||
4728          ++NumOfVarIndices > 1)
4729         return IndexSize; // 64
4730     }
4731     return (unsigned)32;
4732   };
4733 
4734   // Trying to reduce IndexSize to 32 bits for vector 16.
4735   // By default the IndexSize is equal to pointer size.
4736   unsigned IndexSize = (ST->hasAVX512() && VF >= 16)
4737                            ? getIndexSizeInBits(Ptr, DL)
4738                            : DL.getPointerSizeInBits();
4739 
4740   auto *IndexVTy = FixedVectorType::get(
4741       IntegerType::get(SrcVTy->getContext(), IndexSize), VF);
4742   std::pair<InstructionCost, MVT> IdxsLT =
4743       TLI->getTypeLegalizationCost(DL, IndexVTy);
4744   std::pair<InstructionCost, MVT> SrcLT =
4745       TLI->getTypeLegalizationCost(DL, SrcVTy);
4746   InstructionCost::CostType SplitFactor =
4747       *std::max(IdxsLT.first, SrcLT.first).getValue();
4748   if (SplitFactor > 1) {
4749     // Handle splitting of vector of pointers
4750     auto *SplitSrcTy =
4751         FixedVectorType::get(SrcVTy->getScalarType(), VF / SplitFactor);
4752     return SplitFactor * getGSVectorCost(Opcode, SplitSrcTy, Ptr, Alignment,
4753                                          AddressSpace);
4754   }
4755 
4756   // The gather / scatter cost is given by Intel architects. It is a rough
4757   // number since we are looking at one instruction in a time.
4758   const int GSOverhead = (Opcode == Instruction::Load)
4759                              ? getGatherOverhead()
4760                              : getScatterOverhead();
4761   return GSOverhead + VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
4762                                            MaybeAlign(Alignment), AddressSpace,
4763                                            TTI::TCK_RecipThroughput);
4764 }
4765 
4766 /// Return the cost of full scalarization of gather / scatter operation.
4767 ///
4768 /// Opcode - Load or Store instruction.
4769 /// SrcVTy - The type of the data vector that should be gathered or scattered.
4770 /// VariableMask - The mask is non-constant at compile time.
4771 /// Alignment - Alignment for one element.
4772 /// AddressSpace - pointer[s] address space.
4773 ///
4774 /// FIXME: Add TargetCostKind support.
4775 InstructionCost X86TTIImpl::getGSScalarCost(unsigned Opcode, Type *SrcVTy,
4776                                             bool VariableMask, Align Alignment,
4777                                             unsigned AddressSpace) {
4778   Type *ScalarTy = SrcVTy->getScalarType();
4779   unsigned VF = cast<FixedVectorType>(SrcVTy)->getNumElements();
4780   APInt DemandedElts = APInt::getAllOnes(VF);
4781   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4782 
4783   InstructionCost MaskUnpackCost = 0;
4784   if (VariableMask) {
4785     auto *MaskTy =
4786         FixedVectorType::get(Type::getInt1Ty(SrcVTy->getContext()), VF);
4787     MaskUnpackCost = getScalarizationOverhead(
4788         MaskTy, DemandedElts, /*Insert=*/false, /*Extract=*/true);
4789     InstructionCost ScalarCompareCost = getCmpSelInstrCost(
4790         Instruction::ICmp, Type::getInt1Ty(SrcVTy->getContext()), nullptr,
4791         CmpInst::BAD_ICMP_PREDICATE, CostKind);
4792     InstructionCost BranchCost = getCFInstrCost(Instruction::Br, CostKind);
4793     MaskUnpackCost += VF * (BranchCost + ScalarCompareCost);
4794   }
4795 
4796   InstructionCost AddressUnpackCost = getScalarizationOverhead(
4797       FixedVectorType::get(ScalarTy->getPointerTo(), VF), DemandedElts,
4798       /*Insert=*/false, /*Extract=*/true);
4799 
4800   // The cost of the scalar loads/stores.
4801   InstructionCost MemoryOpCost =
4802       VF * getMemoryOpCost(Opcode, ScalarTy, MaybeAlign(Alignment),
4803                            AddressSpace, CostKind);
4804 
4805   // The cost of forming the vector from loaded scalars/
4806   // scalarizing the vector to perform scalar stores.
4807   InstructionCost InsertExtractCost =
4808       getScalarizationOverhead(cast<FixedVectorType>(SrcVTy), DemandedElts,
4809                                /*Insert=*/Opcode == Instruction::Load,
4810                                /*Extract=*/Opcode == Instruction::Store);
4811 
4812   return AddressUnpackCost + MemoryOpCost + MaskUnpackCost + InsertExtractCost;
4813 }
4814 
4815 /// Calculate the cost of Gather / Scatter operation
4816 InstructionCost X86TTIImpl::getGatherScatterOpCost(
4817     unsigned Opcode, Type *SrcVTy, const Value *Ptr, bool VariableMask,
4818     Align Alignment, TTI::TargetCostKind CostKind,
4819     const Instruction *I = nullptr) {
4820   if (CostKind != TTI::TCK_RecipThroughput) {
4821     if ((Opcode == Instruction::Load &&
4822          isLegalMaskedGather(SrcVTy, Align(Alignment))) ||
4823         (Opcode == Instruction::Store &&
4824          isLegalMaskedScatter(SrcVTy, Align(Alignment))))
4825       return 1;
4826     return BaseT::getGatherScatterOpCost(Opcode, SrcVTy, Ptr, VariableMask,
4827                                          Alignment, CostKind, I);
4828   }
4829 
4830   assert(SrcVTy->isVectorTy() && "Unexpected data type for Gather/Scatter");
4831   PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4832   if (!PtrTy && Ptr->getType()->isVectorTy())
4833     PtrTy = dyn_cast<PointerType>(
4834         cast<VectorType>(Ptr->getType())->getElementType());
4835   assert(PtrTy && "Unexpected type for Ptr argument");
4836   unsigned AddressSpace = PtrTy->getAddressSpace();
4837 
4838   if ((Opcode == Instruction::Load &&
4839        !isLegalMaskedGather(SrcVTy, Align(Alignment))) ||
4840       (Opcode == Instruction::Store &&
4841        !isLegalMaskedScatter(SrcVTy, Align(Alignment))))
4842     return getGSScalarCost(Opcode, SrcVTy, VariableMask, Alignment,
4843                            AddressSpace);
4844 
4845   return getGSVectorCost(Opcode, SrcVTy, Ptr, Alignment, AddressSpace);
4846 }
4847 
4848 bool X86TTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
4849                                TargetTransformInfo::LSRCost &C2) {
4850     // X86 specific here are "instruction number 1st priority".
4851     return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
4852                     C1.NumIVMuls, C1.NumBaseAdds,
4853                     C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
4854            std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
4855                     C2.NumIVMuls, C2.NumBaseAdds,
4856                     C2.ScaleCost, C2.ImmCost, C2.SetupCost);
4857 }
4858 
4859 bool X86TTIImpl::canMacroFuseCmp() {
4860   return ST->hasMacroFusion() || ST->hasBranchFusion();
4861 }
4862 
4863 bool X86TTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) {
4864   if (!ST->hasAVX())
4865     return false;
4866 
4867   // The backend can't handle a single element vector.
4868   if (isa<VectorType>(DataTy) &&
4869       cast<FixedVectorType>(DataTy)->getNumElements() == 1)
4870     return false;
4871   Type *ScalarTy = DataTy->getScalarType();
4872 
4873   if (ScalarTy->isPointerTy())
4874     return true;
4875 
4876   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4877     return true;
4878 
4879   if (ScalarTy->isHalfTy() && ST->hasBWI() && ST->hasFP16())
4880     return true;
4881 
4882   if (!ScalarTy->isIntegerTy())
4883     return false;
4884 
4885   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4886   return IntWidth == 32 || IntWidth == 64 ||
4887          ((IntWidth == 8 || IntWidth == 16) && ST->hasBWI());
4888 }
4889 
4890 bool X86TTIImpl::isLegalMaskedStore(Type *DataType, Align Alignment) {
4891   return isLegalMaskedLoad(DataType, Alignment);
4892 }
4893 
4894 bool X86TTIImpl::isLegalNTLoad(Type *DataType, Align Alignment) {
4895   unsigned DataSize = DL.getTypeStoreSize(DataType);
4896   // The only supported nontemporal loads are for aligned vectors of 16 or 32
4897   // bytes.  Note that 32-byte nontemporal vector loads are supported by AVX2
4898   // (the equivalent stores only require AVX).
4899   if (Alignment >= DataSize && (DataSize == 16 || DataSize == 32))
4900     return DataSize == 16 ?  ST->hasSSE1() : ST->hasAVX2();
4901 
4902   return false;
4903 }
4904 
4905 bool X86TTIImpl::isLegalNTStore(Type *DataType, Align Alignment) {
4906   unsigned DataSize = DL.getTypeStoreSize(DataType);
4907 
4908   // SSE4A supports nontemporal stores of float and double at arbitrary
4909   // alignment.
4910   if (ST->hasSSE4A() && (DataType->isFloatTy() || DataType->isDoubleTy()))
4911     return true;
4912 
4913   // Besides the SSE4A subtarget exception above, only aligned stores are
4914   // available nontemporaly on any other subtarget.  And only stores with a size
4915   // of 4..32 bytes (powers of 2, only) are permitted.
4916   if (Alignment < DataSize || DataSize < 4 || DataSize > 32 ||
4917       !isPowerOf2_32(DataSize))
4918     return false;
4919 
4920   // 32-byte vector nontemporal stores are supported by AVX (the equivalent
4921   // loads require AVX2).
4922   if (DataSize == 32)
4923     return ST->hasAVX();
4924   if (DataSize == 16)
4925     return ST->hasSSE1();
4926   return true;
4927 }
4928 
4929 bool X86TTIImpl::isLegalMaskedExpandLoad(Type *DataTy) {
4930   if (!isa<VectorType>(DataTy))
4931     return false;
4932 
4933   if (!ST->hasAVX512())
4934     return false;
4935 
4936   // The backend can't handle a single element vector.
4937   if (cast<FixedVectorType>(DataTy)->getNumElements() == 1)
4938     return false;
4939 
4940   Type *ScalarTy = cast<VectorType>(DataTy)->getElementType();
4941 
4942   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4943     return true;
4944 
4945   if (!ScalarTy->isIntegerTy())
4946     return false;
4947 
4948   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4949   return IntWidth == 32 || IntWidth == 64 ||
4950          ((IntWidth == 8 || IntWidth == 16) && ST->hasVBMI2());
4951 }
4952 
4953 bool X86TTIImpl::isLegalMaskedCompressStore(Type *DataTy) {
4954   return isLegalMaskedExpandLoad(DataTy);
4955 }
4956 
4957 bool X86TTIImpl::supportsGather() const {
4958   // Some CPUs have better gather performance than others.
4959   // TODO: Remove the explicit ST->hasAVX512()?, That would mean we would only
4960   // enable gather with a -march.
4961   return ST->hasAVX512() || (ST->hasFastGather() && ST->hasAVX2());
4962 }
4963 
4964 bool X86TTIImpl::isLegalMaskedGather(Type *DataTy, Align Alignment) {
4965   if (!supportsGather())
4966     return false;
4967 
4968   // This function is called now in two cases: from the Loop Vectorizer
4969   // and from the Scalarizer.
4970   // When the Loop Vectorizer asks about legality of the feature,
4971   // the vectorization factor is not calculated yet. The Loop Vectorizer
4972   // sends a scalar type and the decision is based on the width of the
4973   // scalar element.
4974   // Later on, the cost model will estimate usage this intrinsic based on
4975   // the vector type.
4976   // The Scalarizer asks again about legality. It sends a vector type.
4977   // In this case we can reject non-power-of-2 vectors.
4978   // We also reject single element vectors as the type legalizer can't
4979   // scalarize it.
4980   if (auto *DataVTy = dyn_cast<FixedVectorType>(DataTy)) {
4981     unsigned NumElts = DataVTy->getNumElements();
4982     if (NumElts == 1)
4983       return false;
4984     // Gather / Scatter for vector 2 is not profitable on KNL / SKX
4985     // Vector-4 of gather/scatter instruction does not exist on KNL.
4986     // We can extend it to 8 elements, but zeroing upper bits of
4987     // the mask vector will add more instructions. Right now we give the scalar
4988     // cost of vector-4 for KNL. TODO: Check, maybe the gather/scatter
4989     // instruction is better in the VariableMask case.
4990     if (ST->hasAVX512() && (NumElts == 2 || (NumElts == 4 && !ST->hasVLX())))
4991       return false;
4992   }
4993   Type *ScalarTy = DataTy->getScalarType();
4994   if (ScalarTy->isPointerTy())
4995     return true;
4996 
4997   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4998     return true;
4999 
5000   if (!ScalarTy->isIntegerTy())
5001     return false;
5002 
5003   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
5004   return IntWidth == 32 || IntWidth == 64;
5005 }
5006 
5007 bool X86TTIImpl::isLegalMaskedScatter(Type *DataType, Align Alignment) {
5008   // AVX2 doesn't support scatter
5009   if (!ST->hasAVX512())
5010     return false;
5011   return isLegalMaskedGather(DataType, Alignment);
5012 }
5013 
5014 bool X86TTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
5015   EVT VT = TLI->getValueType(DL, DataType);
5016   return TLI->isOperationLegal(IsSigned ? ISD::SDIVREM : ISD::UDIVREM, VT);
5017 }
5018 
5019 bool X86TTIImpl::isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
5020   return false;
5021 }
5022 
5023 bool X86TTIImpl::areInlineCompatible(const Function *Caller,
5024                                      const Function *Callee) const {
5025   const TargetMachine &TM = getTLI()->getTargetMachine();
5026 
5027   // Work this as a subsetting of subtarget features.
5028   const FeatureBitset &CallerBits =
5029       TM.getSubtargetImpl(*Caller)->getFeatureBits();
5030   const FeatureBitset &CalleeBits =
5031       TM.getSubtargetImpl(*Callee)->getFeatureBits();
5032 
5033   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
5034   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
5035   return (RealCallerBits & RealCalleeBits) == RealCalleeBits;
5036 }
5037 
5038 bool X86TTIImpl::areFunctionArgsABICompatible(
5039     const Function *Caller, const Function *Callee,
5040     SmallPtrSetImpl<Argument *> &Args) const {
5041   if (!BaseT::areFunctionArgsABICompatible(Caller, Callee, Args))
5042     return false;
5043 
5044   // If we get here, we know the target features match. If one function
5045   // considers 512-bit vectors legal and the other does not, consider them
5046   // incompatible.
5047   const TargetMachine &TM = getTLI()->getTargetMachine();
5048 
5049   if (TM.getSubtarget<X86Subtarget>(*Caller).useAVX512Regs() ==
5050       TM.getSubtarget<X86Subtarget>(*Callee).useAVX512Regs())
5051     return true;
5052 
5053   // Consider the arguments compatible if they aren't vectors or aggregates.
5054   // FIXME: Look at the size of vectors.
5055   // FIXME: Look at the element types of aggregates to see if there are vectors.
5056   // FIXME: The API of this function seems intended to allow arguments
5057   // to be removed from the set, but the caller doesn't check if the set
5058   // becomes empty so that may not work in practice.
5059   return llvm::none_of(Args, [](Argument *A) {
5060     auto *EltTy = cast<PointerType>(A->getType())->getElementType();
5061     return EltTy->isVectorTy() || EltTy->isAggregateType();
5062   });
5063 }
5064 
5065 X86TTIImpl::TTI::MemCmpExpansionOptions
5066 X86TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
5067   TTI::MemCmpExpansionOptions Options;
5068   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
5069   Options.NumLoadsPerBlock = 2;
5070   // All GPR and vector loads can be unaligned.
5071   Options.AllowOverlappingLoads = true;
5072   if (IsZeroCmp) {
5073     // Only enable vector loads for equality comparison. Right now the vector
5074     // version is not as fast for three way compare (see #33329).
5075     const unsigned PreferredWidth = ST->getPreferVectorWidth();
5076     if (PreferredWidth >= 512 && ST->hasAVX512()) Options.LoadSizes.push_back(64);
5077     if (PreferredWidth >= 256 && ST->hasAVX()) Options.LoadSizes.push_back(32);
5078     if (PreferredWidth >= 128 && ST->hasSSE2()) Options.LoadSizes.push_back(16);
5079   }
5080   if (ST->is64Bit()) {
5081     Options.LoadSizes.push_back(8);
5082   }
5083   Options.LoadSizes.push_back(4);
5084   Options.LoadSizes.push_back(2);
5085   Options.LoadSizes.push_back(1);
5086   return Options;
5087 }
5088 
5089 bool X86TTIImpl::prefersVectorizedAddressing() const {
5090   return supportsGather();
5091 }
5092 
5093 bool X86TTIImpl::supportsEfficientVectorElementLoadStore() const {
5094   return false;
5095 }
5096 
5097 bool X86TTIImpl::enableInterleavedAccessVectorization() {
5098   // TODO: We expect this to be beneficial regardless of arch,
5099   // but there are currently some unexplained performance artifacts on Atom.
5100   // As a temporary solution, disable on Atom.
5101   return !(ST->isAtom());
5102 }
5103 
5104 // Get estimation for interleaved load/store operations and strided load.
5105 // \p Indices contains indices for strided load.
5106 // \p Factor - the factor of interleaving.
5107 // AVX-512 provides 3-src shuffles that significantly reduces the cost.
5108 InstructionCost X86TTIImpl::getInterleavedMemoryOpCostAVX512(
5109     unsigned Opcode, FixedVectorType *VecTy, unsigned Factor,
5110     ArrayRef<unsigned> Indices, Align Alignment, unsigned AddressSpace,
5111     TTI::TargetCostKind CostKind, bool UseMaskForCond, bool UseMaskForGaps) {
5112   // VecTy for interleave memop is <VF*Factor x Elt>.
5113   // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
5114   // VecTy = <12 x i32>.
5115 
5116   // Calculate the number of memory operations (NumOfMemOps), required
5117   // for load/store the VecTy.
5118   MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
5119   unsigned VecTySize = DL.getTypeStoreSize(VecTy);
5120   unsigned LegalVTSize = LegalVT.getStoreSize();
5121   unsigned NumOfMemOps = (VecTySize + LegalVTSize - 1) / LegalVTSize;
5122 
5123   // Get the cost of one memory operation.
5124   auto *SingleMemOpTy = FixedVectorType::get(VecTy->getElementType(),
5125                                              LegalVT.getVectorNumElements());
5126   InstructionCost MemOpCost;
5127   if (UseMaskForCond || UseMaskForGaps)
5128     MemOpCost = getMaskedMemoryOpCost(Opcode, SingleMemOpTy, Alignment,
5129                                       AddressSpace, CostKind);
5130   else
5131     MemOpCost = getMemoryOpCost(Opcode, SingleMemOpTy, MaybeAlign(Alignment),
5132                                 AddressSpace, CostKind);
5133 
5134   unsigned VF = VecTy->getNumElements() / Factor;
5135   MVT VT = MVT::getVectorVT(MVT::getVT(VecTy->getScalarType()), VF);
5136 
5137   // FIXME: this is the most conservative estimate for the mask cost.
5138   InstructionCost MaskCost;
5139   if (UseMaskForCond || UseMaskForGaps) {
5140     APInt DemandedLoadStoreElts = APInt::getZero(VecTy->getNumElements());
5141     for (unsigned Index : Indices) {
5142       assert(Index < Factor && "Invalid index for interleaved memory op");
5143       for (unsigned Elm = 0; Elm < VF; Elm++)
5144         DemandedLoadStoreElts.setBit(Index + Elm * Factor);
5145     }
5146 
5147     Type *I8Type = Type::getInt8Ty(VecTy->getContext());
5148 
5149     MaskCost = getReplicationShuffleCost(
5150         I8Type, Factor, VF,
5151         UseMaskForGaps ? DemandedLoadStoreElts
5152                        : APInt::getAllOnes(VecTy->getNumElements()),
5153         CostKind);
5154 
5155     // The Gaps mask is invariant and created outside the loop, therefore the
5156     // cost of creating it is not accounted for here. However if we have both
5157     // a MaskForGaps and some other mask that guards the execution of the
5158     // memory access, we need to account for the cost of And-ing the two masks
5159     // inside the loop.
5160     if (UseMaskForGaps) {
5161       auto *MaskVT = FixedVectorType::get(I8Type, VecTy->getNumElements());
5162       MaskCost += getArithmeticInstrCost(BinaryOperator::And, MaskVT, CostKind);
5163     }
5164   }
5165 
5166   if (Opcode == Instruction::Load) {
5167     // The tables (AVX512InterleavedLoadTbl and AVX512InterleavedStoreTbl)
5168     // contain the cost of the optimized shuffle sequence that the
5169     // X86InterleavedAccess pass will generate.
5170     // The cost of loads and stores are computed separately from the table.
5171 
5172     // X86InterleavedAccess support only the following interleaved-access group.
5173     static const CostTblEntry AVX512InterleavedLoadTbl[] = {
5174         {3, MVT::v16i8, 12}, //(load 48i8 and) deinterleave into 3 x 16i8
5175         {3, MVT::v32i8, 14}, //(load 96i8 and) deinterleave into 3 x 32i8
5176         {3, MVT::v64i8, 22}, //(load 96i8 and) deinterleave into 3 x 32i8
5177     };
5178 
5179     if (const auto *Entry =
5180             CostTableLookup(AVX512InterleavedLoadTbl, Factor, VT))
5181       return MaskCost + NumOfMemOps * MemOpCost + Entry->Cost;
5182     //If an entry does not exist, fallback to the default implementation.
5183 
5184     // Kind of shuffle depends on number of loaded values.
5185     // If we load the entire data in one register, we can use a 1-src shuffle.
5186     // Otherwise, we'll merge 2 sources in each operation.
5187     TTI::ShuffleKind ShuffleKind =
5188         (NumOfMemOps > 1) ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc;
5189 
5190     InstructionCost ShuffleCost =
5191         getShuffleCost(ShuffleKind, SingleMemOpTy, None, 0, nullptr);
5192 
5193     unsigned NumOfLoadsInInterleaveGrp =
5194         Indices.size() ? Indices.size() : Factor;
5195     auto *ResultTy = FixedVectorType::get(VecTy->getElementType(),
5196                                           VecTy->getNumElements() / Factor);
5197     InstructionCost NumOfResults =
5198         getTLI()->getTypeLegalizationCost(DL, ResultTy).first *
5199         NumOfLoadsInInterleaveGrp;
5200 
5201     // About a half of the loads may be folded in shuffles when we have only
5202     // one result. If we have more than one result, we do not fold loads at all.
5203     unsigned NumOfUnfoldedLoads =
5204         NumOfResults > 1 ? NumOfMemOps : NumOfMemOps / 2;
5205 
5206     // Get a number of shuffle operations per result.
5207     unsigned NumOfShufflesPerResult =
5208         std::max((unsigned)1, (unsigned)(NumOfMemOps - 1));
5209 
5210     // The SK_MergeTwoSrc shuffle clobbers one of src operands.
5211     // When we have more than one destination, we need additional instructions
5212     // to keep sources.
5213     InstructionCost NumOfMoves = 0;
5214     if (NumOfResults > 1 && ShuffleKind == TTI::SK_PermuteTwoSrc)
5215       NumOfMoves = NumOfResults * NumOfShufflesPerResult / 2;
5216 
5217     InstructionCost Cost = NumOfResults * NumOfShufflesPerResult * ShuffleCost +
5218                            MaskCost + NumOfUnfoldedLoads * MemOpCost +
5219                            NumOfMoves;
5220 
5221     return Cost;
5222   }
5223 
5224   // Store.
5225   assert(Opcode == Instruction::Store &&
5226          "Expected Store Instruction at this  point");
5227   // X86InterleavedAccess support only the following interleaved-access group.
5228   static const CostTblEntry AVX512InterleavedStoreTbl[] = {
5229       {3, MVT::v16i8, 12}, // interleave 3 x 16i8 into 48i8 (and store)
5230       {3, MVT::v32i8, 14}, // interleave 3 x 32i8 into 96i8 (and store)
5231       {3, MVT::v64i8, 26}, // interleave 3 x 64i8 into 96i8 (and store)
5232 
5233       {4, MVT::v8i8, 10},  // interleave 4 x 8i8  into 32i8  (and store)
5234       {4, MVT::v16i8, 11}, // interleave 4 x 16i8 into 64i8  (and store)
5235       {4, MVT::v32i8, 14}, // interleave 4 x 32i8 into 128i8 (and store)
5236       {4, MVT::v64i8, 24}  // interleave 4 x 32i8 into 256i8 (and store)
5237   };
5238 
5239   if (const auto *Entry =
5240           CostTableLookup(AVX512InterleavedStoreTbl, Factor, VT))
5241     return MaskCost + NumOfMemOps * MemOpCost + Entry->Cost;
5242   //If an entry does not exist, fallback to the default implementation.
5243 
5244   // There is no strided stores meanwhile. And store can't be folded in
5245   // shuffle.
5246   unsigned NumOfSources = Factor; // The number of values to be merged.
5247   InstructionCost ShuffleCost =
5248       getShuffleCost(TTI::SK_PermuteTwoSrc, SingleMemOpTy, None, 0, nullptr);
5249   unsigned NumOfShufflesPerStore = NumOfSources - 1;
5250 
5251   // The SK_MergeTwoSrc shuffle clobbers one of src operands.
5252   // We need additional instructions to keep sources.
5253   unsigned NumOfMoves = NumOfMemOps * NumOfShufflesPerStore / 2;
5254   InstructionCost Cost =
5255       MaskCost +
5256       NumOfMemOps * (MemOpCost + NumOfShufflesPerStore * ShuffleCost) +
5257       NumOfMoves;
5258   return Cost;
5259 }
5260 
5261 InstructionCost X86TTIImpl::getInterleavedMemoryOpCost(
5262     unsigned Opcode, Type *BaseTy, unsigned Factor, ArrayRef<unsigned> Indices,
5263     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
5264     bool UseMaskForCond, bool UseMaskForGaps) {
5265   auto *VecTy = cast<FixedVectorType>(BaseTy);
5266 
5267   auto isSupportedOnAVX512 = [&](Type *VecTy, bool HasBW) {
5268     Type *EltTy = cast<VectorType>(VecTy)->getElementType();
5269     if (EltTy->isFloatTy() || EltTy->isDoubleTy() || EltTy->isIntegerTy(64) ||
5270         EltTy->isIntegerTy(32) || EltTy->isPointerTy())
5271       return true;
5272     if (EltTy->isIntegerTy(16) || EltTy->isIntegerTy(8) ||
5273         (!ST->useSoftFloat() && ST->hasFP16() && EltTy->isHalfTy()))
5274       return HasBW;
5275     return false;
5276   };
5277   if (ST->hasAVX512() && isSupportedOnAVX512(VecTy, ST->hasBWI()))
5278     return getInterleavedMemoryOpCostAVX512(
5279         Opcode, VecTy, Factor, Indices, Alignment,
5280         AddressSpace, CostKind, UseMaskForCond, UseMaskForGaps);
5281 
5282   if (UseMaskForCond || UseMaskForGaps)
5283     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5284                                              Alignment, AddressSpace, CostKind,
5285                                              UseMaskForCond, UseMaskForGaps);
5286 
5287   // Get estimation for interleaved load/store operations for SSE-AVX2.
5288   // As opposed to AVX-512, SSE-AVX2 do not have generic shuffles that allow
5289   // computing the cost using a generic formula as a function of generic
5290   // shuffles. We therefore use a lookup table instead, filled according to
5291   // the instruction sequences that codegen currently generates.
5292 
5293   // VecTy for interleave memop is <VF*Factor x Elt>.
5294   // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
5295   // VecTy = <12 x i32>.
5296   MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
5297 
5298   // This function can be called with VecTy=<6xi128>, Factor=3, in which case
5299   // the VF=2, while v2i128 is an unsupported MVT vector type
5300   // (see MachineValueType.h::getVectorVT()).
5301   if (!LegalVT.isVector())
5302     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5303                                              Alignment, AddressSpace, CostKind);
5304 
5305   unsigned VF = VecTy->getNumElements() / Factor;
5306   Type *ScalarTy = VecTy->getElementType();
5307   // Deduplicate entries, model floats/pointers as appropriately-sized integers.
5308   if (!ScalarTy->isIntegerTy())
5309     ScalarTy =
5310         Type::getIntNTy(ScalarTy->getContext(), DL.getTypeSizeInBits(ScalarTy));
5311 
5312   // Get the cost of all the memory operations.
5313   // FIXME: discount dead loads.
5314   InstructionCost MemOpCosts = getMemoryOpCost(
5315       Opcode, VecTy, MaybeAlign(Alignment), AddressSpace, CostKind);
5316 
5317   auto *VT = FixedVectorType::get(ScalarTy, VF);
5318   EVT ETy = TLI->getValueType(DL, VT);
5319   if (!ETy.isSimple())
5320     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5321                                              Alignment, AddressSpace, CostKind);
5322 
5323   // TODO: Complete for other data-types and strides.
5324   // Each combination of Stride, element bit width and VF results in a different
5325   // sequence; The cost tables are therefore accessed with:
5326   // Factor (stride) and VectorType=VFxiN.
5327   // The Cost accounts only for the shuffle sequence;
5328   // The cost of the loads/stores is accounted for separately.
5329   //
5330   static const CostTblEntry AVX2InterleavedLoadTbl[] = {
5331       {2, MVT::v2i8, 2},  // (load 4i8 and) deinterleave into 2 x 2i8
5332       {2, MVT::v4i8, 2},  // (load 8i8 and) deinterleave into 2 x 4i8
5333       {2, MVT::v8i8, 2},  // (load 16i8 and) deinterleave into 2 x 8i8
5334       {2, MVT::v16i8, 4}, // (load 32i8 and) deinterleave into 2 x 16i8
5335       {2, MVT::v32i8, 6}, // (load 64i8 and) deinterleave into 2 x 32i8
5336 
5337       {2, MVT::v8i16, 6},   // (load 16i16 and) deinterleave into 2 x 8i16
5338       {2, MVT::v16i16, 9},  // (load 32i16 and) deinterleave into 2 x 16i16
5339       {2, MVT::v32i16, 18}, // (load 64i16 and) deinterleave into 2 x 32i16
5340 
5341       {2, MVT::v8i32, 4},   // (load 16i32 and) deinterleave into 2 x 8i32
5342       {2, MVT::v16i32, 8},  // (load 32i32 and) deinterleave into 2 x 16i32
5343       {2, MVT::v32i32, 16}, // (load 64i32 and) deinterleave into 2 x 32i32
5344 
5345       {2, MVT::v4i64, 4},   // (load 8i64 and) deinterleave into 2 x 4i64
5346       {2, MVT::v8i64, 8},   // (load 16i64 and) deinterleave into 2 x 8i64
5347       {2, MVT::v16i64, 16}, // (load 32i64 and) deinterleave into 2 x 16i64
5348       {2, MVT::v32i64, 32}, // (load 64i64 and) deinterleave into 2 x 32i64
5349 
5350       {3, MVT::v2i8, 3},   // (load 6i8 and) deinterleave into 3 x 2i8
5351       {3, MVT::v4i8, 3},   // (load 12i8 and) deinterleave into 3 x 4i8
5352       {3, MVT::v8i8, 6},   // (load 24i8 and) deinterleave into 3 x 8i8
5353       {3, MVT::v16i8, 11}, // (load 48i8 and) deinterleave into 3 x 16i8
5354       {3, MVT::v32i8, 14}, // (load 96i8 and) deinterleave into 3 x 32i8
5355 
5356       {3, MVT::v2i16, 5},   // (load 6i16 and) deinterleave into 3 x 2i16
5357       {3, MVT::v4i16, 7},   // (load 12i16 and) deinterleave into 3 x 4i16
5358       {3, MVT::v8i16, 9},   // (load 24i16 and) deinterleave into 3 x 8i16
5359       {3, MVT::v16i16, 28}, // (load 48i16 and) deinterleave into 3 x 16i16
5360       {3, MVT::v32i16, 56}, // (load 96i16 and) deinterleave into 3 x 32i16
5361 
5362       {3, MVT::v2i32, 3},   // (load 6i32 and) deinterleave into 3 x 2i32
5363       {3, MVT::v4i32, 3},   // (load 12i32 and) deinterleave into 3 x 4i32
5364       {3, MVT::v8i32, 7},   // (load 24i32 and) deinterleave into 3 x 8i32
5365       {3, MVT::v16i32, 14}, // (load 48i32 and) deinterleave into 3 x 16i32
5366       {3, MVT::v32i32, 32}, // (load 96i32 and) deinterleave into 3 x 32i32
5367 
5368       {3, MVT::v2i64, 1},   // (load 6i64 and) deinterleave into 3 x 2i64
5369       {3, MVT::v4i64, 5},   // (load 12i64 and) deinterleave into 3 x 4i64
5370       {3, MVT::v8i64, 10},  // (load 24i64 and) deinterleave into 3 x 8i64
5371       {3, MVT::v16i64, 20}, // (load 48i64 and) deinterleave into 3 x 16i64
5372 
5373       {4, MVT::v2i8, 4},   // (load 8i8 and) deinterleave into 4 x 2i8
5374       {4, MVT::v4i8, 4},   // (load 16i8 and) deinterleave into 4 x 4i8
5375       {4, MVT::v8i8, 12},  // (load 32i8 and) deinterleave into 4 x 8i8
5376       {4, MVT::v16i8, 24}, // (load 64i8 and) deinterleave into 4 x 16i8
5377       {4, MVT::v32i8, 56}, // (load 128i8 and) deinterleave into 4 x 32i8
5378 
5379       {4, MVT::v2i16, 6},    // (load 8i16 and) deinterleave into 4 x 2i16
5380       {4, MVT::v4i16, 17},   // (load 16i16 and) deinterleave into 4 x 4i16
5381       {4, MVT::v8i16, 33},   // (load 32i16 and) deinterleave into 4 x 8i16
5382       {4, MVT::v16i16, 75},  // (load 64i16 and) deinterleave into 4 x 16i16
5383       {4, MVT::v32i16, 150}, // (load 128i16 and) deinterleave into 4 x 32i16
5384 
5385       {4, MVT::v2i32, 4},   // (load 8i32 and) deinterleave into 4 x 2i32
5386       {4, MVT::v4i32, 8},   // (load 16i32 and) deinterleave into 4 x 4i32
5387       {4, MVT::v8i32, 16},  // (load 32i32 and) deinterleave into 4 x 8i32
5388       {4, MVT::v16i32, 32}, // (load 64i32 and) deinterleave into 4 x 16i32
5389       {4, MVT::v32i32, 68}, // (load 128i32 and) deinterleave into 4 x 32i32
5390 
5391       {4, MVT::v2i64, 6},  // (load 8i64 and) deinterleave into 4 x 2i64
5392       {4, MVT::v4i64, 8},  // (load 16i64 and) deinterleave into 4 x 4i64
5393       {4, MVT::v8i64, 20}, // (load 32i64 and) deinterleave into 4 x 8i64
5394       {4, MVT::v16i64, 40}, // (load 64i64 and) deinterleave into 4 x 16i64
5395 
5396       {6, MVT::v2i8, 6},   // (load 12i8 and) deinterleave into 6 x 2i8
5397       {6, MVT::v4i8, 14},  // (load 24i8 and) deinterleave into 6 x 4i8
5398       {6, MVT::v8i8, 18},  // (load 48i8 and) deinterleave into 6 x 8i8
5399       {6, MVT::v16i8, 43}, // (load 96i8 and) deinterleave into 6 x 16i8
5400       {6, MVT::v32i8, 82}, // (load 192i8 and) deinterleave into 6 x 32i8
5401 
5402       {6, MVT::v2i16, 13},   // (load 12i16 and) deinterleave into 6 x 2i16
5403       {6, MVT::v4i16, 9},    // (load 24i16 and) deinterleave into 6 x 4i16
5404       {6, MVT::v8i16, 39},   // (load 48i16 and) deinterleave into 6 x 8i16
5405       {6, MVT::v16i16, 106}, // (load 96i16 and) deinterleave into 6 x 16i16
5406       {6, MVT::v32i16, 212}, // (load 192i16 and) deinterleave into 6 x 32i16
5407 
5408       {6, MVT::v2i32, 6},   // (load 12i32 and) deinterleave into 6 x 2i32
5409       {6, MVT::v4i32, 15},  // (load 24i32 and) deinterleave into 6 x 4i32
5410       {6, MVT::v8i32, 31},  // (load 48i32 and) deinterleave into 6 x 8i32
5411       {6, MVT::v16i32, 64}, // (load 96i32 and) deinterleave into 6 x 16i32
5412 
5413       {6, MVT::v2i64, 6},  // (load 12i64 and) deinterleave into 6 x 2i64
5414       {6, MVT::v4i64, 18}, // (load 24i64 and) deinterleave into 6 x 4i64
5415       {6, MVT::v8i64, 36}, // (load 48i64 and) deinterleave into 6 x 8i64
5416 
5417       {8, MVT::v8i32, 40} // (load 64i32 and) deinterleave into 8 x 8i32
5418   };
5419 
5420   static const CostTblEntry SSSE3InterleavedLoadTbl[] = {
5421       {2, MVT::v4i16, 2},   // (load 8i16 and) deinterleave into 2 x 4i16
5422   };
5423 
5424   static const CostTblEntry SSE2InterleavedLoadTbl[] = {
5425       {2, MVT::v2i16, 2},   // (load 4i16 and) deinterleave into 2 x 2i16
5426       {2, MVT::v4i16, 7},   // (load 8i16 and) deinterleave into 2 x 4i16
5427 
5428       {2, MVT::v2i32, 2},   // (load 4i32 and) deinterleave into 2 x 2i32
5429       {2, MVT::v4i32, 2},   // (load 8i32 and) deinterleave into 2 x 4i32
5430 
5431       {2, MVT::v2i64, 2},   // (load 4i64 and) deinterleave into 2 x 2i64
5432   };
5433 
5434   static const CostTblEntry AVX2InterleavedStoreTbl[] = {
5435       {2, MVT::v16i8, 3}, // interleave 2 x 16i8 into 32i8 (and store)
5436       {2, MVT::v32i8, 4}, // interleave 2 x 32i8 into 64i8 (and store)
5437 
5438       {2, MVT::v8i16, 3},  // interleave 2 x 8i16 into 16i16 (and store)
5439       {2, MVT::v16i16, 4}, // interleave 2 x 16i16 into 32i16 (and store)
5440       {2, MVT::v32i16, 8}, // interleave 2 x 32i16 into 64i16 (and store)
5441 
5442       {2, MVT::v4i32, 2},   // interleave 2 x 4i32 into 8i32 (and store)
5443       {2, MVT::v8i32, 4},   // interleave 2 x 8i32 into 16i32 (and store)
5444       {2, MVT::v16i32, 8},  // interleave 2 x 16i32 into 32i32 (and store)
5445       {2, MVT::v32i32, 16}, // interleave 2 x 32i32 into 64i32 (and store)
5446 
5447       {2, MVT::v2i64, 2},   // interleave 2 x 2i64 into 4i64 (and store)
5448       {2, MVT::v4i64, 4},   // interleave 2 x 4i64 into 8i64 (and store)
5449       {2, MVT::v8i64, 8},   // interleave 2 x 8i64 into 16i64 (and store)
5450       {2, MVT::v16i64, 16}, // interleave 2 x 16i64 into 32i64 (and store)
5451       {2, MVT::v32i64, 32}, // interleave 2 x 32i64 into 64i64 (and store)
5452 
5453       {3, MVT::v2i8, 4},   // interleave 3 x 2i8 into 6i8 (and store)
5454       {3, MVT::v4i8, 4},   // interleave 3 x 4i8 into 12i8 (and store)
5455       {3, MVT::v8i8, 6},   // interleave 3 x 8i8 into 24i8 (and store)
5456       {3, MVT::v16i8, 11}, // interleave 3 x 16i8 into 48i8 (and store)
5457       {3, MVT::v32i8, 13}, // interleave 3 x 32i8 into 96i8 (and store)
5458 
5459       {3, MVT::v2i16, 4},   // interleave 3 x 2i16 into 6i16 (and store)
5460       {3, MVT::v4i16, 6},   // interleave 3 x 4i16 into 12i16 (and store)
5461       {3, MVT::v8i16, 12},  // interleave 3 x 8i16 into 24i16 (and store)
5462       {3, MVT::v16i16, 27}, // interleave 3 x 16i16 into 48i16 (and store)
5463       {3, MVT::v32i16, 54}, // interleave 3 x 32i16 into 96i16 (and store)
5464 
5465       {3, MVT::v2i32, 4},   // interleave 3 x 2i32 into 6i32 (and store)
5466       {3, MVT::v4i32, 5},   // interleave 3 x 4i32 into 12i32 (and store)
5467       {3, MVT::v8i32, 11},  // interleave 3 x 8i32 into 24i32 (and store)
5468       {3, MVT::v16i32, 22}, // interleave 3 x 16i32 into 48i32 (and store)
5469       {3, MVT::v32i32, 48}, // interleave 3 x 32i32 into 96i32 (and store)
5470 
5471       {3, MVT::v2i64, 4},   // interleave 3 x 2i64 into 6i64 (and store)
5472       {3, MVT::v4i64, 6},   // interleave 3 x 4i64 into 12i64 (and store)
5473       {3, MVT::v8i64, 12},  // interleave 3 x 8i64 into 24i64 (and store)
5474       {3, MVT::v16i64, 24}, // interleave 3 x 16i64 into 48i64 (and store)
5475 
5476       {4, MVT::v2i8, 4},   // interleave 4 x 2i8 into 8i8 (and store)
5477       {4, MVT::v4i8, 4},   // interleave 4 x 4i8 into 16i8 (and store)
5478       {4, MVT::v8i8, 4},   // interleave 4 x 8i8 into 32i8 (and store)
5479       {4, MVT::v16i8, 8},  // interleave 4 x 16i8 into 64i8 (and store)
5480       {4, MVT::v32i8, 12}, // interleave 4 x 32i8 into 128i8 (and store)
5481 
5482       {4, MVT::v2i16, 2},   // interleave 4 x 2i16 into 8i16 (and store)
5483       {4, MVT::v4i16, 6},   // interleave 4 x 4i16 into 16i16 (and store)
5484       {4, MVT::v8i16, 10},  // interleave 4 x 8i16 into 32i16 (and store)
5485       {4, MVT::v16i16, 32}, // interleave 4 x 16i16 into 64i16 (and store)
5486       {4, MVT::v32i16, 64}, // interleave 4 x 32i16 into 128i16 (and store)
5487 
5488       {4, MVT::v2i32, 5},   // interleave 4 x 2i32 into 8i32 (and store)
5489       {4, MVT::v4i32, 6},   // interleave 4 x 4i32 into 16i32 (and store)
5490       {4, MVT::v8i32, 16},  // interleave 4 x 8i32 into 32i32 (and store)
5491       {4, MVT::v16i32, 32}, // interleave 4 x 16i32 into 64i32 (and store)
5492       {4, MVT::v32i32, 64}, // interleave 4 x 32i32 into 128i32 (and store)
5493 
5494       {4, MVT::v2i64, 6},  // interleave 4 x 2i64 into 8i64 (and store)
5495       {4, MVT::v4i64, 8},  // interleave 4 x 4i64 into 16i64 (and store)
5496       {4, MVT::v8i64, 20}, // interleave 4 x 8i64 into 32i64 (and store)
5497       {4, MVT::v16i64, 40}, // interleave 4 x 16i64 into 64i64 (and store)
5498 
5499       {6, MVT::v2i8, 7},   // interleave 6 x 2i8 into 12i8 (and store)
5500       {6, MVT::v4i8, 9},   // interleave 6 x 4i8 into 24i8 (and store)
5501       {6, MVT::v8i8, 16},  // interleave 6 x 8i8 into 48i8 (and store)
5502       {6, MVT::v16i8, 27}, // interleave 6 x 16i8 into 96i8 (and store)
5503       {6, MVT::v32i8, 90}, // interleave 6 x 32i8 into 192i8 (and store)
5504 
5505       {6, MVT::v2i16, 10},  // interleave 6 x 2i16 into 12i16 (and store)
5506       {6, MVT::v4i16, 15},  // interleave 6 x 4i16 into 24i16 (and store)
5507       {6, MVT::v8i16, 21},  // interleave 6 x 8i16 into 48i16 (and store)
5508       {6, MVT::v16i16, 58}, // interleave 6 x 16i16 into 96i16 (and store)
5509       {6, MVT::v32i16, 90}, // interleave 6 x 32i16 into 192i16 (and store)
5510 
5511       {6, MVT::v2i32, 9},   // interleave 6 x 2i32 into 12i32 (and store)
5512       {6, MVT::v4i32, 12},  // interleave 6 x 4i32 into 24i32 (and store)
5513       {6, MVT::v8i32, 33},  // interleave 6 x 8i32 into 48i32 (and store)
5514       {6, MVT::v16i32, 66}, // interleave 6 x 16i32 into 96i32 (and store)
5515 
5516       {6, MVT::v2i64, 8},  // interleave 6 x 2i64 into 12i64 (and store)
5517       {6, MVT::v4i64, 15}, // interleave 6 x 4i64 into 24i64 (and store)
5518       {6, MVT::v8i64, 30}, // interleave 6 x 8i64 into 48i64 (and store)
5519   };
5520 
5521   static const CostTblEntry SSE2InterleavedStoreTbl[] = {
5522       {2, MVT::v2i8, 1},   // interleave 2 x 2i8 into 4i8 (and store)
5523       {2, MVT::v4i8, 1},   // interleave 2 x 4i8 into 8i8 (and store)
5524       {2, MVT::v8i8, 1},   // interleave 2 x 8i8 into 16i8 (and store)
5525 
5526       {2, MVT::v2i16, 1},  // interleave 2 x 2i16 into 4i16 (and store)
5527       {2, MVT::v4i16, 1},  // interleave 2 x 4i16 into 8i16 (and store)
5528 
5529       {2, MVT::v2i32, 1},  // interleave 2 x 2i32 into 4i32 (and store)
5530   };
5531 
5532   if (Opcode == Instruction::Load) {
5533     auto GetDiscountedCost = [Factor, NumMembers = Indices.size(),
5534                               MemOpCosts](const CostTblEntry *Entry) {
5535       // NOTE: this is just an approximation!
5536       //       It can over/under -estimate the cost!
5537       return MemOpCosts + divideCeil(NumMembers * Entry->Cost, Factor);
5538     };
5539 
5540     if (ST->hasAVX2())
5541       if (const auto *Entry = CostTableLookup(AVX2InterleavedLoadTbl, Factor,
5542                                               ETy.getSimpleVT()))
5543         return GetDiscountedCost(Entry);
5544 
5545     if (ST->hasSSSE3())
5546       if (const auto *Entry = CostTableLookup(SSSE3InterleavedLoadTbl, Factor,
5547                                               ETy.getSimpleVT()))
5548         return GetDiscountedCost(Entry);
5549 
5550     if (ST->hasSSE2())
5551       if (const auto *Entry = CostTableLookup(SSE2InterleavedLoadTbl, Factor,
5552                                               ETy.getSimpleVT()))
5553         return GetDiscountedCost(Entry);
5554   } else {
5555     assert(Opcode == Instruction::Store &&
5556            "Expected Store Instruction at this point");
5557     assert((!Indices.size() || Indices.size() == Factor) &&
5558            "Interleaved store only supports fully-interleaved groups.");
5559     if (ST->hasAVX2())
5560       if (const auto *Entry = CostTableLookup(AVX2InterleavedStoreTbl, Factor,
5561                                               ETy.getSimpleVT()))
5562         return MemOpCosts + Entry->Cost;
5563 
5564     if (ST->hasSSE2())
5565       if (const auto *Entry = CostTableLookup(SSE2InterleavedStoreTbl, Factor,
5566                                               ETy.getSimpleVT()))
5567         return MemOpCosts + Entry->Cost;
5568   }
5569 
5570   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5571                                            Alignment, AddressSpace, CostKind,
5572                                            UseMaskForCond, UseMaskForGaps);
5573 }
5574