1 //===-- AArch64TargetTransformInfo.cpp - AArch64 specific TTI -------------===//
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 
9 #include "AArch64ExpandImm.h"
10 #include "AArch64TargetTransformInfo.h"
11 #include "MCTargetDesc/AArch64AddressingModes.h"
12 #include "llvm/Analysis/LoopInfo.h"
13 #include "llvm/Analysis/TargetTransformInfo.h"
14 #include "llvm/CodeGen/BasicTTIImpl.h"
15 #include "llvm/CodeGen/CostTable.h"
16 #include "llvm/CodeGen/TargetLowering.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/IntrinsicsAArch64.h"
19 #include "llvm/Support/Debug.h"
20 #include <algorithm>
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "aarch64tti"
24 
25 static cl::opt<bool> EnableFalkorHWPFUnrollFix("enable-falkor-hwpf-unroll-fix",
26                                                cl::init(true), cl::Hidden);
27 
28 bool AArch64TTIImpl::areInlineCompatible(const Function *Caller,
29                                          const Function *Callee) const {
30   const TargetMachine &TM = getTLI()->getTargetMachine();
31 
32   const FeatureBitset &CallerBits =
33       TM.getSubtargetImpl(*Caller)->getFeatureBits();
34   const FeatureBitset &CalleeBits =
35       TM.getSubtargetImpl(*Callee)->getFeatureBits();
36 
37   // Inline a callee if its target-features are a subset of the callers
38   // target-features.
39   return (CallerBits & CalleeBits) == CalleeBits;
40 }
41 
42 /// Calculate the cost of materializing a 64-bit value. This helper
43 /// method might only calculate a fraction of a larger immediate. Therefore it
44 /// is valid to return a cost of ZERO.
45 int AArch64TTIImpl::getIntImmCost(int64_t Val) {
46   // Check if the immediate can be encoded within an instruction.
47   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, 64))
48     return 0;
49 
50   if (Val < 0)
51     Val = ~Val;
52 
53   // Calculate how many moves we will need to materialize this constant.
54   SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
55   AArch64_IMM::expandMOVImm(Val, 64, Insn);
56   return Insn.size();
57 }
58 
59 /// Calculate the cost of materializing the given constant.
60 int AArch64TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
61                                   TTI::TargetCostKind CostKind) {
62   assert(Ty->isIntegerTy());
63 
64   unsigned BitSize = Ty->getPrimitiveSizeInBits();
65   if (BitSize == 0)
66     return ~0U;
67 
68   // Sign-extend all constants to a multiple of 64-bit.
69   APInt ImmVal = Imm;
70   if (BitSize & 0x3f)
71     ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
72 
73   // Split the constant into 64-bit chunks and calculate the cost for each
74   // chunk.
75   int Cost = 0;
76   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
77     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
78     int64_t Val = Tmp.getSExtValue();
79     Cost += getIntImmCost(Val);
80   }
81   // We need at least one instruction to materialze the constant.
82   return std::max(1, Cost);
83 }
84 
85 int AArch64TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
86                                       const APInt &Imm, Type *Ty,
87                                       TTI::TargetCostKind CostKind) {
88   assert(Ty->isIntegerTy());
89 
90   unsigned BitSize = Ty->getPrimitiveSizeInBits();
91   // There is no cost model for constants with a bit size of 0. Return TCC_Free
92   // here, so that constant hoisting will ignore this constant.
93   if (BitSize == 0)
94     return TTI::TCC_Free;
95 
96   unsigned ImmIdx = ~0U;
97   switch (Opcode) {
98   default:
99     return TTI::TCC_Free;
100   case Instruction::GetElementPtr:
101     // Always hoist the base address of a GetElementPtr.
102     if (Idx == 0)
103       return 2 * TTI::TCC_Basic;
104     return TTI::TCC_Free;
105   case Instruction::Store:
106     ImmIdx = 0;
107     break;
108   case Instruction::Add:
109   case Instruction::Sub:
110   case Instruction::Mul:
111   case Instruction::UDiv:
112   case Instruction::SDiv:
113   case Instruction::URem:
114   case Instruction::SRem:
115   case Instruction::And:
116   case Instruction::Or:
117   case Instruction::Xor:
118   case Instruction::ICmp:
119     ImmIdx = 1;
120     break;
121   // Always return TCC_Free for the shift value of a shift instruction.
122   case Instruction::Shl:
123   case Instruction::LShr:
124   case Instruction::AShr:
125     if (Idx == 1)
126       return TTI::TCC_Free;
127     break;
128   case Instruction::Trunc:
129   case Instruction::ZExt:
130   case Instruction::SExt:
131   case Instruction::IntToPtr:
132   case Instruction::PtrToInt:
133   case Instruction::BitCast:
134   case Instruction::PHI:
135   case Instruction::Call:
136   case Instruction::Select:
137   case Instruction::Ret:
138   case Instruction::Load:
139     break;
140   }
141 
142   if (Idx == ImmIdx) {
143     int NumConstants = (BitSize + 63) / 64;
144     int Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
145     return (Cost <= NumConstants * TTI::TCC_Basic)
146                ? static_cast<int>(TTI::TCC_Free)
147                : Cost;
148   }
149   return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
150 }
151 
152 int AArch64TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
153                                         const APInt &Imm, Type *Ty,
154                                         TTI::TargetCostKind CostKind) {
155   assert(Ty->isIntegerTy());
156 
157   unsigned BitSize = Ty->getPrimitiveSizeInBits();
158   // There is no cost model for constants with a bit size of 0. Return TCC_Free
159   // here, so that constant hoisting will ignore this constant.
160   if (BitSize == 0)
161     return TTI::TCC_Free;
162 
163   // Most (all?) AArch64 intrinsics do not support folding immediates into the
164   // selected instruction, so we compute the materialization cost for the
165   // immediate directly.
166   if (IID >= Intrinsic::aarch64_addg && IID <= Intrinsic::aarch64_udiv)
167     return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
168 
169   switch (IID) {
170   default:
171     return TTI::TCC_Free;
172   case Intrinsic::sadd_with_overflow:
173   case Intrinsic::uadd_with_overflow:
174   case Intrinsic::ssub_with_overflow:
175   case Intrinsic::usub_with_overflow:
176   case Intrinsic::smul_with_overflow:
177   case Intrinsic::umul_with_overflow:
178     if (Idx == 1) {
179       int NumConstants = (BitSize + 63) / 64;
180       int Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
181       return (Cost <= NumConstants * TTI::TCC_Basic)
182                  ? static_cast<int>(TTI::TCC_Free)
183                  : Cost;
184     }
185     break;
186   case Intrinsic::experimental_stackmap:
187     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
188       return TTI::TCC_Free;
189     break;
190   case Intrinsic::experimental_patchpoint_void:
191   case Intrinsic::experimental_patchpoint_i64:
192     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
193       return TTI::TCC_Free;
194     break;
195   case Intrinsic::experimental_gc_statepoint:
196     if ((Idx < 5) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
197       return TTI::TCC_Free;
198     break;
199   }
200   return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
201 }
202 
203 TargetTransformInfo::PopcntSupportKind
204 AArch64TTIImpl::getPopcntSupport(unsigned TyWidth) {
205   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
206   if (TyWidth == 32 || TyWidth == 64)
207     return TTI::PSK_FastHardware;
208   // TODO: AArch64TargetLowering::LowerCTPOP() supports 128bit popcount.
209   return TTI::PSK_Software;
210 }
211 
212 bool AArch64TTIImpl::isWideningInstruction(Type *DstTy, unsigned Opcode,
213                                            ArrayRef<const Value *> Args) {
214 
215   // A helper that returns a vector type from the given type. The number of
216   // elements in type Ty determine the vector width.
217   auto toVectorTy = [&](Type *ArgTy) {
218     return FixedVectorType::get(ArgTy->getScalarType(),
219                                 cast<FixedVectorType>(DstTy)->getNumElements());
220   };
221 
222   // Exit early if DstTy is not a vector type whose elements are at least
223   // 16-bits wide.
224   if (!DstTy->isVectorTy() || DstTy->getScalarSizeInBits() < 16)
225     return false;
226 
227   // Determine if the operation has a widening variant. We consider both the
228   // "long" (e.g., usubl) and "wide" (e.g., usubw) versions of the
229   // instructions.
230   //
231   // TODO: Add additional widening operations (e.g., mul, shl, etc.) once we
232   //       verify that their extending operands are eliminated during code
233   //       generation.
234   switch (Opcode) {
235   case Instruction::Add: // UADDL(2), SADDL(2), UADDW(2), SADDW(2).
236   case Instruction::Sub: // USUBL(2), SSUBL(2), USUBW(2), SSUBW(2).
237     break;
238   default:
239     return false;
240   }
241 
242   // To be a widening instruction (either the "wide" or "long" versions), the
243   // second operand must be a sign- or zero extend having a single user. We
244   // only consider extends having a single user because they may otherwise not
245   // be eliminated.
246   if (Args.size() != 2 ||
247       (!isa<SExtInst>(Args[1]) && !isa<ZExtInst>(Args[1])) ||
248       !Args[1]->hasOneUse())
249     return false;
250   auto *Extend = cast<CastInst>(Args[1]);
251 
252   // Legalize the destination type and ensure it can be used in a widening
253   // operation.
254   auto DstTyL = TLI->getTypeLegalizationCost(DL, DstTy);
255   unsigned DstElTySize = DstTyL.second.getScalarSizeInBits();
256   if (!DstTyL.second.isVector() || DstElTySize != DstTy->getScalarSizeInBits())
257     return false;
258 
259   // Legalize the source type and ensure it can be used in a widening
260   // operation.
261   auto *SrcTy = toVectorTy(Extend->getSrcTy());
262   auto SrcTyL = TLI->getTypeLegalizationCost(DL, SrcTy);
263   unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits();
264   if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits())
265     return false;
266 
267   // Get the total number of vector elements in the legalized types.
268   unsigned NumDstEls = DstTyL.first * DstTyL.second.getVectorNumElements();
269   unsigned NumSrcEls = SrcTyL.first * SrcTyL.second.getVectorNumElements();
270 
271   // Return true if the legalized types have the same number of vector elements
272   // and the destination element type size is twice that of the source type.
273   return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstElTySize;
274 }
275 
276 int AArch64TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
277                                      TTI::CastContextHint CCH,
278                                      TTI::TargetCostKind CostKind,
279                                      const Instruction *I) {
280   int ISD = TLI->InstructionOpcodeToISD(Opcode);
281   assert(ISD && "Invalid opcode");
282 
283   // If the cast is observable, and it is used by a widening instruction (e.g.,
284   // uaddl, saddw, etc.), it may be free.
285   if (I && I->hasOneUse()) {
286     auto *SingleUser = cast<Instruction>(*I->user_begin());
287     SmallVector<const Value *, 4> Operands(SingleUser->operand_values());
288     if (isWideningInstruction(Dst, SingleUser->getOpcode(), Operands)) {
289       // If the cast is the second operand, it is free. We will generate either
290       // a "wide" or "long" version of the widening instruction.
291       if (I == SingleUser->getOperand(1))
292         return 0;
293       // If the cast is not the second operand, it will be free if it looks the
294       // same as the second operand. In this case, we will generate a "long"
295       // version of the widening instruction.
296       if (auto *Cast = dyn_cast<CastInst>(SingleUser->getOperand(1)))
297         if (I->getOpcode() == unsigned(Cast->getOpcode()) &&
298             cast<CastInst>(I)->getSrcTy() == Cast->getSrcTy())
299           return 0;
300     }
301   }
302 
303   // TODO: Allow non-throughput costs that aren't binary.
304   auto AdjustCost = [&CostKind](int Cost) {
305     if (CostKind != TTI::TCK_RecipThroughput)
306       return Cost == 0 ? 0 : 1;
307     return Cost;
308   };
309 
310   EVT SrcTy = TLI->getValueType(DL, Src);
311   EVT DstTy = TLI->getValueType(DL, Dst);
312 
313   if (!SrcTy.isSimple() || !DstTy.isSimple())
314     return AdjustCost(
315         BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
316 
317   static const TypeConversionCostTblEntry
318   ConversionTbl[] = {
319     { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32,  1 },
320     { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64,  0 },
321     { ISD::TRUNCATE, MVT::v8i8,  MVT::v8i32,  3 },
322     { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
323 
324     // The number of shll instructions for the extension.
325     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
326     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
327     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
328     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
329     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
330     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
331     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
332     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
333     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
334     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
335     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
336     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
337     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
338     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
339     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
340     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
341 
342     // LowerVectorINT_TO_FP:
343     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
344     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
345     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
346     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
347     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
348     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
349 
350     // Complex: to v2f32
351     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
352     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
353     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
354     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
355     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
356     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
357 
358     // Complex: to v4f32
359     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8,  4 },
360     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
361     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8,  3 },
362     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
363 
364     // Complex: to v8f32
365     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
366     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
367     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
368     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
369 
370     // Complex: to v16f32
371     { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
372     { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
373 
374     // Complex: to v2f64
375     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
376     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
377     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
378     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
379     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
380     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
381 
382 
383     // LowerVectorFP_TO_INT
384     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f32, 1 },
385     { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
386     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1 },
387     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1 },
388     { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
389     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 },
390 
391     // Complex, from v2f32: legal type is v2i32 (no cost) or v2i64 (1 ext).
392     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 2 },
393     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 1 },
394     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f32, 1 },
395     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 2 },
396     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 1 },
397     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f32, 1 },
398 
399     // Complex, from v4f32: legal type is v4i16, 1 narrowing => ~2
400     { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
401     { ISD::FP_TO_SINT, MVT::v4i8,  MVT::v4f32, 2 },
402     { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
403     { ISD::FP_TO_UINT, MVT::v4i8,  MVT::v4f32, 2 },
404 
405     // Complex, from v2f64: legal type is v2i32, 1 narrowing => ~2.
406     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
407     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f64, 2 },
408     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f64, 2 },
409     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
410     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f64, 2 },
411     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f64, 2 },
412   };
413 
414   if (const auto *Entry = ConvertCostTableLookup(ConversionTbl, ISD,
415                                                  DstTy.getSimpleVT(),
416                                                  SrcTy.getSimpleVT()))
417     return AdjustCost(Entry->Cost);
418 
419   return AdjustCost(
420       BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
421 }
422 
423 int AArch64TTIImpl::getExtractWithExtendCost(unsigned Opcode, Type *Dst,
424                                              VectorType *VecTy,
425                                              unsigned Index) {
426 
427   // Make sure we were given a valid extend opcode.
428   assert((Opcode == Instruction::SExt || Opcode == Instruction::ZExt) &&
429          "Invalid opcode");
430 
431   // We are extending an element we extract from a vector, so the source type
432   // of the extend is the element type of the vector.
433   auto *Src = VecTy->getElementType();
434 
435   // Sign- and zero-extends are for integer types only.
436   assert(isa<IntegerType>(Dst) && isa<IntegerType>(Src) && "Invalid type");
437 
438   // Get the cost for the extract. We compute the cost (if any) for the extend
439   // below.
440   auto Cost = getVectorInstrCost(Instruction::ExtractElement, VecTy, Index);
441 
442   // Legalize the types.
443   auto VecLT = TLI->getTypeLegalizationCost(DL, VecTy);
444   auto DstVT = TLI->getValueType(DL, Dst);
445   auto SrcVT = TLI->getValueType(DL, Src);
446   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
447 
448   // If the resulting type is still a vector and the destination type is legal,
449   // we may get the extension for free. If not, get the default cost for the
450   // extend.
451   if (!VecLT.second.isVector() || !TLI->isTypeLegal(DstVT))
452     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
453                                    CostKind);
454 
455   // The destination type should be larger than the element type. If not, get
456   // the default cost for the extend.
457   if (DstVT.getSizeInBits() < SrcVT.getSizeInBits())
458     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
459                                    CostKind);
460 
461   switch (Opcode) {
462   default:
463     llvm_unreachable("Opcode should be either SExt or ZExt");
464 
465   // For sign-extends, we only need a smov, which performs the extension
466   // automatically.
467   case Instruction::SExt:
468     return Cost;
469 
470   // For zero-extends, the extend is performed automatically by a umov unless
471   // the destination type is i64 and the element type is i8 or i16.
472   case Instruction::ZExt:
473     if (DstVT.getSizeInBits() != 64u || SrcVT.getSizeInBits() == 32u)
474       return Cost;
475   }
476 
477   // If we are unable to perform the extend for free, get the default cost.
478   return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
479                                  CostKind);
480 }
481 
482 unsigned AArch64TTIImpl::getCFInstrCost(unsigned Opcode,
483                                         TTI::TargetCostKind CostKind) {
484   if (CostKind != TTI::TCK_RecipThroughput)
485     return Opcode == Instruction::PHI ? 0 : 1;
486   assert(CostKind == TTI::TCK_RecipThroughput && "unexpected CostKind");
487   // Branches are assumed to be predicted.
488   return 0;
489 }
490 
491 int AArch64TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
492                                        unsigned Index) {
493   assert(Val->isVectorTy() && "This must be a vector type");
494 
495   if (Index != -1U) {
496     // Legalize the type.
497     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
498 
499     // This type is legalized to a scalar type.
500     if (!LT.second.isVector())
501       return 0;
502 
503     // The type may be split. Normalize the index to the new type.
504     unsigned Width = LT.second.getVectorNumElements();
505     Index = Index % Width;
506 
507     // The element at index zero is already inside the vector.
508     if (Index == 0)
509       return 0;
510   }
511 
512   // All other insert/extracts cost this much.
513   return ST->getVectorInsertExtractBaseCost();
514 }
515 
516 int AArch64TTIImpl::getArithmeticInstrCost(
517     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
518     TTI::OperandValueKind Opd1Info,
519     TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo,
520     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
521     const Instruction *CxtI) {
522   // TODO: Handle more cost kinds.
523   if (CostKind != TTI::TCK_RecipThroughput)
524     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
525                                          Opd2Info, Opd1PropInfo,
526                                          Opd2PropInfo, Args, CxtI);
527 
528   // Legalize the type.
529   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
530 
531   // If the instruction is a widening instruction (e.g., uaddl, saddw, etc.),
532   // add in the widening overhead specified by the sub-target. Since the
533   // extends feeding widening instructions are performed automatically, they
534   // aren't present in the generated code and have a zero cost. By adding a
535   // widening overhead here, we attach the total cost of the combined operation
536   // to the widening instruction.
537   int Cost = 0;
538   if (isWideningInstruction(Ty, Opcode, Args))
539     Cost += ST->getWideningBaseCost();
540 
541   int ISD = TLI->InstructionOpcodeToISD(Opcode);
542 
543   switch (ISD) {
544   default:
545     return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
546                                                 Opd2Info,
547                                                 Opd1PropInfo, Opd2PropInfo);
548   case ISD::SDIV:
549     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue &&
550         Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
551       // On AArch64, scalar signed division by constants power-of-two are
552       // normally expanded to the sequence ADD + CMP + SELECT + SRA.
553       // The OperandValue properties many not be same as that of previous
554       // operation; conservatively assume OP_None.
555       Cost += getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
556                                      Opd1Info, Opd2Info,
557                                      TargetTransformInfo::OP_None,
558                                      TargetTransformInfo::OP_None);
559       Cost += getArithmeticInstrCost(Instruction::Sub, Ty, CostKind,
560                                      Opd1Info, Opd2Info,
561                                      TargetTransformInfo::OP_None,
562                                      TargetTransformInfo::OP_None);
563       Cost += getArithmeticInstrCost(Instruction::Select, Ty, CostKind,
564                                      Opd1Info, Opd2Info,
565                                      TargetTransformInfo::OP_None,
566                                      TargetTransformInfo::OP_None);
567       Cost += getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
568                                      Opd1Info, Opd2Info,
569                                      TargetTransformInfo::OP_None,
570                                      TargetTransformInfo::OP_None);
571       return Cost;
572     }
573     LLVM_FALLTHROUGH;
574   case ISD::UDIV:
575     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue) {
576       auto VT = TLI->getValueType(DL, Ty);
577       if (TLI->isOperationLegalOrCustom(ISD::MULHU, VT)) {
578         // Vector signed division by constant are expanded to the
579         // sequence MULHS + ADD/SUB + SRA + SRL + ADD, and unsigned division
580         // to MULHS + SUB + SRL + ADD + SRL.
581         int MulCost = getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
582                                              Opd1Info, Opd2Info,
583                                              TargetTransformInfo::OP_None,
584                                              TargetTransformInfo::OP_None);
585         int AddCost = getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
586                                              Opd1Info, Opd2Info,
587                                              TargetTransformInfo::OP_None,
588                                              TargetTransformInfo::OP_None);
589         int ShrCost = getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
590                                              Opd1Info, Opd2Info,
591                                              TargetTransformInfo::OP_None,
592                                              TargetTransformInfo::OP_None);
593         return MulCost * 2 + AddCost * 2 + ShrCost * 2 + 1;
594       }
595     }
596 
597     Cost += BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
598                                           Opd2Info,
599                                           Opd1PropInfo, Opd2PropInfo);
600     if (Ty->isVectorTy()) {
601       // On AArch64, vector divisions are not supported natively and are
602       // expanded into scalar divisions of each pair of elements.
603       Cost += getArithmeticInstrCost(Instruction::ExtractElement, Ty, CostKind,
604                                      Opd1Info, Opd2Info, Opd1PropInfo,
605                                      Opd2PropInfo);
606       Cost += getArithmeticInstrCost(Instruction::InsertElement, Ty, CostKind,
607                                      Opd1Info, Opd2Info, Opd1PropInfo,
608                                      Opd2PropInfo);
609       // TODO: if one of the arguments is scalar, then it's not necessary to
610       // double the cost of handling the vector elements.
611       Cost += Cost;
612     }
613     return Cost;
614 
615   case ISD::ADD:
616   case ISD::MUL:
617   case ISD::XOR:
618   case ISD::OR:
619   case ISD::AND:
620     // These nodes are marked as 'custom' for combining purposes only.
621     // We know that they are legal. See LowerAdd in ISelLowering.
622     return (Cost + 1) * LT.first;
623 
624   case ISD::FADD:
625     // These nodes are marked as 'custom' just to lower them to SVE.
626     // We know said lowering will incur no additional cost.
627     if (isa<FixedVectorType>(Ty) && !Ty->getScalarType()->isFP128Ty())
628       return (Cost + 2) * LT.first;
629 
630     return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
631                                                 Opd2Info,
632                                                 Opd1PropInfo, Opd2PropInfo);
633   }
634 }
635 
636 int AArch64TTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
637                                               const SCEV *Ptr) {
638   // Address computations in vectorized code with non-consecutive addresses will
639   // likely result in more instructions compared to scalar code where the
640   // computation can more often be merged into the index mode. The resulting
641   // extra micro-ops can significantly decrease throughput.
642   unsigned NumVectorInstToHideOverhead = 10;
643   int MaxMergeDistance = 64;
644 
645   if (Ty->isVectorTy() && SE &&
646       !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
647     return NumVectorInstToHideOverhead;
648 
649   // In many cases the address computation is not merged into the instruction
650   // addressing mode.
651   return 1;
652 }
653 
654 int AArch64TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
655                                        Type *CondTy,
656                                        TTI::TargetCostKind CostKind,
657                                        const Instruction *I) {
658   // TODO: Handle other cost kinds.
659   if (CostKind != TTI::TCK_RecipThroughput)
660     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, I);
661 
662   int ISD = TLI->InstructionOpcodeToISD(Opcode);
663   // We don't lower some vector selects well that are wider than the register
664   // width.
665   if (ValTy->isVectorTy() && ISD == ISD::SELECT) {
666     // We would need this many instructions to hide the scalarization happening.
667     const int AmortizationCost = 20;
668     static const TypeConversionCostTblEntry
669     VectorSelectTbl[] = {
670       { ISD::SELECT, MVT::v16i1, MVT::v16i16, 16 },
671       { ISD::SELECT, MVT::v8i1, MVT::v8i32, 8 },
672       { ISD::SELECT, MVT::v16i1, MVT::v16i32, 16 },
673       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost },
674       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost },
675       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost }
676     };
677 
678     EVT SelCondTy = TLI->getValueType(DL, CondTy);
679     EVT SelValTy = TLI->getValueType(DL, ValTy);
680     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
681       if (const auto *Entry = ConvertCostTableLookup(VectorSelectTbl, ISD,
682                                                      SelCondTy.getSimpleVT(),
683                                                      SelValTy.getSimpleVT()))
684         return Entry->Cost;
685     }
686   }
687   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, I);
688 }
689 
690 AArch64TTIImpl::TTI::MemCmpExpansionOptions
691 AArch64TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
692   TTI::MemCmpExpansionOptions Options;
693   if (ST->requiresStrictAlign()) {
694     // TODO: Add cost modeling for strict align. Misaligned loads expand to
695     // a bunch of instructions when strict align is enabled.
696     return Options;
697   }
698   Options.AllowOverlappingLoads = true;
699   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
700   Options.NumLoadsPerBlock = Options.MaxNumLoads;
701   // TODO: Though vector loads usually perform well on AArch64, in some targets
702   // they may wake up the FP unit, which raises the power consumption.  Perhaps
703   // they could be used with no holds barred (-O3).
704   Options.LoadSizes = {8, 4, 2, 1};
705   return Options;
706 }
707 
708 int AArch64TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Ty,
709                                     MaybeAlign Alignment, unsigned AddressSpace,
710                                     TTI::TargetCostKind CostKind,
711                                     const Instruction *I) {
712   // TODO: Handle other cost kinds.
713   if (CostKind != TTI::TCK_RecipThroughput)
714     return 1;
715 
716   // Type legalization can't handle structs
717   if (TLI->getValueType(DL, Ty,  true) == MVT::Other)
718     return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace,
719                                   CostKind);
720 
721   auto LT = TLI->getTypeLegalizationCost(DL, Ty);
722 
723   if (ST->isMisaligned128StoreSlow() && Opcode == Instruction::Store &&
724       LT.second.is128BitVector() && (!Alignment || *Alignment < Align(16))) {
725     // Unaligned stores are extremely inefficient. We don't split all
726     // unaligned 128-bit stores because the negative impact that has shown in
727     // practice on inlined block copy code.
728     // We make such stores expensive so that we will only vectorize if there
729     // are 6 other instructions getting vectorized.
730     const int AmortizationCost = 6;
731 
732     return LT.first * 2 * AmortizationCost;
733   }
734 
735   if (Ty->isVectorTy() &&
736       cast<VectorType>(Ty)->getElementType()->isIntegerTy(8)) {
737     unsigned ProfitableNumElements;
738     if (Opcode == Instruction::Store)
739       // We use a custom trunc store lowering so v.4b should be profitable.
740       ProfitableNumElements = 4;
741     else
742       // We scalarize the loads because there is not v.4b register and we
743       // have to promote the elements to v.2.
744       ProfitableNumElements = 8;
745 
746     if (cast<FixedVectorType>(Ty)->getNumElements() < ProfitableNumElements) {
747       unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements();
748       unsigned NumVectorizableInstsToAmortize = NumVecElts * 2;
749       // We generate 2 instructions per vector element.
750       return NumVectorizableInstsToAmortize * NumVecElts * 2;
751     }
752   }
753 
754   return LT.first;
755 }
756 
757 int AArch64TTIImpl::getInterleavedMemoryOpCost(
758     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
759     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
760     bool UseMaskForCond, bool UseMaskForGaps) {
761   assert(Factor >= 2 && "Invalid interleave factor");
762   auto *VecVTy = cast<FixedVectorType>(VecTy);
763 
764   if (!UseMaskForCond && !UseMaskForGaps &&
765       Factor <= TLI->getMaxSupportedInterleaveFactor()) {
766     unsigned NumElts = VecVTy->getNumElements();
767     auto *SubVecTy =
768         FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
769 
770     // ldN/stN only support legal vector types of size 64 or 128 in bits.
771     // Accesses having vector types that are a multiple of 128 bits can be
772     // matched to more than one ldN/stN instruction.
773     if (NumElts % Factor == 0 &&
774         TLI->isLegalInterleavedAccessType(SubVecTy, DL))
775       return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL);
776   }
777 
778   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
779                                            Alignment, AddressSpace, CostKind,
780                                            UseMaskForCond, UseMaskForGaps);
781 }
782 
783 int AArch64TTIImpl::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) {
784   int Cost = 0;
785   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
786   for (auto *I : Tys) {
787     if (!I->isVectorTy())
788       continue;
789     if (I->getScalarSizeInBits() * cast<FixedVectorType>(I)->getNumElements() ==
790         128)
791       Cost += getMemoryOpCost(Instruction::Store, I, Align(128), 0, CostKind) +
792               getMemoryOpCost(Instruction::Load, I, Align(128), 0, CostKind);
793   }
794   return Cost;
795 }
796 
797 unsigned AArch64TTIImpl::getMaxInterleaveFactor(unsigned VF) {
798   return ST->getMaxInterleaveFactor();
799 }
800 
801 // For Falkor, we want to avoid having too many strided loads in a loop since
802 // that can exhaust the HW prefetcher resources.  We adjust the unroller
803 // MaxCount preference below to attempt to ensure unrolling doesn't create too
804 // many strided loads.
805 static void
806 getFalkorUnrollingPreferences(Loop *L, ScalarEvolution &SE,
807                               TargetTransformInfo::UnrollingPreferences &UP) {
808   enum { MaxStridedLoads = 7 };
809   auto countStridedLoads = [](Loop *L, ScalarEvolution &SE) {
810     int StridedLoads = 0;
811     // FIXME? We could make this more precise by looking at the CFG and
812     // e.g. not counting loads in each side of an if-then-else diamond.
813     for (const auto BB : L->blocks()) {
814       for (auto &I : *BB) {
815         LoadInst *LMemI = dyn_cast<LoadInst>(&I);
816         if (!LMemI)
817           continue;
818 
819         Value *PtrValue = LMemI->getPointerOperand();
820         if (L->isLoopInvariant(PtrValue))
821           continue;
822 
823         const SCEV *LSCEV = SE.getSCEV(PtrValue);
824         const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
825         if (!LSCEVAddRec || !LSCEVAddRec->isAffine())
826           continue;
827 
828         // FIXME? We could take pairing of unrolled load copies into account
829         // by looking at the AddRec, but we would probably have to limit this
830         // to loops with no stores or other memory optimization barriers.
831         ++StridedLoads;
832         // We've seen enough strided loads that seeing more won't make a
833         // difference.
834         if (StridedLoads > MaxStridedLoads / 2)
835           return StridedLoads;
836       }
837     }
838     return StridedLoads;
839   };
840 
841   int StridedLoads = countStridedLoads(L, SE);
842   LLVM_DEBUG(dbgs() << "falkor-hwpf: detected " << StridedLoads
843                     << " strided loads\n");
844   // Pick the largest power of 2 unroll count that won't result in too many
845   // strided loads.
846   if (StridedLoads) {
847     UP.MaxCount = 1 << Log2_32(MaxStridedLoads / StridedLoads);
848     LLVM_DEBUG(dbgs() << "falkor-hwpf: setting unroll MaxCount to "
849                       << UP.MaxCount << '\n');
850   }
851 }
852 
853 void AArch64TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
854                                              TTI::UnrollingPreferences &UP) {
855   // Enable partial unrolling and runtime unrolling.
856   BaseT::getUnrollingPreferences(L, SE, UP);
857 
858   // For inner loop, it is more likely to be a hot one, and the runtime check
859   // can be promoted out from LICM pass, so the overhead is less, let's try
860   // a larger threshold to unroll more loops.
861   if (L->getLoopDepth() > 1)
862     UP.PartialThreshold *= 2;
863 
864   // Disable partial & runtime unrolling on -Os.
865   UP.PartialOptSizeThreshold = 0;
866 
867   if (ST->getProcFamily() == AArch64Subtarget::Falkor &&
868       EnableFalkorHWPFUnrollFix)
869     getFalkorUnrollingPreferences(L, SE, UP);
870 }
871 
872 void AArch64TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
873                                            TTI::PeelingPreferences &PP) {
874   BaseT::getPeelingPreferences(L, SE, PP);
875 }
876 
877 Value *AArch64TTIImpl::getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
878                                                          Type *ExpectedType) {
879   switch (Inst->getIntrinsicID()) {
880   default:
881     return nullptr;
882   case Intrinsic::aarch64_neon_st2:
883   case Intrinsic::aarch64_neon_st3:
884   case Intrinsic::aarch64_neon_st4: {
885     // Create a struct type
886     StructType *ST = dyn_cast<StructType>(ExpectedType);
887     if (!ST)
888       return nullptr;
889     unsigned NumElts = Inst->getNumArgOperands() - 1;
890     if (ST->getNumElements() != NumElts)
891       return nullptr;
892     for (unsigned i = 0, e = NumElts; i != e; ++i) {
893       if (Inst->getArgOperand(i)->getType() != ST->getElementType(i))
894         return nullptr;
895     }
896     Value *Res = UndefValue::get(ExpectedType);
897     IRBuilder<> Builder(Inst);
898     for (unsigned i = 0, e = NumElts; i != e; ++i) {
899       Value *L = Inst->getArgOperand(i);
900       Res = Builder.CreateInsertValue(Res, L, i);
901     }
902     return Res;
903   }
904   case Intrinsic::aarch64_neon_ld2:
905   case Intrinsic::aarch64_neon_ld3:
906   case Intrinsic::aarch64_neon_ld4:
907     if (Inst->getType() == ExpectedType)
908       return Inst;
909     return nullptr;
910   }
911 }
912 
913 bool AArch64TTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
914                                         MemIntrinsicInfo &Info) {
915   switch (Inst->getIntrinsicID()) {
916   default:
917     break;
918   case Intrinsic::aarch64_neon_ld2:
919   case Intrinsic::aarch64_neon_ld3:
920   case Intrinsic::aarch64_neon_ld4:
921     Info.ReadMem = true;
922     Info.WriteMem = false;
923     Info.PtrVal = Inst->getArgOperand(0);
924     break;
925   case Intrinsic::aarch64_neon_st2:
926   case Intrinsic::aarch64_neon_st3:
927   case Intrinsic::aarch64_neon_st4:
928     Info.ReadMem = false;
929     Info.WriteMem = true;
930     Info.PtrVal = Inst->getArgOperand(Inst->getNumArgOperands() - 1);
931     break;
932   }
933 
934   switch (Inst->getIntrinsicID()) {
935   default:
936     return false;
937   case Intrinsic::aarch64_neon_ld2:
938   case Intrinsic::aarch64_neon_st2:
939     Info.MatchingId = VECTOR_LDST_TWO_ELEMENTS;
940     break;
941   case Intrinsic::aarch64_neon_ld3:
942   case Intrinsic::aarch64_neon_st3:
943     Info.MatchingId = VECTOR_LDST_THREE_ELEMENTS;
944     break;
945   case Intrinsic::aarch64_neon_ld4:
946   case Intrinsic::aarch64_neon_st4:
947     Info.MatchingId = VECTOR_LDST_FOUR_ELEMENTS;
948     break;
949   }
950   return true;
951 }
952 
953 /// See if \p I should be considered for address type promotion. We check if \p
954 /// I is a sext with right type and used in memory accesses. If it used in a
955 /// "complex" getelementptr, we allow it to be promoted without finding other
956 /// sext instructions that sign extended the same initial value. A getelementptr
957 /// is considered as "complex" if it has more than 2 operands.
958 bool AArch64TTIImpl::shouldConsiderAddressTypePromotion(
959     const Instruction &I, bool &AllowPromotionWithoutCommonHeader) {
960   bool Considerable = false;
961   AllowPromotionWithoutCommonHeader = false;
962   if (!isa<SExtInst>(&I))
963     return false;
964   Type *ConsideredSExtType =
965       Type::getInt64Ty(I.getParent()->getParent()->getContext());
966   if (I.getType() != ConsideredSExtType)
967     return false;
968   // See if the sext is the one with the right type and used in at least one
969   // GetElementPtrInst.
970   for (const User *U : I.users()) {
971     if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
972       Considerable = true;
973       // A getelementptr is considered as "complex" if it has more than 2
974       // operands. We will promote a SExt used in such complex GEP as we
975       // expect some computation to be merged if they are done on 64 bits.
976       if (GEPInst->getNumOperands() > 2) {
977         AllowPromotionWithoutCommonHeader = true;
978         break;
979       }
980     }
981   }
982   return Considerable;
983 }
984 
985 bool AArch64TTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
986                                            TTI::ReductionFlags Flags) const {
987   auto *VTy = cast<VectorType>(Ty);
988   unsigned ScalarBits = Ty->getScalarSizeInBits();
989   switch (Opcode) {
990   case Instruction::FAdd:
991   case Instruction::FMul:
992   case Instruction::And:
993   case Instruction::Or:
994   case Instruction::Xor:
995   case Instruction::Mul:
996     return false;
997   case Instruction::Add:
998     return ScalarBits * cast<FixedVectorType>(VTy)->getNumElements() >= 128;
999   case Instruction::ICmp:
1000     return (ScalarBits < 64) &&
1001            (ScalarBits * cast<FixedVectorType>(VTy)->getNumElements() >= 128);
1002   case Instruction::FCmp:
1003     return Flags.NoNaN;
1004   default:
1005     llvm_unreachable("Unhandled reduction opcode");
1006   }
1007   return false;
1008 }
1009 
1010 int AArch64TTIImpl::getArithmeticReductionCost(unsigned Opcode,
1011                                                VectorType *ValTy,
1012                                                bool IsPairwiseForm,
1013                                                TTI::TargetCostKind CostKind) {
1014 
1015   if (IsPairwiseForm)
1016     return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
1017                                              CostKind);
1018 
1019   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
1020   MVT MTy = LT.second;
1021   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1022   assert(ISD && "Invalid opcode");
1023 
1024   // Horizontal adds can use the 'addv' instruction. We model the cost of these
1025   // instructions as normal vector adds. This is the only arithmetic vector
1026   // reduction operation for which we have an instruction.
1027   static const CostTblEntry CostTblNoPairwise[]{
1028       {ISD::ADD, MVT::v8i8,  1},
1029       {ISD::ADD, MVT::v16i8, 1},
1030       {ISD::ADD, MVT::v4i16, 1},
1031       {ISD::ADD, MVT::v8i16, 1},
1032       {ISD::ADD, MVT::v4i32, 1},
1033   };
1034 
1035   if (const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy))
1036     return LT.first * Entry->Cost;
1037 
1038   return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
1039                                            CostKind);
1040 }
1041 
1042 int AArch64TTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
1043                                    int Index, VectorType *SubTp) {
1044   if (Kind == TTI::SK_Broadcast || Kind == TTI::SK_Transpose ||
1045       Kind == TTI::SK_Select || Kind == TTI::SK_PermuteSingleSrc) {
1046     static const CostTblEntry ShuffleTbl[] = {
1047       // Broadcast shuffle kinds can be performed with 'dup'.
1048       { TTI::SK_Broadcast, MVT::v8i8,  1 },
1049       { TTI::SK_Broadcast, MVT::v16i8, 1 },
1050       { TTI::SK_Broadcast, MVT::v4i16, 1 },
1051       { TTI::SK_Broadcast, MVT::v8i16, 1 },
1052       { TTI::SK_Broadcast, MVT::v2i32, 1 },
1053       { TTI::SK_Broadcast, MVT::v4i32, 1 },
1054       { TTI::SK_Broadcast, MVT::v2i64, 1 },
1055       { TTI::SK_Broadcast, MVT::v2f32, 1 },
1056       { TTI::SK_Broadcast, MVT::v4f32, 1 },
1057       { TTI::SK_Broadcast, MVT::v2f64, 1 },
1058       // Transpose shuffle kinds can be performed with 'trn1/trn2' and
1059       // 'zip1/zip2' instructions.
1060       { TTI::SK_Transpose, MVT::v8i8,  1 },
1061       { TTI::SK_Transpose, MVT::v16i8, 1 },
1062       { TTI::SK_Transpose, MVT::v4i16, 1 },
1063       { TTI::SK_Transpose, MVT::v8i16, 1 },
1064       { TTI::SK_Transpose, MVT::v2i32, 1 },
1065       { TTI::SK_Transpose, MVT::v4i32, 1 },
1066       { TTI::SK_Transpose, MVT::v2i64, 1 },
1067       { TTI::SK_Transpose, MVT::v2f32, 1 },
1068       { TTI::SK_Transpose, MVT::v4f32, 1 },
1069       { TTI::SK_Transpose, MVT::v2f64, 1 },
1070       // Select shuffle kinds.
1071       // TODO: handle vXi8/vXi16.
1072       { TTI::SK_Select, MVT::v2i32, 1 }, // mov.
1073       { TTI::SK_Select, MVT::v4i32, 2 }, // rev+trn (or similar).
1074       { TTI::SK_Select, MVT::v2i64, 1 }, // mov.
1075       { TTI::SK_Select, MVT::v2f32, 1 }, // mov.
1076       { TTI::SK_Select, MVT::v4f32, 2 }, // rev+trn (or similar).
1077       { TTI::SK_Select, MVT::v2f64, 1 }, // mov.
1078       // PermuteSingleSrc shuffle kinds.
1079       // TODO: handle vXi8/vXi16.
1080       { TTI::SK_PermuteSingleSrc, MVT::v2i32, 1 }, // mov.
1081       { TTI::SK_PermuteSingleSrc, MVT::v4i32, 3 }, // perfectshuffle worst case.
1082       { TTI::SK_PermuteSingleSrc, MVT::v2i64, 1 }, // mov.
1083       { TTI::SK_PermuteSingleSrc, MVT::v2f32, 1 }, // mov.
1084       { TTI::SK_PermuteSingleSrc, MVT::v4f32, 3 }, // perfectshuffle worst case.
1085       { TTI::SK_PermuteSingleSrc, MVT::v2f64, 1 }, // mov.
1086     };
1087     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1088     if (const auto *Entry = CostTableLookup(ShuffleTbl, Kind, LT.second))
1089       return LT.first * Entry->Cost;
1090   }
1091 
1092   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
1093 }
1094