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 "AArch64TargetTransformInfo.h"
10 #include "AArch64ExpandImm.h"
11 #include "AArch64PerfectShuffle.h"
12 #include "MCTargetDesc/AArch64AddressingModes.h"
13 #include "llvm/Analysis/IVDescriptors.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/Analysis/TargetTransformInfo.h"
16 #include "llvm/CodeGen/BasicTTIImpl.h"
17 #include "llvm/CodeGen/CostTable.h"
18 #include "llvm/CodeGen/TargetLowering.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/IR/IntrinsicsAArch64.h"
22 #include "llvm/IR/PatternMatch.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Transforms/InstCombine/InstCombiner.h"
25 #include <algorithm>
26 using namespace llvm;
27 using namespace llvm::PatternMatch;
28 
29 #define DEBUG_TYPE "aarch64tti"
30 
31 static cl::opt<bool> EnableFalkorHWPFUnrollFix("enable-falkor-hwpf-unroll-fix",
32                                                cl::init(true), cl::Hidden);
33 
34 static cl::opt<unsigned> SVEGatherOverhead("sve-gather-overhead", cl::init(10),
35                                            cl::Hidden);
36 
37 static cl::opt<unsigned> SVEScatterOverhead("sve-scatter-overhead",
38                                             cl::init(10), cl::Hidden);
39 
40 bool AArch64TTIImpl::areInlineCompatible(const Function *Caller,
41                                          const Function *Callee) const {
42   const TargetMachine &TM = getTLI()->getTargetMachine();
43 
44   const FeatureBitset &CallerBits =
45       TM.getSubtargetImpl(*Caller)->getFeatureBits();
46   const FeatureBitset &CalleeBits =
47       TM.getSubtargetImpl(*Callee)->getFeatureBits();
48 
49   // Inline a callee if its target-features are a subset of the callers
50   // target-features.
51   return (CallerBits & CalleeBits) == CalleeBits;
52 }
53 
54 /// Calculate the cost of materializing a 64-bit value. This helper
55 /// method might only calculate a fraction of a larger immediate. Therefore it
56 /// is valid to return a cost of ZERO.
57 InstructionCost AArch64TTIImpl::getIntImmCost(int64_t Val) {
58   // Check if the immediate can be encoded within an instruction.
59   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, 64))
60     return 0;
61 
62   if (Val < 0)
63     Val = ~Val;
64 
65   // Calculate how many moves we will need to materialize this constant.
66   SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
67   AArch64_IMM::expandMOVImm(Val, 64, Insn);
68   return Insn.size();
69 }
70 
71 /// Calculate the cost of materializing the given constant.
72 InstructionCost AArch64TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
73                                               TTI::TargetCostKind CostKind) {
74   assert(Ty->isIntegerTy());
75 
76   unsigned BitSize = Ty->getPrimitiveSizeInBits();
77   if (BitSize == 0)
78     return ~0U;
79 
80   // Sign-extend all constants to a multiple of 64-bit.
81   APInt ImmVal = Imm;
82   if (BitSize & 0x3f)
83     ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
84 
85   // Split the constant into 64-bit chunks and calculate the cost for each
86   // chunk.
87   InstructionCost Cost = 0;
88   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
89     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
90     int64_t Val = Tmp.getSExtValue();
91     Cost += getIntImmCost(Val);
92   }
93   // We need at least one instruction to materialze the constant.
94   return std::max<InstructionCost>(1, Cost);
95 }
96 
97 InstructionCost AArch64TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
98                                                   const APInt &Imm, Type *Ty,
99                                                   TTI::TargetCostKind CostKind,
100                                                   Instruction *Inst) {
101   assert(Ty->isIntegerTy());
102 
103   unsigned BitSize = Ty->getPrimitiveSizeInBits();
104   // There is no cost model for constants with a bit size of 0. Return TCC_Free
105   // here, so that constant hoisting will ignore this constant.
106   if (BitSize == 0)
107     return TTI::TCC_Free;
108 
109   unsigned ImmIdx = ~0U;
110   switch (Opcode) {
111   default:
112     return TTI::TCC_Free;
113   case Instruction::GetElementPtr:
114     // Always hoist the base address of a GetElementPtr.
115     if (Idx == 0)
116       return 2 * TTI::TCC_Basic;
117     return TTI::TCC_Free;
118   case Instruction::Store:
119     ImmIdx = 0;
120     break;
121   case Instruction::Add:
122   case Instruction::Sub:
123   case Instruction::Mul:
124   case Instruction::UDiv:
125   case Instruction::SDiv:
126   case Instruction::URem:
127   case Instruction::SRem:
128   case Instruction::And:
129   case Instruction::Or:
130   case Instruction::Xor:
131   case Instruction::ICmp:
132     ImmIdx = 1;
133     break;
134   // Always return TCC_Free for the shift value of a shift instruction.
135   case Instruction::Shl:
136   case Instruction::LShr:
137   case Instruction::AShr:
138     if (Idx == 1)
139       return TTI::TCC_Free;
140     break;
141   case Instruction::Trunc:
142   case Instruction::ZExt:
143   case Instruction::SExt:
144   case Instruction::IntToPtr:
145   case Instruction::PtrToInt:
146   case Instruction::BitCast:
147   case Instruction::PHI:
148   case Instruction::Call:
149   case Instruction::Select:
150   case Instruction::Ret:
151   case Instruction::Load:
152     break;
153   }
154 
155   if (Idx == ImmIdx) {
156     int NumConstants = (BitSize + 63) / 64;
157     InstructionCost Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
158     return (Cost <= NumConstants * TTI::TCC_Basic)
159                ? static_cast<int>(TTI::TCC_Free)
160                : Cost;
161   }
162   return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
163 }
164 
165 InstructionCost
166 AArch64TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
167                                     const APInt &Imm, Type *Ty,
168                                     TTI::TargetCostKind CostKind) {
169   assert(Ty->isIntegerTy());
170 
171   unsigned BitSize = Ty->getPrimitiveSizeInBits();
172   // There is no cost model for constants with a bit size of 0. Return TCC_Free
173   // here, so that constant hoisting will ignore this constant.
174   if (BitSize == 0)
175     return TTI::TCC_Free;
176 
177   // Most (all?) AArch64 intrinsics do not support folding immediates into the
178   // selected instruction, so we compute the materialization cost for the
179   // immediate directly.
180   if (IID >= Intrinsic::aarch64_addg && IID <= Intrinsic::aarch64_udiv)
181     return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
182 
183   switch (IID) {
184   default:
185     return TTI::TCC_Free;
186   case Intrinsic::sadd_with_overflow:
187   case Intrinsic::uadd_with_overflow:
188   case Intrinsic::ssub_with_overflow:
189   case Intrinsic::usub_with_overflow:
190   case Intrinsic::smul_with_overflow:
191   case Intrinsic::umul_with_overflow:
192     if (Idx == 1) {
193       int NumConstants = (BitSize + 63) / 64;
194       InstructionCost Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
195       return (Cost <= NumConstants * TTI::TCC_Basic)
196                  ? static_cast<int>(TTI::TCC_Free)
197                  : Cost;
198     }
199     break;
200   case Intrinsic::experimental_stackmap:
201     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
202       return TTI::TCC_Free;
203     break;
204   case Intrinsic::experimental_patchpoint_void:
205   case Intrinsic::experimental_patchpoint_i64:
206     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
207       return TTI::TCC_Free;
208     break;
209   case Intrinsic::experimental_gc_statepoint:
210     if ((Idx < 5) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
211       return TTI::TCC_Free;
212     break;
213   }
214   return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
215 }
216 
217 TargetTransformInfo::PopcntSupportKind
218 AArch64TTIImpl::getPopcntSupport(unsigned TyWidth) {
219   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
220   if (TyWidth == 32 || TyWidth == 64)
221     return TTI::PSK_FastHardware;
222   // TODO: AArch64TargetLowering::LowerCTPOP() supports 128bit popcount.
223   return TTI::PSK_Software;
224 }
225 
226 InstructionCost
227 AArch64TTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
228                                       TTI::TargetCostKind CostKind) {
229   auto *RetTy = ICA.getReturnType();
230   switch (ICA.getID()) {
231   case Intrinsic::umin:
232   case Intrinsic::umax:
233   case Intrinsic::smin:
234   case Intrinsic::smax: {
235     static const auto ValidMinMaxTys = {MVT::v8i8,  MVT::v16i8, MVT::v4i16,
236                                         MVT::v8i16, MVT::v2i32, MVT::v4i32};
237     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
238     // v2i64 types get converted to cmp+bif hence the cost of 2
239     if (LT.second == MVT::v2i64)
240       return LT.first * 2;
241     if (any_of(ValidMinMaxTys, [&LT](MVT M) { return M == LT.second; }))
242       return LT.first;
243     break;
244   }
245   case Intrinsic::sadd_sat:
246   case Intrinsic::ssub_sat:
247   case Intrinsic::uadd_sat:
248   case Intrinsic::usub_sat: {
249     static const auto ValidSatTys = {MVT::v8i8,  MVT::v16i8, MVT::v4i16,
250                                      MVT::v8i16, MVT::v2i32, MVT::v4i32,
251                                      MVT::v2i64};
252     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
253     // This is a base cost of 1 for the vadd, plus 3 extract shifts if we
254     // need to extend the type, as it uses shr(qadd(shl, shl)).
255     unsigned Instrs =
256         LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits() ? 1 : 4;
257     if (any_of(ValidSatTys, [&LT](MVT M) { return M == LT.second; }))
258       return LT.first * Instrs;
259     break;
260   }
261   case Intrinsic::abs: {
262     static const auto ValidAbsTys = {MVT::v8i8,  MVT::v16i8, MVT::v4i16,
263                                      MVT::v8i16, MVT::v2i32, MVT::v4i32,
264                                      MVT::v2i64};
265     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
266     if (any_of(ValidAbsTys, [&LT](MVT M) { return M == LT.second; }))
267       return LT.first;
268     break;
269   }
270   case Intrinsic::experimental_stepvector: {
271     InstructionCost Cost = 1; // Cost of the `index' instruction
272     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
273     // Legalisation of illegal vectors involves an `index' instruction plus
274     // (LT.first - 1) vector adds.
275     if (LT.first > 1) {
276       Type *LegalVTy = EVT(LT.second).getTypeForEVT(RetTy->getContext());
277       InstructionCost AddCost =
278           getArithmeticInstrCost(Instruction::Add, LegalVTy, CostKind);
279       Cost += AddCost * (LT.first - 1);
280     }
281     return Cost;
282   }
283   case Intrinsic::bitreverse: {
284     static const CostTblEntry BitreverseTbl[] = {
285         {Intrinsic::bitreverse, MVT::i32, 1},
286         {Intrinsic::bitreverse, MVT::i64, 1},
287         {Intrinsic::bitreverse, MVT::v8i8, 1},
288         {Intrinsic::bitreverse, MVT::v16i8, 1},
289         {Intrinsic::bitreverse, MVT::v4i16, 2},
290         {Intrinsic::bitreverse, MVT::v8i16, 2},
291         {Intrinsic::bitreverse, MVT::v2i32, 2},
292         {Intrinsic::bitreverse, MVT::v4i32, 2},
293         {Intrinsic::bitreverse, MVT::v1i64, 2},
294         {Intrinsic::bitreverse, MVT::v2i64, 2},
295     };
296     const auto LegalisationCost = TLI->getTypeLegalizationCost(DL, RetTy);
297     const auto *Entry =
298         CostTableLookup(BitreverseTbl, ICA.getID(), LegalisationCost.second);
299     if (Entry) {
300       // Cost Model is using the legal type(i32) that i8 and i16 will be
301       // converted to +1 so that we match the actual lowering cost
302       if (TLI->getValueType(DL, RetTy, true) == MVT::i8 ||
303           TLI->getValueType(DL, RetTy, true) == MVT::i16)
304         return LegalisationCost.first * Entry->Cost + 1;
305 
306       return LegalisationCost.first * Entry->Cost;
307     }
308     break;
309   }
310   case Intrinsic::ctpop: {
311     static const CostTblEntry CtpopCostTbl[] = {
312         {ISD::CTPOP, MVT::v2i64, 4},
313         {ISD::CTPOP, MVT::v4i32, 3},
314         {ISD::CTPOP, MVT::v8i16, 2},
315         {ISD::CTPOP, MVT::v16i8, 1},
316         {ISD::CTPOP, MVT::i64,   4},
317         {ISD::CTPOP, MVT::v2i32, 3},
318         {ISD::CTPOP, MVT::v4i16, 2},
319         {ISD::CTPOP, MVT::v8i8,  1},
320         {ISD::CTPOP, MVT::i32,   5},
321     };
322     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
323     MVT MTy = LT.second;
324     if (const auto *Entry = CostTableLookup(CtpopCostTbl, ISD::CTPOP, MTy)) {
325       // Extra cost of +1 when illegal vector types are legalized by promoting
326       // the integer type.
327       int ExtraCost = MTy.isVector() && MTy.getScalarSizeInBits() !=
328                                             RetTy->getScalarSizeInBits()
329                           ? 1
330                           : 0;
331       return LT.first * Entry->Cost + ExtraCost;
332     }
333     break;
334   }
335   case Intrinsic::sadd_with_overflow:
336   case Intrinsic::uadd_with_overflow:
337   case Intrinsic::ssub_with_overflow:
338   case Intrinsic::usub_with_overflow:
339   case Intrinsic::smul_with_overflow:
340   case Intrinsic::umul_with_overflow: {
341     static const CostTblEntry WithOverflowCostTbl[] = {
342         {Intrinsic::sadd_with_overflow, MVT::i8, 3},
343         {Intrinsic::uadd_with_overflow, MVT::i8, 3},
344         {Intrinsic::sadd_with_overflow, MVT::i16, 3},
345         {Intrinsic::uadd_with_overflow, MVT::i16, 3},
346         {Intrinsic::sadd_with_overflow, MVT::i32, 1},
347         {Intrinsic::uadd_with_overflow, MVT::i32, 1},
348         {Intrinsic::sadd_with_overflow, MVT::i64, 1},
349         {Intrinsic::uadd_with_overflow, MVT::i64, 1},
350         {Intrinsic::ssub_with_overflow, MVT::i8, 3},
351         {Intrinsic::usub_with_overflow, MVT::i8, 3},
352         {Intrinsic::ssub_with_overflow, MVT::i16, 3},
353         {Intrinsic::usub_with_overflow, MVT::i16, 3},
354         {Intrinsic::ssub_with_overflow, MVT::i32, 1},
355         {Intrinsic::usub_with_overflow, MVT::i32, 1},
356         {Intrinsic::ssub_with_overflow, MVT::i64, 1},
357         {Intrinsic::usub_with_overflow, MVT::i64, 1},
358         {Intrinsic::smul_with_overflow, MVT::i8, 5},
359         {Intrinsic::umul_with_overflow, MVT::i8, 4},
360         {Intrinsic::smul_with_overflow, MVT::i16, 5},
361         {Intrinsic::umul_with_overflow, MVT::i16, 4},
362         {Intrinsic::smul_with_overflow, MVT::i32, 2}, // eg umull;tst
363         {Intrinsic::umul_with_overflow, MVT::i32, 2}, // eg umull;cmp sxtw
364         {Intrinsic::smul_with_overflow, MVT::i64, 3}, // eg mul;smulh;cmp
365         {Intrinsic::umul_with_overflow, MVT::i64, 3}, // eg mul;umulh;cmp asr
366     };
367     EVT MTy = TLI->getValueType(DL, RetTy->getContainedType(0), true);
368     if (MTy.isSimple())
369       if (const auto *Entry = CostTableLookup(WithOverflowCostTbl, ICA.getID(),
370                                               MTy.getSimpleVT()))
371         return Entry->Cost;
372     break;
373   }
374   default:
375     break;
376   }
377   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
378 }
379 
380 /// The function will remove redundant reinterprets casting in the presence
381 /// of the control flow
382 static Optional<Instruction *> processPhiNode(InstCombiner &IC,
383                                               IntrinsicInst &II) {
384   SmallVector<Instruction *, 32> Worklist;
385   auto RequiredType = II.getType();
386 
387   auto *PN = dyn_cast<PHINode>(II.getArgOperand(0));
388   assert(PN && "Expected Phi Node!");
389 
390   // Don't create a new Phi unless we can remove the old one.
391   if (!PN->hasOneUse())
392     return None;
393 
394   for (Value *IncValPhi : PN->incoming_values()) {
395     auto *Reinterpret = dyn_cast<IntrinsicInst>(IncValPhi);
396     if (!Reinterpret ||
397         Reinterpret->getIntrinsicID() !=
398             Intrinsic::aarch64_sve_convert_to_svbool ||
399         RequiredType != Reinterpret->getArgOperand(0)->getType())
400       return None;
401   }
402 
403   // Create the new Phi
404   LLVMContext &Ctx = PN->getContext();
405   IRBuilder<> Builder(Ctx);
406   Builder.SetInsertPoint(PN);
407   PHINode *NPN = Builder.CreatePHI(RequiredType, PN->getNumIncomingValues());
408   Worklist.push_back(PN);
409 
410   for (unsigned I = 0; I < PN->getNumIncomingValues(); I++) {
411     auto *Reinterpret = cast<Instruction>(PN->getIncomingValue(I));
412     NPN->addIncoming(Reinterpret->getOperand(0), PN->getIncomingBlock(I));
413     Worklist.push_back(Reinterpret);
414   }
415 
416   // Cleanup Phi Node and reinterprets
417   return IC.replaceInstUsesWith(II, NPN);
418 }
419 
420 // (from_svbool (binop (to_svbool pred) (svbool_t _) (svbool_t _))))
421 // => (binop (pred) (from_svbool _) (from_svbool _))
422 //
423 // The above transformation eliminates a `to_svbool` in the predicate
424 // operand of bitwise operation `binop` by narrowing the vector width of
425 // the operation. For example, it would convert a `<vscale x 16 x i1>
426 // and` into a `<vscale x 4 x i1> and`. This is profitable because
427 // to_svbool must zero the new lanes during widening, whereas
428 // from_svbool is free.
429 static Optional<Instruction *> tryCombineFromSVBoolBinOp(InstCombiner &IC,
430                                                          IntrinsicInst &II) {
431   auto BinOp = dyn_cast<IntrinsicInst>(II.getOperand(0));
432   if (!BinOp)
433     return None;
434 
435   auto IntrinsicID = BinOp->getIntrinsicID();
436   switch (IntrinsicID) {
437   case Intrinsic::aarch64_sve_and_z:
438   case Intrinsic::aarch64_sve_bic_z:
439   case Intrinsic::aarch64_sve_eor_z:
440   case Intrinsic::aarch64_sve_nand_z:
441   case Intrinsic::aarch64_sve_nor_z:
442   case Intrinsic::aarch64_sve_orn_z:
443   case Intrinsic::aarch64_sve_orr_z:
444     break;
445   default:
446     return None;
447   }
448 
449   auto BinOpPred = BinOp->getOperand(0);
450   auto BinOpOp1 = BinOp->getOperand(1);
451   auto BinOpOp2 = BinOp->getOperand(2);
452 
453   auto PredIntr = dyn_cast<IntrinsicInst>(BinOpPred);
454   if (!PredIntr ||
455       PredIntr->getIntrinsicID() != Intrinsic::aarch64_sve_convert_to_svbool)
456     return None;
457 
458   auto PredOp = PredIntr->getOperand(0);
459   auto PredOpTy = cast<VectorType>(PredOp->getType());
460   if (PredOpTy != II.getType())
461     return None;
462 
463   IRBuilder<> Builder(II.getContext());
464   Builder.SetInsertPoint(&II);
465 
466   SmallVector<Value *> NarrowedBinOpArgs = {PredOp};
467   auto NarrowBinOpOp1 = Builder.CreateIntrinsic(
468       Intrinsic::aarch64_sve_convert_from_svbool, {PredOpTy}, {BinOpOp1});
469   NarrowedBinOpArgs.push_back(NarrowBinOpOp1);
470   if (BinOpOp1 == BinOpOp2)
471     NarrowedBinOpArgs.push_back(NarrowBinOpOp1);
472   else
473     NarrowedBinOpArgs.push_back(Builder.CreateIntrinsic(
474         Intrinsic::aarch64_sve_convert_from_svbool, {PredOpTy}, {BinOpOp2}));
475 
476   auto NarrowedBinOp =
477       Builder.CreateIntrinsic(IntrinsicID, {PredOpTy}, NarrowedBinOpArgs);
478   return IC.replaceInstUsesWith(II, NarrowedBinOp);
479 }
480 
481 static Optional<Instruction *> instCombineConvertFromSVBool(InstCombiner &IC,
482                                                             IntrinsicInst &II) {
483   // If the reinterpret instruction operand is a PHI Node
484   if (isa<PHINode>(II.getArgOperand(0)))
485     return processPhiNode(IC, II);
486 
487   if (auto BinOpCombine = tryCombineFromSVBoolBinOp(IC, II))
488     return BinOpCombine;
489 
490   SmallVector<Instruction *, 32> CandidatesForRemoval;
491   Value *Cursor = II.getOperand(0), *EarliestReplacement = nullptr;
492 
493   const auto *IVTy = cast<VectorType>(II.getType());
494 
495   // Walk the chain of conversions.
496   while (Cursor) {
497     // If the type of the cursor has fewer lanes than the final result, zeroing
498     // must take place, which breaks the equivalence chain.
499     const auto *CursorVTy = cast<VectorType>(Cursor->getType());
500     if (CursorVTy->getElementCount().getKnownMinValue() <
501         IVTy->getElementCount().getKnownMinValue())
502       break;
503 
504     // If the cursor has the same type as I, it is a viable replacement.
505     if (Cursor->getType() == IVTy)
506       EarliestReplacement = Cursor;
507 
508     auto *IntrinsicCursor = dyn_cast<IntrinsicInst>(Cursor);
509 
510     // If this is not an SVE conversion intrinsic, this is the end of the chain.
511     if (!IntrinsicCursor || !(IntrinsicCursor->getIntrinsicID() ==
512                                   Intrinsic::aarch64_sve_convert_to_svbool ||
513                               IntrinsicCursor->getIntrinsicID() ==
514                                   Intrinsic::aarch64_sve_convert_from_svbool))
515       break;
516 
517     CandidatesForRemoval.insert(CandidatesForRemoval.begin(), IntrinsicCursor);
518     Cursor = IntrinsicCursor->getOperand(0);
519   }
520 
521   // If no viable replacement in the conversion chain was found, there is
522   // nothing to do.
523   if (!EarliestReplacement)
524     return None;
525 
526   return IC.replaceInstUsesWith(II, EarliestReplacement);
527 }
528 
529 static Optional<Instruction *> instCombineSVESel(InstCombiner &IC,
530                                                  IntrinsicInst &II) {
531   IRBuilder<> Builder(&II);
532   auto Select = Builder.CreateSelect(II.getOperand(0), II.getOperand(1),
533                                      II.getOperand(2));
534   return IC.replaceInstUsesWith(II, Select);
535 }
536 
537 static Optional<Instruction *> instCombineSVEDup(InstCombiner &IC,
538                                                  IntrinsicInst &II) {
539   IntrinsicInst *Pg = dyn_cast<IntrinsicInst>(II.getArgOperand(1));
540   if (!Pg)
541     return None;
542 
543   if (Pg->getIntrinsicID() != Intrinsic::aarch64_sve_ptrue)
544     return None;
545 
546   const auto PTruePattern =
547       cast<ConstantInt>(Pg->getOperand(0))->getZExtValue();
548   if (PTruePattern != AArch64SVEPredPattern::vl1)
549     return None;
550 
551   // The intrinsic is inserting into lane zero so use an insert instead.
552   auto *IdxTy = Type::getInt64Ty(II.getContext());
553   auto *Insert = InsertElementInst::Create(
554       II.getArgOperand(0), II.getArgOperand(2), ConstantInt::get(IdxTy, 0));
555   Insert->insertBefore(&II);
556   Insert->takeName(&II);
557 
558   return IC.replaceInstUsesWith(II, Insert);
559 }
560 
561 static Optional<Instruction *> instCombineSVEDupX(InstCombiner &IC,
562                                                   IntrinsicInst &II) {
563   // Replace DupX with a regular IR splat.
564   IRBuilder<> Builder(II.getContext());
565   Builder.SetInsertPoint(&II);
566   auto *RetTy = cast<ScalableVectorType>(II.getType());
567   Value *Splat =
568       Builder.CreateVectorSplat(RetTy->getElementCount(), II.getArgOperand(0));
569   Splat->takeName(&II);
570   return IC.replaceInstUsesWith(II, Splat);
571 }
572 
573 static Optional<Instruction *> instCombineSVECmpNE(InstCombiner &IC,
574                                                    IntrinsicInst &II) {
575   LLVMContext &Ctx = II.getContext();
576   IRBuilder<> Builder(Ctx);
577   Builder.SetInsertPoint(&II);
578 
579   // Check that the predicate is all active
580   auto *Pg = dyn_cast<IntrinsicInst>(II.getArgOperand(0));
581   if (!Pg || Pg->getIntrinsicID() != Intrinsic::aarch64_sve_ptrue)
582     return None;
583 
584   const auto PTruePattern =
585       cast<ConstantInt>(Pg->getOperand(0))->getZExtValue();
586   if (PTruePattern != AArch64SVEPredPattern::all)
587     return None;
588 
589   // Check that we have a compare of zero..
590   auto *SplatValue =
591       dyn_cast_or_null<ConstantInt>(getSplatValue(II.getArgOperand(2)));
592   if (!SplatValue || !SplatValue->isZero())
593     return None;
594 
595   // ..against a dupq
596   auto *DupQLane = dyn_cast<IntrinsicInst>(II.getArgOperand(1));
597   if (!DupQLane ||
598       DupQLane->getIntrinsicID() != Intrinsic::aarch64_sve_dupq_lane)
599     return None;
600 
601   // Where the dupq is a lane 0 replicate of a vector insert
602   if (!cast<ConstantInt>(DupQLane->getArgOperand(1))->isZero())
603     return None;
604 
605   auto *VecIns = dyn_cast<IntrinsicInst>(DupQLane->getArgOperand(0));
606   if (!VecIns ||
607       VecIns->getIntrinsicID() != Intrinsic::experimental_vector_insert)
608     return None;
609 
610   // Where the vector insert is a fixed constant vector insert into undef at
611   // index zero
612   if (!isa<UndefValue>(VecIns->getArgOperand(0)))
613     return None;
614 
615   if (!cast<ConstantInt>(VecIns->getArgOperand(2))->isZero())
616     return None;
617 
618   auto *ConstVec = dyn_cast<Constant>(VecIns->getArgOperand(1));
619   if (!ConstVec)
620     return None;
621 
622   auto *VecTy = dyn_cast<FixedVectorType>(ConstVec->getType());
623   auto *OutTy = dyn_cast<ScalableVectorType>(II.getType());
624   if (!VecTy || !OutTy || VecTy->getNumElements() != OutTy->getMinNumElements())
625     return None;
626 
627   unsigned NumElts = VecTy->getNumElements();
628   unsigned PredicateBits = 0;
629 
630   // Expand intrinsic operands to a 16-bit byte level predicate
631   for (unsigned I = 0; I < NumElts; ++I) {
632     auto *Arg = dyn_cast<ConstantInt>(ConstVec->getAggregateElement(I));
633     if (!Arg)
634       return None;
635     if (!Arg->isZero())
636       PredicateBits |= 1 << (I * (16 / NumElts));
637   }
638 
639   // If all bits are zero bail early with an empty predicate
640   if (PredicateBits == 0) {
641     auto *PFalse = Constant::getNullValue(II.getType());
642     PFalse->takeName(&II);
643     return IC.replaceInstUsesWith(II, PFalse);
644   }
645 
646   // Calculate largest predicate type used (where byte predicate is largest)
647   unsigned Mask = 8;
648   for (unsigned I = 0; I < 16; ++I)
649     if ((PredicateBits & (1 << I)) != 0)
650       Mask |= (I % 8);
651 
652   unsigned PredSize = Mask & -Mask;
653   auto *PredType = ScalableVectorType::get(
654       Type::getInt1Ty(Ctx), AArch64::SVEBitsPerBlock / (PredSize * 8));
655 
656   // Ensure all relevant bits are set
657   for (unsigned I = 0; I < 16; I += PredSize)
658     if ((PredicateBits & (1 << I)) == 0)
659       return None;
660 
661   auto *PTruePat =
662       ConstantInt::get(Type::getInt32Ty(Ctx), AArch64SVEPredPattern::all);
663   auto *PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue,
664                                         {PredType}, {PTruePat});
665   auto *ConvertToSVBool = Builder.CreateIntrinsic(
666       Intrinsic::aarch64_sve_convert_to_svbool, {PredType}, {PTrue});
667   auto *ConvertFromSVBool =
668       Builder.CreateIntrinsic(Intrinsic::aarch64_sve_convert_from_svbool,
669                               {II.getType()}, {ConvertToSVBool});
670 
671   ConvertFromSVBool->takeName(&II);
672   return IC.replaceInstUsesWith(II, ConvertFromSVBool);
673 }
674 
675 static Optional<Instruction *> instCombineSVELast(InstCombiner &IC,
676                                                   IntrinsicInst &II) {
677   IRBuilder<> Builder(II.getContext());
678   Builder.SetInsertPoint(&II);
679   Value *Pg = II.getArgOperand(0);
680   Value *Vec = II.getArgOperand(1);
681   auto IntrinsicID = II.getIntrinsicID();
682   bool IsAfter = IntrinsicID == Intrinsic::aarch64_sve_lasta;
683 
684   // lastX(splat(X)) --> X
685   if (auto *SplatVal = getSplatValue(Vec))
686     return IC.replaceInstUsesWith(II, SplatVal);
687 
688   // If x and/or y is a splat value then:
689   // lastX (binop (x, y)) --> binop(lastX(x), lastX(y))
690   Value *LHS, *RHS;
691   if (match(Vec, m_OneUse(m_BinOp(m_Value(LHS), m_Value(RHS))))) {
692     if (isSplatValue(LHS) || isSplatValue(RHS)) {
693       auto *OldBinOp = cast<BinaryOperator>(Vec);
694       auto OpC = OldBinOp->getOpcode();
695       auto *NewLHS =
696           Builder.CreateIntrinsic(IntrinsicID, {Vec->getType()}, {Pg, LHS});
697       auto *NewRHS =
698           Builder.CreateIntrinsic(IntrinsicID, {Vec->getType()}, {Pg, RHS});
699       auto *NewBinOp = BinaryOperator::CreateWithCopiedFlags(
700           OpC, NewLHS, NewRHS, OldBinOp, OldBinOp->getName(), &II);
701       return IC.replaceInstUsesWith(II, NewBinOp);
702     }
703   }
704 
705   auto *C = dyn_cast<Constant>(Pg);
706   if (IsAfter && C && C->isNullValue()) {
707     // The intrinsic is extracting lane 0 so use an extract instead.
708     auto *IdxTy = Type::getInt64Ty(II.getContext());
709     auto *Extract = ExtractElementInst::Create(Vec, ConstantInt::get(IdxTy, 0));
710     Extract->insertBefore(&II);
711     Extract->takeName(&II);
712     return IC.replaceInstUsesWith(II, Extract);
713   }
714 
715   auto *IntrPG = dyn_cast<IntrinsicInst>(Pg);
716   if (!IntrPG)
717     return None;
718 
719   if (IntrPG->getIntrinsicID() != Intrinsic::aarch64_sve_ptrue)
720     return None;
721 
722   const auto PTruePattern =
723       cast<ConstantInt>(IntrPG->getOperand(0))->getZExtValue();
724 
725   // Can the intrinsic's predicate be converted to a known constant index?
726   unsigned MinNumElts = getNumElementsFromSVEPredPattern(PTruePattern);
727   if (!MinNumElts)
728     return None;
729 
730   unsigned Idx = MinNumElts - 1;
731   // Increment the index if extracting the element after the last active
732   // predicate element.
733   if (IsAfter)
734     ++Idx;
735 
736   // Ignore extracts whose index is larger than the known minimum vector
737   // length. NOTE: This is an artificial constraint where we prefer to
738   // maintain what the user asked for until an alternative is proven faster.
739   auto *PgVTy = cast<ScalableVectorType>(Pg->getType());
740   if (Idx >= PgVTy->getMinNumElements())
741     return None;
742 
743   // The intrinsic is extracting a fixed lane so use an extract instead.
744   auto *IdxTy = Type::getInt64Ty(II.getContext());
745   auto *Extract = ExtractElementInst::Create(Vec, ConstantInt::get(IdxTy, Idx));
746   Extract->insertBefore(&II);
747   Extract->takeName(&II);
748   return IC.replaceInstUsesWith(II, Extract);
749 }
750 
751 static Optional<Instruction *> instCombineRDFFR(InstCombiner &IC,
752                                                 IntrinsicInst &II) {
753   LLVMContext &Ctx = II.getContext();
754   IRBuilder<> Builder(Ctx);
755   Builder.SetInsertPoint(&II);
756   // Replace rdffr with predicated rdffr.z intrinsic, so that optimizePTestInstr
757   // can work with RDFFR_PP for ptest elimination.
758   auto *AllPat =
759       ConstantInt::get(Type::getInt32Ty(Ctx), AArch64SVEPredPattern::all);
760   auto *PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue,
761                                         {II.getType()}, {AllPat});
762   auto *RDFFR =
763       Builder.CreateIntrinsic(Intrinsic::aarch64_sve_rdffr_z, {}, {PTrue});
764   RDFFR->takeName(&II);
765   return IC.replaceInstUsesWith(II, RDFFR);
766 }
767 
768 static Optional<Instruction *>
769 instCombineSVECntElts(InstCombiner &IC, IntrinsicInst &II, unsigned NumElts) {
770   const auto Pattern = cast<ConstantInt>(II.getArgOperand(0))->getZExtValue();
771 
772   if (Pattern == AArch64SVEPredPattern::all) {
773     LLVMContext &Ctx = II.getContext();
774     IRBuilder<> Builder(Ctx);
775     Builder.SetInsertPoint(&II);
776 
777     Constant *StepVal = ConstantInt::get(II.getType(), NumElts);
778     auto *VScale = Builder.CreateVScale(StepVal);
779     VScale->takeName(&II);
780     return IC.replaceInstUsesWith(II, VScale);
781   }
782 
783   unsigned MinNumElts = getNumElementsFromSVEPredPattern(Pattern);
784 
785   return MinNumElts && NumElts >= MinNumElts
786              ? Optional<Instruction *>(IC.replaceInstUsesWith(
787                    II, ConstantInt::get(II.getType(), MinNumElts)))
788              : None;
789 }
790 
791 static Optional<Instruction *> instCombineSVEPTest(InstCombiner &IC,
792                                                    IntrinsicInst &II) {
793   IntrinsicInst *Op1 = dyn_cast<IntrinsicInst>(II.getArgOperand(0));
794   IntrinsicInst *Op2 = dyn_cast<IntrinsicInst>(II.getArgOperand(1));
795 
796   if (Op1 && Op2 &&
797       Op1->getIntrinsicID() == Intrinsic::aarch64_sve_convert_to_svbool &&
798       Op2->getIntrinsicID() == Intrinsic::aarch64_sve_convert_to_svbool &&
799       Op1->getArgOperand(0)->getType() == Op2->getArgOperand(0)->getType()) {
800 
801     IRBuilder<> Builder(II.getContext());
802     Builder.SetInsertPoint(&II);
803 
804     Value *Ops[] = {Op1->getArgOperand(0), Op2->getArgOperand(0)};
805     Type *Tys[] = {Op1->getArgOperand(0)->getType()};
806 
807     auto *PTest = Builder.CreateIntrinsic(II.getIntrinsicID(), Tys, Ops);
808 
809     PTest->takeName(&II);
810     return IC.replaceInstUsesWith(II, PTest);
811   }
812 
813   return None;
814 }
815 
816 static Optional<Instruction *> instCombineSVEVectorFMLA(InstCombiner &IC,
817                                                         IntrinsicInst &II) {
818   // fold (fadd p a (fmul p b c)) -> (fma p a b c)
819   Value *P = II.getOperand(0);
820   Value *A = II.getOperand(1);
821   auto FMul = II.getOperand(2);
822   Value *B, *C;
823   if (!match(FMul, m_Intrinsic<Intrinsic::aarch64_sve_fmul>(
824                        m_Specific(P), m_Value(B), m_Value(C))))
825     return None;
826 
827   if (!FMul->hasOneUse())
828     return None;
829 
830   llvm::FastMathFlags FAddFlags = II.getFastMathFlags();
831   // Stop the combine when the flags on the inputs differ in case dropping flags
832   // would lead to us missing out on more beneficial optimizations.
833   if (FAddFlags != cast<CallInst>(FMul)->getFastMathFlags())
834     return None;
835   if (!FAddFlags.allowContract())
836     return None;
837 
838   IRBuilder<> Builder(II.getContext());
839   Builder.SetInsertPoint(&II);
840   auto FMLA = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_fmla,
841                                       {II.getType()}, {P, A, B, C}, &II);
842   FMLA->setFastMathFlags(FAddFlags);
843   return IC.replaceInstUsesWith(II, FMLA);
844 }
845 
846 static bool isAllActivePredicate(Value *Pred) {
847   // Look through convert.from.svbool(convert.to.svbool(...) chain.
848   Value *UncastedPred;
849   if (match(Pred, m_Intrinsic<Intrinsic::aarch64_sve_convert_from_svbool>(
850                       m_Intrinsic<Intrinsic::aarch64_sve_convert_to_svbool>(
851                           m_Value(UncastedPred)))))
852     // If the predicate has the same or less lanes than the uncasted
853     // predicate then we know the casting has no effect.
854     if (cast<ScalableVectorType>(Pred->getType())->getMinNumElements() <=
855         cast<ScalableVectorType>(UncastedPred->getType())->getMinNumElements())
856       Pred = UncastedPred;
857 
858   return match(Pred, m_Intrinsic<Intrinsic::aarch64_sve_ptrue>(
859                          m_ConstantInt<AArch64SVEPredPattern::all>()));
860 }
861 
862 static Optional<Instruction *>
863 instCombineSVELD1(InstCombiner &IC, IntrinsicInst &II, const DataLayout &DL) {
864   IRBuilder<> Builder(II.getContext());
865   Builder.SetInsertPoint(&II);
866 
867   Value *Pred = II.getOperand(0);
868   Value *PtrOp = II.getOperand(1);
869   Type *VecTy = II.getType();
870   Value *VecPtr = Builder.CreateBitCast(PtrOp, VecTy->getPointerTo());
871 
872   if (isAllActivePredicate(Pred)) {
873     LoadInst *Load = Builder.CreateLoad(VecTy, VecPtr);
874     Load->copyMetadata(II);
875     return IC.replaceInstUsesWith(II, Load);
876   }
877 
878   CallInst *MaskedLoad =
879       Builder.CreateMaskedLoad(VecTy, VecPtr, PtrOp->getPointerAlignment(DL),
880                                Pred, ConstantAggregateZero::get(VecTy));
881   MaskedLoad->copyMetadata(II);
882   return IC.replaceInstUsesWith(II, MaskedLoad);
883 }
884 
885 static Optional<Instruction *>
886 instCombineSVEST1(InstCombiner &IC, IntrinsicInst &II, const DataLayout &DL) {
887   IRBuilder<> Builder(II.getContext());
888   Builder.SetInsertPoint(&II);
889 
890   Value *VecOp = II.getOperand(0);
891   Value *Pred = II.getOperand(1);
892   Value *PtrOp = II.getOperand(2);
893   Value *VecPtr =
894       Builder.CreateBitCast(PtrOp, VecOp->getType()->getPointerTo());
895 
896   if (isAllActivePredicate(Pred)) {
897     StoreInst *Store = Builder.CreateStore(VecOp, VecPtr);
898     Store->copyMetadata(II);
899     return IC.eraseInstFromFunction(II);
900   }
901 
902   CallInst *MaskedStore = Builder.CreateMaskedStore(
903       VecOp, VecPtr, PtrOp->getPointerAlignment(DL), Pred);
904   MaskedStore->copyMetadata(II);
905   return IC.eraseInstFromFunction(II);
906 }
907 
908 static Instruction::BinaryOps intrinsicIDToBinOpCode(unsigned Intrinsic) {
909   switch (Intrinsic) {
910   case Intrinsic::aarch64_sve_fmul:
911     return Instruction::BinaryOps::FMul;
912   case Intrinsic::aarch64_sve_fadd:
913     return Instruction::BinaryOps::FAdd;
914   case Intrinsic::aarch64_sve_fsub:
915     return Instruction::BinaryOps::FSub;
916   default:
917     return Instruction::BinaryOpsEnd;
918   }
919 }
920 
921 static Optional<Instruction *> instCombineSVEVectorBinOp(InstCombiner &IC,
922                                                          IntrinsicInst &II) {
923   auto *OpPredicate = II.getOperand(0);
924   auto BinOpCode = intrinsicIDToBinOpCode(II.getIntrinsicID());
925   if (BinOpCode == Instruction::BinaryOpsEnd ||
926       !match(OpPredicate, m_Intrinsic<Intrinsic::aarch64_sve_ptrue>(
927                               m_ConstantInt<AArch64SVEPredPattern::all>())))
928     return None;
929   IRBuilder<> Builder(II.getContext());
930   Builder.SetInsertPoint(&II);
931   Builder.setFastMathFlags(II.getFastMathFlags());
932   auto BinOp =
933       Builder.CreateBinOp(BinOpCode, II.getOperand(1), II.getOperand(2));
934   return IC.replaceInstUsesWith(II, BinOp);
935 }
936 
937 static Optional<Instruction *> instCombineSVEVectorFAdd(InstCombiner &IC,
938                                                         IntrinsicInst &II) {
939   if (auto FMLA = instCombineSVEVectorFMLA(IC, II))
940     return FMLA;
941   return instCombineSVEVectorBinOp(IC, II);
942 }
943 
944 static Optional<Instruction *> instCombineSVEVectorMul(InstCombiner &IC,
945                                                        IntrinsicInst &II) {
946   auto *OpPredicate = II.getOperand(0);
947   auto *OpMultiplicand = II.getOperand(1);
948   auto *OpMultiplier = II.getOperand(2);
949 
950   IRBuilder<> Builder(II.getContext());
951   Builder.SetInsertPoint(&II);
952 
953   // Return true if a given instruction is a unit splat value, false otherwise.
954   auto IsUnitSplat = [](auto *I) {
955     auto *SplatValue = getSplatValue(I);
956     if (!SplatValue)
957       return false;
958     return match(SplatValue, m_FPOne()) || match(SplatValue, m_One());
959   };
960 
961   // Return true if a given instruction is an aarch64_sve_dup intrinsic call
962   // with a unit splat value, false otherwise.
963   auto IsUnitDup = [](auto *I) {
964     auto *IntrI = dyn_cast<IntrinsicInst>(I);
965     if (!IntrI || IntrI->getIntrinsicID() != Intrinsic::aarch64_sve_dup)
966       return false;
967 
968     auto *SplatValue = IntrI->getOperand(2);
969     return match(SplatValue, m_FPOne()) || match(SplatValue, m_One());
970   };
971 
972   if (IsUnitSplat(OpMultiplier)) {
973     // [f]mul pg %n, (dupx 1) => %n
974     OpMultiplicand->takeName(&II);
975     return IC.replaceInstUsesWith(II, OpMultiplicand);
976   } else if (IsUnitDup(OpMultiplier)) {
977     // [f]mul pg %n, (dup pg 1) => %n
978     auto *DupInst = cast<IntrinsicInst>(OpMultiplier);
979     auto *DupPg = DupInst->getOperand(1);
980     // TODO: this is naive. The optimization is still valid if DupPg
981     // 'encompasses' OpPredicate, not only if they're the same predicate.
982     if (OpPredicate == DupPg) {
983       OpMultiplicand->takeName(&II);
984       return IC.replaceInstUsesWith(II, OpMultiplicand);
985     }
986   }
987 
988   return instCombineSVEVectorBinOp(IC, II);
989 }
990 
991 static Optional<Instruction *> instCombineSVEUnpack(InstCombiner &IC,
992                                                     IntrinsicInst &II) {
993   IRBuilder<> Builder(II.getContext());
994   Builder.SetInsertPoint(&II);
995   Value *UnpackArg = II.getArgOperand(0);
996   auto *RetTy = cast<ScalableVectorType>(II.getType());
997   bool IsSigned = II.getIntrinsicID() == Intrinsic::aarch64_sve_sunpkhi ||
998                   II.getIntrinsicID() == Intrinsic::aarch64_sve_sunpklo;
999 
1000   // Hi = uunpkhi(splat(X)) --> Hi = splat(extend(X))
1001   // Lo = uunpklo(splat(X)) --> Lo = splat(extend(X))
1002   if (auto *ScalarArg = getSplatValue(UnpackArg)) {
1003     ScalarArg =
1004         Builder.CreateIntCast(ScalarArg, RetTy->getScalarType(), IsSigned);
1005     Value *NewVal =
1006         Builder.CreateVectorSplat(RetTy->getElementCount(), ScalarArg);
1007     NewVal->takeName(&II);
1008     return IC.replaceInstUsesWith(II, NewVal);
1009   }
1010 
1011   return None;
1012 }
1013 static Optional<Instruction *> instCombineSVETBL(InstCombiner &IC,
1014                                                  IntrinsicInst &II) {
1015   auto *OpVal = II.getOperand(0);
1016   auto *OpIndices = II.getOperand(1);
1017   VectorType *VTy = cast<VectorType>(II.getType());
1018 
1019   // Check whether OpIndices is a constant splat value < minimal element count
1020   // of result.
1021   auto *SplatValue = dyn_cast_or_null<ConstantInt>(getSplatValue(OpIndices));
1022   if (!SplatValue ||
1023       SplatValue->getValue().uge(VTy->getElementCount().getKnownMinValue()))
1024     return None;
1025 
1026   // Convert sve_tbl(OpVal sve_dup_x(SplatValue)) to
1027   // splat_vector(extractelement(OpVal, SplatValue)) for further optimization.
1028   IRBuilder<> Builder(II.getContext());
1029   Builder.SetInsertPoint(&II);
1030   auto *Extract = Builder.CreateExtractElement(OpVal, SplatValue);
1031   auto *VectorSplat =
1032       Builder.CreateVectorSplat(VTy->getElementCount(), Extract);
1033 
1034   VectorSplat->takeName(&II);
1035   return IC.replaceInstUsesWith(II, VectorSplat);
1036 }
1037 
1038 static Optional<Instruction *> instCombineSVETupleGet(InstCombiner &IC,
1039                                                       IntrinsicInst &II) {
1040   // Try to remove sequences of tuple get/set.
1041   Value *SetTuple, *SetIndex, *SetValue;
1042   auto *GetTuple = II.getArgOperand(0);
1043   auto *GetIndex = II.getArgOperand(1);
1044   // Check that we have tuple_get(GetTuple, GetIndex) where GetTuple is a
1045   // call to tuple_set i.e. tuple_set(SetTuple, SetIndex, SetValue).
1046   // Make sure that the types of the current intrinsic and SetValue match
1047   // in order to safely remove the sequence.
1048   if (!match(GetTuple,
1049              m_Intrinsic<Intrinsic::aarch64_sve_tuple_set>(
1050                  m_Value(SetTuple), m_Value(SetIndex), m_Value(SetValue))) ||
1051       SetValue->getType() != II.getType())
1052     return None;
1053   // Case where we get the same index right after setting it.
1054   // tuple_get(tuple_set(SetTuple, SetIndex, SetValue), GetIndex) --> SetValue
1055   if (GetIndex == SetIndex)
1056     return IC.replaceInstUsesWith(II, SetValue);
1057   // If we are getting a different index than what was set in the tuple_set
1058   // intrinsic. We can just set the input tuple to the one up in the chain.
1059   // tuple_get(tuple_set(SetTuple, SetIndex, SetValue), GetIndex)
1060   // --> tuple_get(SetTuple, GetIndex)
1061   return IC.replaceOperand(II, 0, SetTuple);
1062 }
1063 
1064 static Optional<Instruction *> instCombineSVEZip(InstCombiner &IC,
1065                                                  IntrinsicInst &II) {
1066   // zip1(uzp1(A, B), uzp2(A, B)) --> A
1067   // zip2(uzp1(A, B), uzp2(A, B)) --> B
1068   Value *A, *B;
1069   if (match(II.getArgOperand(0),
1070             m_Intrinsic<Intrinsic::aarch64_sve_uzp1>(m_Value(A), m_Value(B))) &&
1071       match(II.getArgOperand(1), m_Intrinsic<Intrinsic::aarch64_sve_uzp2>(
1072                                      m_Specific(A), m_Specific(B))))
1073     return IC.replaceInstUsesWith(
1074         II, (II.getIntrinsicID() == Intrinsic::aarch64_sve_zip1 ? A : B));
1075 
1076   return None;
1077 }
1078 
1079 static Optional<Instruction *> instCombineLD1GatherIndex(InstCombiner &IC,
1080                                                          IntrinsicInst &II) {
1081   Value *Mask = II.getOperand(0);
1082   Value *BasePtr = II.getOperand(1);
1083   Value *Index = II.getOperand(2);
1084   Type *Ty = II.getType();
1085   Value *PassThru = ConstantAggregateZero::get(Ty);
1086 
1087   // Contiguous gather => masked load.
1088   // (sve.ld1.gather.index Mask BasePtr (sve.index IndexBase 1))
1089   // => (masked.load (gep BasePtr IndexBase) Align Mask zeroinitializer)
1090   Value *IndexBase;
1091   if (match(Index, m_Intrinsic<Intrinsic::aarch64_sve_index>(
1092                        m_Value(IndexBase), m_SpecificInt(1)))) {
1093     IRBuilder<> Builder(II.getContext());
1094     Builder.SetInsertPoint(&II);
1095 
1096     Align Alignment =
1097         BasePtr->getPointerAlignment(II.getModule()->getDataLayout());
1098 
1099     Type *VecPtrTy = PointerType::getUnqual(Ty);
1100     Value *Ptr = Builder.CreateGEP(
1101         cast<VectorType>(Ty)->getElementType(), BasePtr, IndexBase);
1102     Ptr = Builder.CreateBitCast(Ptr, VecPtrTy);
1103     CallInst *MaskedLoad =
1104         Builder.CreateMaskedLoad(Ty, Ptr, Alignment, Mask, PassThru);
1105     MaskedLoad->takeName(&II);
1106     return IC.replaceInstUsesWith(II, MaskedLoad);
1107   }
1108 
1109   return None;
1110 }
1111 
1112 static Optional<Instruction *> instCombineST1ScatterIndex(InstCombiner &IC,
1113                                                           IntrinsicInst &II) {
1114   Value *Val = II.getOperand(0);
1115   Value *Mask = II.getOperand(1);
1116   Value *BasePtr = II.getOperand(2);
1117   Value *Index = II.getOperand(3);
1118   Type *Ty = Val->getType();
1119 
1120   // Contiguous scatter => masked store.
1121   // (sve.st1.scatter.index Value Mask BasePtr (sve.index IndexBase 1))
1122   // => (masked.store Value (gep BasePtr IndexBase) Align Mask)
1123   Value *IndexBase;
1124   if (match(Index, m_Intrinsic<Intrinsic::aarch64_sve_index>(
1125                        m_Value(IndexBase), m_SpecificInt(1)))) {
1126     IRBuilder<> Builder(II.getContext());
1127     Builder.SetInsertPoint(&II);
1128 
1129     Align Alignment =
1130         BasePtr->getPointerAlignment(II.getModule()->getDataLayout());
1131 
1132     Value *Ptr = Builder.CreateGEP(
1133         cast<VectorType>(Ty)->getElementType(), BasePtr, IndexBase);
1134     Type *VecPtrTy = PointerType::getUnqual(Ty);
1135     Ptr = Builder.CreateBitCast(Ptr, VecPtrTy);
1136 
1137     (void)Builder.CreateMaskedStore(Val, Ptr, Alignment, Mask);
1138 
1139     return IC.eraseInstFromFunction(II);
1140   }
1141 
1142   return None;
1143 }
1144 
1145 static Optional<Instruction *> instCombineSVESDIV(InstCombiner &IC,
1146                                                   IntrinsicInst &II) {
1147   IRBuilder<> Builder(II.getContext());
1148   Builder.SetInsertPoint(&II);
1149   Type *Int32Ty = Builder.getInt32Ty();
1150   Value *Pred = II.getOperand(0);
1151   Value *Vec = II.getOperand(1);
1152   Value *DivVec = II.getOperand(2);
1153 
1154   Value *SplatValue = getSplatValue(DivVec);
1155   ConstantInt *SplatConstantInt = dyn_cast_or_null<ConstantInt>(SplatValue);
1156   if (!SplatConstantInt)
1157     return None;
1158   APInt Divisor = SplatConstantInt->getValue();
1159 
1160   if (Divisor.isPowerOf2()) {
1161     Constant *DivisorLog2 = ConstantInt::get(Int32Ty, Divisor.logBase2());
1162     auto ASRD = Builder.CreateIntrinsic(
1163         Intrinsic::aarch64_sve_asrd, {II.getType()}, {Pred, Vec, DivisorLog2});
1164     return IC.replaceInstUsesWith(II, ASRD);
1165   }
1166   if (Divisor.isNegatedPowerOf2()) {
1167     Divisor.negate();
1168     Constant *DivisorLog2 = ConstantInt::get(Int32Ty, Divisor.logBase2());
1169     auto ASRD = Builder.CreateIntrinsic(
1170         Intrinsic::aarch64_sve_asrd, {II.getType()}, {Pred, Vec, DivisorLog2});
1171     auto NEG = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_neg,
1172                                        {ASRD->getType()}, {ASRD, Pred, ASRD});
1173     return IC.replaceInstUsesWith(II, NEG);
1174   }
1175 
1176   return None;
1177 }
1178 
1179 Optional<Instruction *>
1180 AArch64TTIImpl::instCombineIntrinsic(InstCombiner &IC,
1181                                      IntrinsicInst &II) const {
1182   Intrinsic::ID IID = II.getIntrinsicID();
1183   switch (IID) {
1184   default:
1185     break;
1186   case Intrinsic::aarch64_sve_convert_from_svbool:
1187     return instCombineConvertFromSVBool(IC, II);
1188   case Intrinsic::aarch64_sve_dup:
1189     return instCombineSVEDup(IC, II);
1190   case Intrinsic::aarch64_sve_dup_x:
1191     return instCombineSVEDupX(IC, II);
1192   case Intrinsic::aarch64_sve_cmpne:
1193   case Intrinsic::aarch64_sve_cmpne_wide:
1194     return instCombineSVECmpNE(IC, II);
1195   case Intrinsic::aarch64_sve_rdffr:
1196     return instCombineRDFFR(IC, II);
1197   case Intrinsic::aarch64_sve_lasta:
1198   case Intrinsic::aarch64_sve_lastb:
1199     return instCombineSVELast(IC, II);
1200   case Intrinsic::aarch64_sve_cntd:
1201     return instCombineSVECntElts(IC, II, 2);
1202   case Intrinsic::aarch64_sve_cntw:
1203     return instCombineSVECntElts(IC, II, 4);
1204   case Intrinsic::aarch64_sve_cnth:
1205     return instCombineSVECntElts(IC, II, 8);
1206   case Intrinsic::aarch64_sve_cntb:
1207     return instCombineSVECntElts(IC, II, 16);
1208   case Intrinsic::aarch64_sve_ptest_any:
1209   case Intrinsic::aarch64_sve_ptest_first:
1210   case Intrinsic::aarch64_sve_ptest_last:
1211     return instCombineSVEPTest(IC, II);
1212   case Intrinsic::aarch64_sve_mul:
1213   case Intrinsic::aarch64_sve_fmul:
1214     return instCombineSVEVectorMul(IC, II);
1215   case Intrinsic::aarch64_sve_fadd:
1216     return instCombineSVEVectorFAdd(IC, II);
1217   case Intrinsic::aarch64_sve_fsub:
1218     return instCombineSVEVectorBinOp(IC, II);
1219   case Intrinsic::aarch64_sve_tbl:
1220     return instCombineSVETBL(IC, II);
1221   case Intrinsic::aarch64_sve_uunpkhi:
1222   case Intrinsic::aarch64_sve_uunpklo:
1223   case Intrinsic::aarch64_sve_sunpkhi:
1224   case Intrinsic::aarch64_sve_sunpklo:
1225     return instCombineSVEUnpack(IC, II);
1226   case Intrinsic::aarch64_sve_tuple_get:
1227     return instCombineSVETupleGet(IC, II);
1228   case Intrinsic::aarch64_sve_zip1:
1229   case Intrinsic::aarch64_sve_zip2:
1230     return instCombineSVEZip(IC, II);
1231   case Intrinsic::aarch64_sve_ld1_gather_index:
1232     return instCombineLD1GatherIndex(IC, II);
1233   case Intrinsic::aarch64_sve_st1_scatter_index:
1234     return instCombineST1ScatterIndex(IC, II);
1235   case Intrinsic::aarch64_sve_ld1:
1236     return instCombineSVELD1(IC, II, DL);
1237   case Intrinsic::aarch64_sve_st1:
1238     return instCombineSVEST1(IC, II, DL);
1239   case Intrinsic::aarch64_sve_sdiv:
1240     return instCombineSVESDIV(IC, II);
1241   case Intrinsic::aarch64_sve_sel:
1242     return instCombineSVESel(IC, II);
1243   }
1244 
1245   return None;
1246 }
1247 
1248 Optional<Value *> AArch64TTIImpl::simplifyDemandedVectorEltsIntrinsic(
1249     InstCombiner &IC, IntrinsicInst &II, APInt OrigDemandedElts,
1250     APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3,
1251     std::function<void(Instruction *, unsigned, APInt, APInt &)>
1252         SimplifyAndSetOp) const {
1253   switch (II.getIntrinsicID()) {
1254   default:
1255     break;
1256   case Intrinsic::aarch64_neon_fcvtxn:
1257   case Intrinsic::aarch64_neon_rshrn:
1258   case Intrinsic::aarch64_neon_sqrshrn:
1259   case Intrinsic::aarch64_neon_sqrshrun:
1260   case Intrinsic::aarch64_neon_sqshrn:
1261   case Intrinsic::aarch64_neon_sqshrun:
1262   case Intrinsic::aarch64_neon_sqxtn:
1263   case Intrinsic::aarch64_neon_sqxtun:
1264   case Intrinsic::aarch64_neon_uqrshrn:
1265   case Intrinsic::aarch64_neon_uqshrn:
1266   case Intrinsic::aarch64_neon_uqxtn:
1267     SimplifyAndSetOp(&II, 0, OrigDemandedElts, UndefElts);
1268     break;
1269   }
1270 
1271   return None;
1272 }
1273 
1274 bool AArch64TTIImpl::isWideningInstruction(Type *DstTy, unsigned Opcode,
1275                                            ArrayRef<const Value *> Args) {
1276 
1277   // A helper that returns a vector type from the given type. The number of
1278   // elements in type Ty determine the vector width.
1279   auto toVectorTy = [&](Type *ArgTy) {
1280     return VectorType::get(ArgTy->getScalarType(),
1281                            cast<VectorType>(DstTy)->getElementCount());
1282   };
1283 
1284   // Exit early if DstTy is not a vector type whose elements are at least
1285   // 16-bits wide.
1286   if (!DstTy->isVectorTy() || DstTy->getScalarSizeInBits() < 16)
1287     return false;
1288 
1289   // Determine if the operation has a widening variant. We consider both the
1290   // "long" (e.g., usubl) and "wide" (e.g., usubw) versions of the
1291   // instructions.
1292   //
1293   // TODO: Add additional widening operations (e.g., shl, etc.) once we
1294   //       verify that their extending operands are eliminated during code
1295   //       generation.
1296   switch (Opcode) {
1297   case Instruction::Add: // UADDL(2), SADDL(2), UADDW(2), SADDW(2).
1298   case Instruction::Sub: // USUBL(2), SSUBL(2), USUBW(2), SSUBW(2).
1299   case Instruction::Mul: // SMULL(2), UMULL(2)
1300     break;
1301   default:
1302     return false;
1303   }
1304 
1305   // To be a widening instruction (either the "wide" or "long" versions), the
1306   // second operand must be a sign- or zero extend.
1307   if (Args.size() != 2 ||
1308       (!isa<SExtInst>(Args[1]) && !isa<ZExtInst>(Args[1])))
1309     return false;
1310   auto *Extend = cast<CastInst>(Args[1]);
1311   auto *Arg0 = dyn_cast<CastInst>(Args[0]);
1312 
1313   // A mul only has a mull version (not like addw). Both operands need to be
1314   // extending and the same type.
1315   if (Opcode == Instruction::Mul &&
1316       (!Arg0 || Arg0->getOpcode() != Extend->getOpcode() ||
1317        Arg0->getOperand(0)->getType() != Extend->getOperand(0)->getType()))
1318     return false;
1319 
1320   // Legalize the destination type and ensure it can be used in a widening
1321   // operation.
1322   auto DstTyL = TLI->getTypeLegalizationCost(DL, DstTy);
1323   unsigned DstElTySize = DstTyL.second.getScalarSizeInBits();
1324   if (!DstTyL.second.isVector() || DstElTySize != DstTy->getScalarSizeInBits())
1325     return false;
1326 
1327   // Legalize the source type and ensure it can be used in a widening
1328   // operation.
1329   auto *SrcTy = toVectorTy(Extend->getSrcTy());
1330   auto SrcTyL = TLI->getTypeLegalizationCost(DL, SrcTy);
1331   unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits();
1332   if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits())
1333     return false;
1334 
1335   // Get the total number of vector elements in the legalized types.
1336   InstructionCost NumDstEls =
1337       DstTyL.first * DstTyL.second.getVectorMinNumElements();
1338   InstructionCost NumSrcEls =
1339       SrcTyL.first * SrcTyL.second.getVectorMinNumElements();
1340 
1341   // Return true if the legalized types have the same number of vector elements
1342   // and the destination element type size is twice that of the source type.
1343   return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstElTySize;
1344 }
1345 
1346 InstructionCost AArch64TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst,
1347                                                  Type *Src,
1348                                                  TTI::CastContextHint CCH,
1349                                                  TTI::TargetCostKind CostKind,
1350                                                  const Instruction *I) {
1351   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1352   assert(ISD && "Invalid opcode");
1353 
1354   // If the cast is observable, and it is used by a widening instruction (e.g.,
1355   // uaddl, saddw, etc.), it may be free.
1356   if (I && I->hasOneUser()) {
1357     auto *SingleUser = cast<Instruction>(*I->user_begin());
1358     SmallVector<const Value *, 4> Operands(SingleUser->operand_values());
1359     if (isWideningInstruction(Dst, SingleUser->getOpcode(), Operands)) {
1360       // If the cast is the second operand, it is free. We will generate either
1361       // a "wide" or "long" version of the widening instruction.
1362       if (I == SingleUser->getOperand(1))
1363         return 0;
1364       // If the cast is not the second operand, it will be free if it looks the
1365       // same as the second operand. In this case, we will generate a "long"
1366       // version of the widening instruction.
1367       if (auto *Cast = dyn_cast<CastInst>(SingleUser->getOperand(1)))
1368         if (I->getOpcode() == unsigned(Cast->getOpcode()) &&
1369             cast<CastInst>(I)->getSrcTy() == Cast->getSrcTy())
1370           return 0;
1371     }
1372   }
1373 
1374   // TODO: Allow non-throughput costs that aren't binary.
1375   auto AdjustCost = [&CostKind](InstructionCost Cost) -> InstructionCost {
1376     if (CostKind != TTI::TCK_RecipThroughput)
1377       return Cost == 0 ? 0 : 1;
1378     return Cost;
1379   };
1380 
1381   EVT SrcTy = TLI->getValueType(DL, Src);
1382   EVT DstTy = TLI->getValueType(DL, Dst);
1383 
1384   if (!SrcTy.isSimple() || !DstTy.isSimple())
1385     return AdjustCost(
1386         BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
1387 
1388   static const TypeConversionCostTblEntry
1389   ConversionTbl[] = {
1390     { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32,  1 },
1391     { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64,  0 },
1392     { ISD::TRUNCATE, MVT::v8i8,  MVT::v8i32,  3 },
1393     { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
1394 
1395     // Truncations on nxvmiN
1396     { ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i16, 1 },
1397     { ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i32, 1 },
1398     { ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i64, 1 },
1399     { ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i16, 1 },
1400     { ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i32, 1 },
1401     { ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i64, 2 },
1402     { ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i16, 1 },
1403     { ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i32, 3 },
1404     { ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i64, 5 },
1405     { ISD::TRUNCATE, MVT::nxv16i1, MVT::nxv16i8, 1 },
1406     { ISD::TRUNCATE, MVT::nxv2i16, MVT::nxv2i32, 1 },
1407     { ISD::TRUNCATE, MVT::nxv2i32, MVT::nxv2i64, 1 },
1408     { ISD::TRUNCATE, MVT::nxv4i16, MVT::nxv4i32, 1 },
1409     { ISD::TRUNCATE, MVT::nxv4i32, MVT::nxv4i64, 2 },
1410     { ISD::TRUNCATE, MVT::nxv8i16, MVT::nxv8i32, 3 },
1411     { ISD::TRUNCATE, MVT::nxv8i32, MVT::nxv8i64, 6 },
1412 
1413     // The number of shll instructions for the extension.
1414     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
1415     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
1416     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
1417     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
1418     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
1419     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
1420     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
1421     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
1422     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
1423     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
1424     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
1425     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
1426     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
1427     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
1428     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
1429     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
1430 
1431     // LowerVectorINT_TO_FP:
1432     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
1433     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
1434     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
1435     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
1436     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
1437     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
1438 
1439     // Complex: to v2f32
1440     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
1441     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
1442     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
1443     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
1444     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
1445     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
1446 
1447     // Complex: to v4f32
1448     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8,  4 },
1449     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
1450     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8,  3 },
1451     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
1452 
1453     // Complex: to v8f32
1454     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
1455     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
1456     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
1457     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
1458 
1459     // Complex: to v16f32
1460     { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
1461     { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
1462 
1463     // Complex: to v2f64
1464     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
1465     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
1466     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
1467     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
1468     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
1469     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
1470 
1471 
1472     // LowerVectorFP_TO_INT
1473     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f32, 1 },
1474     { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
1475     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1 },
1476     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1 },
1477     { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
1478     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 },
1479 
1480     // Complex, from v2f32: legal type is v2i32 (no cost) or v2i64 (1 ext).
1481     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 2 },
1482     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 1 },
1483     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f32, 1 },
1484     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 2 },
1485     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 1 },
1486     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f32, 1 },
1487 
1488     // Complex, from v4f32: legal type is v4i16, 1 narrowing => ~2
1489     { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
1490     { ISD::FP_TO_SINT, MVT::v4i8,  MVT::v4f32, 2 },
1491     { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
1492     { ISD::FP_TO_UINT, MVT::v4i8,  MVT::v4f32, 2 },
1493 
1494     // Complex, from nxv2f32.
1495     { ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f32, 1 },
1496     { ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f32, 1 },
1497     { ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f32, 1 },
1498     { ISD::FP_TO_SINT, MVT::nxv2i8,  MVT::nxv2f32, 1 },
1499     { ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f32, 1 },
1500     { ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f32, 1 },
1501     { ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f32, 1 },
1502     { ISD::FP_TO_UINT, MVT::nxv2i8,  MVT::nxv2f32, 1 },
1503 
1504     // Complex, from v2f64: legal type is v2i32, 1 narrowing => ~2.
1505     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
1506     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f64, 2 },
1507     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f64, 2 },
1508     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
1509     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f64, 2 },
1510     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f64, 2 },
1511 
1512     // Complex, from nxv2f64.
1513     { ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f64, 1 },
1514     { ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f64, 1 },
1515     { ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f64, 1 },
1516     { ISD::FP_TO_SINT, MVT::nxv2i8,  MVT::nxv2f64, 1 },
1517     { ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f64, 1 },
1518     { ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f64, 1 },
1519     { ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f64, 1 },
1520     { ISD::FP_TO_UINT, MVT::nxv2i8,  MVT::nxv2f64, 1 },
1521 
1522     // Complex, from nxv4f32.
1523     { ISD::FP_TO_SINT, MVT::nxv4i64, MVT::nxv4f32, 4 },
1524     { ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f32, 1 },
1525     { ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f32, 1 },
1526     { ISD::FP_TO_SINT, MVT::nxv4i8,  MVT::nxv4f32, 1 },
1527     { ISD::FP_TO_UINT, MVT::nxv4i64, MVT::nxv4f32, 4 },
1528     { ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f32, 1 },
1529     { ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f32, 1 },
1530     { ISD::FP_TO_UINT, MVT::nxv4i8,  MVT::nxv4f32, 1 },
1531 
1532     // Complex, from nxv8f64. Illegal -> illegal conversions not required.
1533     { ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f64, 7 },
1534     { ISD::FP_TO_SINT, MVT::nxv8i8,  MVT::nxv8f64, 7 },
1535     { ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f64, 7 },
1536     { ISD::FP_TO_UINT, MVT::nxv8i8,  MVT::nxv8f64, 7 },
1537 
1538     // Complex, from nxv4f64. Illegal -> illegal conversions not required.
1539     { ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f64, 3 },
1540     { ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f64, 3 },
1541     { ISD::FP_TO_SINT, MVT::nxv4i8,  MVT::nxv4f64, 3 },
1542     { ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f64, 3 },
1543     { ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f64, 3 },
1544     { ISD::FP_TO_UINT, MVT::nxv4i8,  MVT::nxv4f64, 3 },
1545 
1546     // Complex, from nxv8f32. Illegal -> illegal conversions not required.
1547     { ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f32, 3 },
1548     { ISD::FP_TO_SINT, MVT::nxv8i8,  MVT::nxv8f32, 3 },
1549     { ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f32, 3 },
1550     { ISD::FP_TO_UINT, MVT::nxv8i8,  MVT::nxv8f32, 3 },
1551 
1552     // Complex, from nxv8f16.
1553     { ISD::FP_TO_SINT, MVT::nxv8i64, MVT::nxv8f16, 10 },
1554     { ISD::FP_TO_SINT, MVT::nxv8i32, MVT::nxv8f16, 4 },
1555     { ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f16, 1 },
1556     { ISD::FP_TO_SINT, MVT::nxv8i8,  MVT::nxv8f16, 1 },
1557     { ISD::FP_TO_UINT, MVT::nxv8i64, MVT::nxv8f16, 10 },
1558     { ISD::FP_TO_UINT, MVT::nxv8i32, MVT::nxv8f16, 4 },
1559     { ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f16, 1 },
1560     { ISD::FP_TO_UINT, MVT::nxv8i8,  MVT::nxv8f16, 1 },
1561 
1562     // Complex, from nxv4f16.
1563     { ISD::FP_TO_SINT, MVT::nxv4i64, MVT::nxv4f16, 4 },
1564     { ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f16, 1 },
1565     { ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f16, 1 },
1566     { ISD::FP_TO_SINT, MVT::nxv4i8,  MVT::nxv4f16, 1 },
1567     { ISD::FP_TO_UINT, MVT::nxv4i64, MVT::nxv4f16, 4 },
1568     { ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f16, 1 },
1569     { ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f16, 1 },
1570     { ISD::FP_TO_UINT, MVT::nxv4i8,  MVT::nxv4f16, 1 },
1571 
1572     // Complex, from nxv2f16.
1573     { ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f16, 1 },
1574     { ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f16, 1 },
1575     { ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f16, 1 },
1576     { ISD::FP_TO_SINT, MVT::nxv2i8,  MVT::nxv2f16, 1 },
1577     { ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f16, 1 },
1578     { ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f16, 1 },
1579     { ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f16, 1 },
1580     { ISD::FP_TO_UINT, MVT::nxv2i8,  MVT::nxv2f16, 1 },
1581 
1582     // Truncate from nxvmf32 to nxvmf16.
1583     { ISD::FP_ROUND, MVT::nxv2f16, MVT::nxv2f32, 1 },
1584     { ISD::FP_ROUND, MVT::nxv4f16, MVT::nxv4f32, 1 },
1585     { ISD::FP_ROUND, MVT::nxv8f16, MVT::nxv8f32, 3 },
1586 
1587     // Truncate from nxvmf64 to nxvmf16.
1588     { ISD::FP_ROUND, MVT::nxv2f16, MVT::nxv2f64, 1 },
1589     { ISD::FP_ROUND, MVT::nxv4f16, MVT::nxv4f64, 3 },
1590     { ISD::FP_ROUND, MVT::nxv8f16, MVT::nxv8f64, 7 },
1591 
1592     // Truncate from nxvmf64 to nxvmf32.
1593     { ISD::FP_ROUND, MVT::nxv2f32, MVT::nxv2f64, 1 },
1594     { ISD::FP_ROUND, MVT::nxv4f32, MVT::nxv4f64, 3 },
1595     { ISD::FP_ROUND, MVT::nxv8f32, MVT::nxv8f64, 6 },
1596 
1597     // Extend from nxvmf16 to nxvmf32.
1598     { ISD::FP_EXTEND, MVT::nxv2f32, MVT::nxv2f16, 1},
1599     { ISD::FP_EXTEND, MVT::nxv4f32, MVT::nxv4f16, 1},
1600     { ISD::FP_EXTEND, MVT::nxv8f32, MVT::nxv8f16, 2},
1601 
1602     // Extend from nxvmf16 to nxvmf64.
1603     { ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2f16, 1},
1604     { ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4f16, 2},
1605     { ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8f16, 4},
1606 
1607     // Extend from nxvmf32 to nxvmf64.
1608     { ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2f32, 1},
1609     { ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4f32, 2},
1610     { ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8f32, 6},
1611 
1612     // Bitcasts from float to integer
1613     { ISD::BITCAST, MVT::nxv2f16, MVT::nxv2i16, 0 },
1614     { ISD::BITCAST, MVT::nxv4f16, MVT::nxv4i16, 0 },
1615     { ISD::BITCAST, MVT::nxv2f32, MVT::nxv2i32, 0 },
1616 
1617     // Bitcasts from integer to float
1618     { ISD::BITCAST, MVT::nxv2i16, MVT::nxv2f16, 0 },
1619     { ISD::BITCAST, MVT::nxv4i16, MVT::nxv4f16, 0 },
1620     { ISD::BITCAST, MVT::nxv2i32, MVT::nxv2f32, 0 },
1621   };
1622 
1623   if (const auto *Entry = ConvertCostTableLookup(ConversionTbl, ISD,
1624                                                  DstTy.getSimpleVT(),
1625                                                  SrcTy.getSimpleVT()))
1626     return AdjustCost(Entry->Cost);
1627 
1628   static const TypeConversionCostTblEntry FP16Tbl[] = {
1629       {ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f16, 1}, // fcvtzs
1630       {ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f16, 1},
1631       {ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f16, 1}, // fcvtzs
1632       {ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f16, 1},
1633       {ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f16, 2}, // fcvtl+fcvtzs
1634       {ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f16, 2},
1635       {ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f16, 2}, // fcvtzs+xtn
1636       {ISD::FP_TO_UINT, MVT::v8i8, MVT::v8f16, 2},
1637       {ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f16, 1}, // fcvtzs
1638       {ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f16, 1},
1639       {ISD::FP_TO_SINT, MVT::v8i32, MVT::v8f16, 4}, // 2*fcvtl+2*fcvtzs
1640       {ISD::FP_TO_UINT, MVT::v8i32, MVT::v8f16, 4},
1641       {ISD::FP_TO_SINT, MVT::v16i8, MVT::v16f16, 3}, // 2*fcvtzs+xtn
1642       {ISD::FP_TO_UINT, MVT::v16i8, MVT::v16f16, 3},
1643       {ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f16, 2}, // 2*fcvtzs
1644       {ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f16, 2},
1645       {ISD::FP_TO_SINT, MVT::v16i32, MVT::v16f16, 8}, // 4*fcvtl+4*fcvtzs
1646       {ISD::FP_TO_UINT, MVT::v16i32, MVT::v16f16, 8},
1647       {ISD::UINT_TO_FP, MVT::v8f16, MVT::v8i8, 2},   // ushll + ucvtf
1648       {ISD::SINT_TO_FP, MVT::v8f16, MVT::v8i8, 2},   // sshll + scvtf
1649       {ISD::UINT_TO_FP, MVT::v16f16, MVT::v16i8, 4}, // 2 * ushl(2) + 2 * ucvtf
1650       {ISD::SINT_TO_FP, MVT::v16f16, MVT::v16i8, 4}, // 2 * sshl(2) + 2 * scvtf
1651   };
1652 
1653   if (ST->hasFullFP16())
1654     if (const auto *Entry = ConvertCostTableLookup(
1655             FP16Tbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
1656       return AdjustCost(Entry->Cost);
1657 
1658   return AdjustCost(
1659       BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
1660 }
1661 
1662 InstructionCost AArch64TTIImpl::getExtractWithExtendCost(unsigned Opcode,
1663                                                          Type *Dst,
1664                                                          VectorType *VecTy,
1665                                                          unsigned Index) {
1666 
1667   // Make sure we were given a valid extend opcode.
1668   assert((Opcode == Instruction::SExt || Opcode == Instruction::ZExt) &&
1669          "Invalid opcode");
1670 
1671   // We are extending an element we extract from a vector, so the source type
1672   // of the extend is the element type of the vector.
1673   auto *Src = VecTy->getElementType();
1674 
1675   // Sign- and zero-extends are for integer types only.
1676   assert(isa<IntegerType>(Dst) && isa<IntegerType>(Src) && "Invalid type");
1677 
1678   // Get the cost for the extract. We compute the cost (if any) for the extend
1679   // below.
1680   InstructionCost Cost =
1681       getVectorInstrCost(Instruction::ExtractElement, VecTy, Index);
1682 
1683   // Legalize the types.
1684   auto VecLT = TLI->getTypeLegalizationCost(DL, VecTy);
1685   auto DstVT = TLI->getValueType(DL, Dst);
1686   auto SrcVT = TLI->getValueType(DL, Src);
1687   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
1688 
1689   // If the resulting type is still a vector and the destination type is legal,
1690   // we may get the extension for free. If not, get the default cost for the
1691   // extend.
1692   if (!VecLT.second.isVector() || !TLI->isTypeLegal(DstVT))
1693     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
1694                                    CostKind);
1695 
1696   // The destination type should be larger than the element type. If not, get
1697   // the default cost for the extend.
1698   if (DstVT.getFixedSizeInBits() < SrcVT.getFixedSizeInBits())
1699     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
1700                                    CostKind);
1701 
1702   switch (Opcode) {
1703   default:
1704     llvm_unreachable("Opcode should be either SExt or ZExt");
1705 
1706   // For sign-extends, we only need a smov, which performs the extension
1707   // automatically.
1708   case Instruction::SExt:
1709     return Cost;
1710 
1711   // For zero-extends, the extend is performed automatically by a umov unless
1712   // the destination type is i64 and the element type is i8 or i16.
1713   case Instruction::ZExt:
1714     if (DstVT.getSizeInBits() != 64u || SrcVT.getSizeInBits() == 32u)
1715       return Cost;
1716   }
1717 
1718   // If we are unable to perform the extend for free, get the default cost.
1719   return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
1720                                  CostKind);
1721 }
1722 
1723 InstructionCost AArch64TTIImpl::getCFInstrCost(unsigned Opcode,
1724                                                TTI::TargetCostKind CostKind,
1725                                                const Instruction *I) {
1726   if (CostKind != TTI::TCK_RecipThroughput)
1727     return Opcode == Instruction::PHI ? 0 : 1;
1728   assert(CostKind == TTI::TCK_RecipThroughput && "unexpected CostKind");
1729   // Branches are assumed to be predicted.
1730   return 0;
1731 }
1732 
1733 InstructionCost AArch64TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
1734                                                    unsigned Index) {
1735   assert(Val->isVectorTy() && "This must be a vector type");
1736 
1737   if (Index != -1U) {
1738     // Legalize the type.
1739     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
1740 
1741     // This type is legalized to a scalar type.
1742     if (!LT.second.isVector())
1743       return 0;
1744 
1745     // The type may be split. For fixed-width vectors we can normalize the
1746     // index to the new type.
1747     if (LT.second.isFixedLengthVector()) {
1748       unsigned Width = LT.second.getVectorNumElements();
1749       Index = Index % Width;
1750     }
1751 
1752     // The element at index zero is already inside the vector.
1753     if (Index == 0)
1754       return 0;
1755   }
1756 
1757   // All other insert/extracts cost this much.
1758   return ST->getVectorInsertExtractBaseCost();
1759 }
1760 
1761 InstructionCost AArch64TTIImpl::getArithmeticInstrCost(
1762     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
1763     TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info,
1764     TTI::OperandValueProperties Opd1PropInfo,
1765     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
1766     const Instruction *CxtI) {
1767   // TODO: Handle more cost kinds.
1768   if (CostKind != TTI::TCK_RecipThroughput)
1769     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
1770                                          Opd2Info, Opd1PropInfo,
1771                                          Opd2PropInfo, Args, CxtI);
1772 
1773   // Legalize the type.
1774   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
1775   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1776 
1777   switch (ISD) {
1778   default:
1779     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
1780                                          Opd2Info, Opd1PropInfo, Opd2PropInfo);
1781   case ISD::SDIV:
1782     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue &&
1783         Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
1784       // On AArch64, scalar signed division by constants power-of-two are
1785       // normally expanded to the sequence ADD + CMP + SELECT + SRA.
1786       // The OperandValue properties many not be same as that of previous
1787       // operation; conservatively assume OP_None.
1788       InstructionCost Cost = getArithmeticInstrCost(
1789           Instruction::Add, Ty, CostKind, Opd1Info, Opd2Info,
1790           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1791       Cost += getArithmeticInstrCost(Instruction::Sub, Ty, CostKind, Opd1Info,
1792                                      Opd2Info, TargetTransformInfo::OP_None,
1793                                      TargetTransformInfo::OP_None);
1794       Cost += getArithmeticInstrCost(
1795           Instruction::Select, Ty, CostKind, Opd1Info, Opd2Info,
1796           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1797       Cost += getArithmeticInstrCost(Instruction::AShr, Ty, CostKind, Opd1Info,
1798                                      Opd2Info, TargetTransformInfo::OP_None,
1799                                      TargetTransformInfo::OP_None);
1800       return Cost;
1801     }
1802     LLVM_FALLTHROUGH;
1803   case ISD::UDIV: {
1804     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue) {
1805       auto VT = TLI->getValueType(DL, Ty);
1806       if (TLI->isOperationLegalOrCustom(ISD::MULHU, VT)) {
1807         // Vector signed division by constant are expanded to the
1808         // sequence MULHS + ADD/SUB + SRA + SRL + ADD, and unsigned division
1809         // to MULHS + SUB + SRL + ADD + SRL.
1810         InstructionCost MulCost = getArithmeticInstrCost(
1811             Instruction::Mul, Ty, CostKind, Opd1Info, Opd2Info,
1812             TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1813         InstructionCost AddCost = getArithmeticInstrCost(
1814             Instruction::Add, Ty, CostKind, Opd1Info, Opd2Info,
1815             TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1816         InstructionCost ShrCost = getArithmeticInstrCost(
1817             Instruction::AShr, Ty, CostKind, Opd1Info, Opd2Info,
1818             TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1819         return MulCost * 2 + AddCost * 2 + ShrCost * 2 + 1;
1820       }
1821     }
1822 
1823     InstructionCost Cost = BaseT::getArithmeticInstrCost(
1824         Opcode, Ty, CostKind, Opd1Info, Opd2Info, Opd1PropInfo, Opd2PropInfo);
1825     if (Ty->isVectorTy()) {
1826       // On AArch64, vector divisions are not supported natively and are
1827       // expanded into scalar divisions of each pair of elements.
1828       Cost += getArithmeticInstrCost(Instruction::ExtractElement, Ty, CostKind,
1829                                      Opd1Info, Opd2Info, Opd1PropInfo,
1830                                      Opd2PropInfo);
1831       Cost += getArithmeticInstrCost(Instruction::InsertElement, Ty, CostKind,
1832                                      Opd1Info, Opd2Info, Opd1PropInfo,
1833                                      Opd2PropInfo);
1834       // TODO: if one of the arguments is scalar, then it's not necessary to
1835       // double the cost of handling the vector elements.
1836       Cost += Cost;
1837     }
1838     return Cost;
1839   }
1840   case ISD::MUL:
1841     // Since we do not have a MUL.2d instruction, a mul <2 x i64> is expensive
1842     // as elements are extracted from the vectors and the muls scalarized.
1843     // As getScalarizationOverhead is a bit too pessimistic, we estimate the
1844     // cost for a i64 vector directly here, which is:
1845     // - four 2-cost i64 extracts,
1846     // - two 2-cost i64 inserts, and
1847     // - two 1-cost muls.
1848     // So, for a v2i64 with LT.First = 1 the cost is 14, and for a v4i64 with
1849     // LT.first = 2 the cost is 28. If both operands are extensions it will not
1850     // need to scalarize so the cost can be cheaper (smull or umull).
1851     if (LT.second != MVT::v2i64 || isWideningInstruction(Ty, Opcode, Args))
1852       return LT.first;
1853     return LT.first * 14;
1854   case ISD::ADD:
1855   case ISD::XOR:
1856   case ISD::OR:
1857   case ISD::AND:
1858   case ISD::SRL:
1859   case ISD::SRA:
1860   case ISD::SHL:
1861     // These nodes are marked as 'custom' for combining purposes only.
1862     // We know that they are legal. See LowerAdd in ISelLowering.
1863     return LT.first;
1864 
1865   case ISD::FADD:
1866   case ISD::FSUB:
1867   case ISD::FMUL:
1868   case ISD::FDIV:
1869   case ISD::FNEG:
1870     // These nodes are marked as 'custom' just to lower them to SVE.
1871     // We know said lowering will incur no additional cost.
1872     if (!Ty->getScalarType()->isFP128Ty())
1873       return 2 * LT.first;
1874 
1875     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
1876                                          Opd2Info, Opd1PropInfo, Opd2PropInfo);
1877   }
1878 }
1879 
1880 InstructionCost AArch64TTIImpl::getAddressComputationCost(Type *Ty,
1881                                                           ScalarEvolution *SE,
1882                                                           const SCEV *Ptr) {
1883   // Address computations in vectorized code with non-consecutive addresses will
1884   // likely result in more instructions compared to scalar code where the
1885   // computation can more often be merged into the index mode. The resulting
1886   // extra micro-ops can significantly decrease throughput.
1887   unsigned NumVectorInstToHideOverhead = 10;
1888   int MaxMergeDistance = 64;
1889 
1890   if (Ty->isVectorTy() && SE &&
1891       !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
1892     return NumVectorInstToHideOverhead;
1893 
1894   // In many cases the address computation is not merged into the instruction
1895   // addressing mode.
1896   return 1;
1897 }
1898 
1899 InstructionCost AArch64TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
1900                                                    Type *CondTy,
1901                                                    CmpInst::Predicate VecPred,
1902                                                    TTI::TargetCostKind CostKind,
1903                                                    const Instruction *I) {
1904   // TODO: Handle other cost kinds.
1905   if (CostKind != TTI::TCK_RecipThroughput)
1906     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
1907                                      I);
1908 
1909   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1910   // We don't lower some vector selects well that are wider than the register
1911   // width.
1912   if (isa<FixedVectorType>(ValTy) && ISD == ISD::SELECT) {
1913     // We would need this many instructions to hide the scalarization happening.
1914     const int AmortizationCost = 20;
1915 
1916     // If VecPred is not set, check if we can get a predicate from the context
1917     // instruction, if its type matches the requested ValTy.
1918     if (VecPred == CmpInst::BAD_ICMP_PREDICATE && I && I->getType() == ValTy) {
1919       CmpInst::Predicate CurrentPred;
1920       if (match(I, m_Select(m_Cmp(CurrentPred, m_Value(), m_Value()), m_Value(),
1921                             m_Value())))
1922         VecPred = CurrentPred;
1923     }
1924     // Check if we have a compare/select chain that can be lowered using
1925     // a (F)CMxx & BFI pair.
1926     if (CmpInst::isIntPredicate(VecPred) || VecPred == CmpInst::FCMP_OLE ||
1927         VecPred == CmpInst::FCMP_OLT || VecPred == CmpInst::FCMP_OGT ||
1928         VecPred == CmpInst::FCMP_OGE || VecPred == CmpInst::FCMP_OEQ ||
1929         VecPred == CmpInst::FCMP_UNE) {
1930       static const auto ValidMinMaxTys = {
1931           MVT::v8i8,  MVT::v16i8, MVT::v4i16, MVT::v8i16, MVT::v2i32,
1932           MVT::v4i32, MVT::v2i64, MVT::v2f32, MVT::v4f32, MVT::v2f64};
1933       static const auto ValidFP16MinMaxTys = {MVT::v4f16, MVT::v8f16};
1934 
1935       auto LT = TLI->getTypeLegalizationCost(DL, ValTy);
1936       if (any_of(ValidMinMaxTys, [&LT](MVT M) { return M == LT.second; }) ||
1937           (ST->hasFullFP16() &&
1938            any_of(ValidFP16MinMaxTys, [&LT](MVT M) { return M == LT.second; })))
1939         return LT.first;
1940     }
1941 
1942     static const TypeConversionCostTblEntry
1943     VectorSelectTbl[] = {
1944       { ISD::SELECT, MVT::v16i1, MVT::v16i16, 16 },
1945       { ISD::SELECT, MVT::v8i1, MVT::v8i32, 8 },
1946       { ISD::SELECT, MVT::v16i1, MVT::v16i32, 16 },
1947       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost },
1948       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost },
1949       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost }
1950     };
1951 
1952     EVT SelCondTy = TLI->getValueType(DL, CondTy);
1953     EVT SelValTy = TLI->getValueType(DL, ValTy);
1954     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
1955       if (const auto *Entry = ConvertCostTableLookup(VectorSelectTbl, ISD,
1956                                                      SelCondTy.getSimpleVT(),
1957                                                      SelValTy.getSimpleVT()))
1958         return Entry->Cost;
1959     }
1960   }
1961   // The base case handles scalable vectors fine for now, since it treats the
1962   // cost as 1 * legalization cost.
1963   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
1964 }
1965 
1966 AArch64TTIImpl::TTI::MemCmpExpansionOptions
1967 AArch64TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
1968   TTI::MemCmpExpansionOptions Options;
1969   if (ST->requiresStrictAlign()) {
1970     // TODO: Add cost modeling for strict align. Misaligned loads expand to
1971     // a bunch of instructions when strict align is enabled.
1972     return Options;
1973   }
1974   Options.AllowOverlappingLoads = true;
1975   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
1976   Options.NumLoadsPerBlock = Options.MaxNumLoads;
1977   // TODO: Though vector loads usually perform well on AArch64, in some targets
1978   // they may wake up the FP unit, which raises the power consumption.  Perhaps
1979   // they could be used with no holds barred (-O3).
1980   Options.LoadSizes = {8, 4, 2, 1};
1981   return Options;
1982 }
1983 
1984 InstructionCost
1985 AArch64TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
1986                                       Align Alignment, unsigned AddressSpace,
1987                                       TTI::TargetCostKind CostKind) {
1988   if (useNeonVector(Src))
1989     return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1990                                         CostKind);
1991   auto LT = TLI->getTypeLegalizationCost(DL, Src);
1992   if (!LT.first.isValid())
1993     return InstructionCost::getInvalid();
1994 
1995   // The code-generator is currently not able to handle scalable vectors
1996   // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
1997   // it. This change will be removed when code-generation for these types is
1998   // sufficiently reliable.
1999   if (cast<VectorType>(Src)->getElementCount() == ElementCount::getScalable(1))
2000     return InstructionCost::getInvalid();
2001 
2002   return LT.first * 2;
2003 }
2004 
2005 static unsigned getSVEGatherScatterOverhead(unsigned Opcode) {
2006   return Opcode == Instruction::Load ? SVEGatherOverhead : SVEScatterOverhead;
2007 }
2008 
2009 InstructionCost AArch64TTIImpl::getGatherScatterOpCost(
2010     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
2011     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) {
2012   if (useNeonVector(DataTy))
2013     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
2014                                          Alignment, CostKind, I);
2015   auto *VT = cast<VectorType>(DataTy);
2016   auto LT = TLI->getTypeLegalizationCost(DL, DataTy);
2017   if (!LT.first.isValid())
2018     return InstructionCost::getInvalid();
2019 
2020   // The code-generator is currently not able to handle scalable vectors
2021   // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
2022   // it. This change will be removed when code-generation for these types is
2023   // sufficiently reliable.
2024   if (cast<VectorType>(DataTy)->getElementCount() ==
2025       ElementCount::getScalable(1))
2026     return InstructionCost::getInvalid();
2027 
2028   ElementCount LegalVF = LT.second.getVectorElementCount();
2029   InstructionCost MemOpCost =
2030       getMemoryOpCost(Opcode, VT->getElementType(), Alignment, 0, CostKind, I);
2031   // Add on an overhead cost for using gathers/scatters.
2032   // TODO: At the moment this is applied unilaterally for all CPUs, but at some
2033   // point we may want a per-CPU overhead.
2034   MemOpCost *= getSVEGatherScatterOverhead(Opcode);
2035   return LT.first * MemOpCost * getMaxNumElements(LegalVF);
2036 }
2037 
2038 bool AArch64TTIImpl::useNeonVector(const Type *Ty) const {
2039   return isa<FixedVectorType>(Ty) && !ST->useSVEForFixedLengthVectors();
2040 }
2041 
2042 InstructionCost AArch64TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Ty,
2043                                                 MaybeAlign Alignment,
2044                                                 unsigned AddressSpace,
2045                                                 TTI::TargetCostKind CostKind,
2046                                                 const Instruction *I) {
2047   EVT VT = TLI->getValueType(DL, Ty, true);
2048   // Type legalization can't handle structs
2049   if (VT == MVT::Other)
2050     return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace,
2051                                   CostKind);
2052 
2053   auto LT = TLI->getTypeLegalizationCost(DL, Ty);
2054   if (!LT.first.isValid())
2055     return InstructionCost::getInvalid();
2056 
2057   // The code-generator is currently not able to handle scalable vectors
2058   // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
2059   // it. This change will be removed when code-generation for these types is
2060   // sufficiently reliable.
2061   if (auto *VTy = dyn_cast<ScalableVectorType>(Ty))
2062     if (VTy->getElementCount() == ElementCount::getScalable(1))
2063       return InstructionCost::getInvalid();
2064 
2065   // TODO: consider latency as well for TCK_SizeAndLatency.
2066   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency)
2067     return LT.first;
2068 
2069   if (CostKind != TTI::TCK_RecipThroughput)
2070     return 1;
2071 
2072   if (ST->isMisaligned128StoreSlow() && Opcode == Instruction::Store &&
2073       LT.second.is128BitVector() && (!Alignment || *Alignment < Align(16))) {
2074     // Unaligned stores are extremely inefficient. We don't split all
2075     // unaligned 128-bit stores because the negative impact that has shown in
2076     // practice on inlined block copy code.
2077     // We make such stores expensive so that we will only vectorize if there
2078     // are 6 other instructions getting vectorized.
2079     const int AmortizationCost = 6;
2080 
2081     return LT.first * 2 * AmortizationCost;
2082   }
2083 
2084   // Check truncating stores and extending loads.
2085   if (useNeonVector(Ty) &&
2086       Ty->getScalarSizeInBits() != LT.second.getScalarSizeInBits()) {
2087     // v4i8 types are lowered to scalar a load/store and sshll/xtn.
2088     if (VT == MVT::v4i8)
2089       return 2;
2090     // Otherwise we need to scalarize.
2091     return cast<FixedVectorType>(Ty)->getNumElements() * 2;
2092   }
2093 
2094   return LT.first;
2095 }
2096 
2097 InstructionCost AArch64TTIImpl::getInterleavedMemoryOpCost(
2098     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
2099     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
2100     bool UseMaskForCond, bool UseMaskForGaps) {
2101   assert(Factor >= 2 && "Invalid interleave factor");
2102   auto *VecVTy = cast<FixedVectorType>(VecTy);
2103 
2104   if (!UseMaskForCond && !UseMaskForGaps &&
2105       Factor <= TLI->getMaxSupportedInterleaveFactor()) {
2106     unsigned NumElts = VecVTy->getNumElements();
2107     auto *SubVecTy =
2108         FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
2109 
2110     // ldN/stN only support legal vector types of size 64 or 128 in bits.
2111     // Accesses having vector types that are a multiple of 128 bits can be
2112     // matched to more than one ldN/stN instruction.
2113     bool UseScalable;
2114     if (NumElts % Factor == 0 &&
2115         TLI->isLegalInterleavedAccessType(SubVecTy, DL, UseScalable))
2116       return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL, UseScalable);
2117   }
2118 
2119   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
2120                                            Alignment, AddressSpace, CostKind,
2121                                            UseMaskForCond, UseMaskForGaps);
2122 }
2123 
2124 InstructionCost
2125 AArch64TTIImpl::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) {
2126   InstructionCost Cost = 0;
2127   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
2128   for (auto *I : Tys) {
2129     if (!I->isVectorTy())
2130       continue;
2131     if (I->getScalarSizeInBits() * cast<FixedVectorType>(I)->getNumElements() ==
2132         128)
2133       Cost += getMemoryOpCost(Instruction::Store, I, Align(128), 0, CostKind) +
2134               getMemoryOpCost(Instruction::Load, I, Align(128), 0, CostKind);
2135   }
2136   return Cost;
2137 }
2138 
2139 unsigned AArch64TTIImpl::getMaxInterleaveFactor(unsigned VF) {
2140   return ST->getMaxInterleaveFactor();
2141 }
2142 
2143 // For Falkor, we want to avoid having too many strided loads in a loop since
2144 // that can exhaust the HW prefetcher resources.  We adjust the unroller
2145 // MaxCount preference below to attempt to ensure unrolling doesn't create too
2146 // many strided loads.
2147 static void
2148 getFalkorUnrollingPreferences(Loop *L, ScalarEvolution &SE,
2149                               TargetTransformInfo::UnrollingPreferences &UP) {
2150   enum { MaxStridedLoads = 7 };
2151   auto countStridedLoads = [](Loop *L, ScalarEvolution &SE) {
2152     int StridedLoads = 0;
2153     // FIXME? We could make this more precise by looking at the CFG and
2154     // e.g. not counting loads in each side of an if-then-else diamond.
2155     for (const auto BB : L->blocks()) {
2156       for (auto &I : *BB) {
2157         LoadInst *LMemI = dyn_cast<LoadInst>(&I);
2158         if (!LMemI)
2159           continue;
2160 
2161         Value *PtrValue = LMemI->getPointerOperand();
2162         if (L->isLoopInvariant(PtrValue))
2163           continue;
2164 
2165         const SCEV *LSCEV = SE.getSCEV(PtrValue);
2166         const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
2167         if (!LSCEVAddRec || !LSCEVAddRec->isAffine())
2168           continue;
2169 
2170         // FIXME? We could take pairing of unrolled load copies into account
2171         // by looking at the AddRec, but we would probably have to limit this
2172         // to loops with no stores or other memory optimization barriers.
2173         ++StridedLoads;
2174         // We've seen enough strided loads that seeing more won't make a
2175         // difference.
2176         if (StridedLoads > MaxStridedLoads / 2)
2177           return StridedLoads;
2178       }
2179     }
2180     return StridedLoads;
2181   };
2182 
2183   int StridedLoads = countStridedLoads(L, SE);
2184   LLVM_DEBUG(dbgs() << "falkor-hwpf: detected " << StridedLoads
2185                     << " strided loads\n");
2186   // Pick the largest power of 2 unroll count that won't result in too many
2187   // strided loads.
2188   if (StridedLoads) {
2189     UP.MaxCount = 1 << Log2_32(MaxStridedLoads / StridedLoads);
2190     LLVM_DEBUG(dbgs() << "falkor-hwpf: setting unroll MaxCount to "
2191                       << UP.MaxCount << '\n');
2192   }
2193 }
2194 
2195 void AArch64TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
2196                                              TTI::UnrollingPreferences &UP,
2197                                              OptimizationRemarkEmitter *ORE) {
2198   // Enable partial unrolling and runtime unrolling.
2199   BaseT::getUnrollingPreferences(L, SE, UP, ORE);
2200 
2201   UP.UpperBound = true;
2202 
2203   // For inner loop, it is more likely to be a hot one, and the runtime check
2204   // can be promoted out from LICM pass, so the overhead is less, let's try
2205   // a larger threshold to unroll more loops.
2206   if (L->getLoopDepth() > 1)
2207     UP.PartialThreshold *= 2;
2208 
2209   // Disable partial & runtime unrolling on -Os.
2210   UP.PartialOptSizeThreshold = 0;
2211 
2212   if (ST->getProcFamily() == AArch64Subtarget::Falkor &&
2213       EnableFalkorHWPFUnrollFix)
2214     getFalkorUnrollingPreferences(L, SE, UP);
2215 
2216   // Scan the loop: don't unroll loops with calls as this could prevent
2217   // inlining. Don't unroll vector loops either, as they don't benefit much from
2218   // unrolling.
2219   for (auto *BB : L->getBlocks()) {
2220     for (auto &I : *BB) {
2221       // Don't unroll vectorised loop.
2222       if (I.getType()->isVectorTy())
2223         return;
2224 
2225       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
2226         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
2227           if (!isLoweredToCall(F))
2228             continue;
2229         }
2230         return;
2231       }
2232     }
2233   }
2234 
2235   // Enable runtime unrolling for in-order models
2236   // If mcpu is omitted, getProcFamily() returns AArch64Subtarget::Others, so by
2237   // checking for that case, we can ensure that the default behaviour is
2238   // unchanged
2239   if (ST->getProcFamily() != AArch64Subtarget::Others &&
2240       !ST->getSchedModel().isOutOfOrder()) {
2241     UP.Runtime = true;
2242     UP.Partial = true;
2243     UP.UnrollRemainder = true;
2244     UP.DefaultUnrollRuntimeCount = 4;
2245 
2246     UP.UnrollAndJam = true;
2247     UP.UnrollAndJamInnerLoopThreshold = 60;
2248   }
2249 }
2250 
2251 void AArch64TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
2252                                            TTI::PeelingPreferences &PP) {
2253   BaseT::getPeelingPreferences(L, SE, PP);
2254 }
2255 
2256 Value *AArch64TTIImpl::getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
2257                                                          Type *ExpectedType) {
2258   switch (Inst->getIntrinsicID()) {
2259   default:
2260     return nullptr;
2261   case Intrinsic::aarch64_neon_st2:
2262   case Intrinsic::aarch64_neon_st3:
2263   case Intrinsic::aarch64_neon_st4: {
2264     // Create a struct type
2265     StructType *ST = dyn_cast<StructType>(ExpectedType);
2266     if (!ST)
2267       return nullptr;
2268     unsigned NumElts = Inst->arg_size() - 1;
2269     if (ST->getNumElements() != NumElts)
2270       return nullptr;
2271     for (unsigned i = 0, e = NumElts; i != e; ++i) {
2272       if (Inst->getArgOperand(i)->getType() != ST->getElementType(i))
2273         return nullptr;
2274     }
2275     Value *Res = UndefValue::get(ExpectedType);
2276     IRBuilder<> Builder(Inst);
2277     for (unsigned i = 0, e = NumElts; i != e; ++i) {
2278       Value *L = Inst->getArgOperand(i);
2279       Res = Builder.CreateInsertValue(Res, L, i);
2280     }
2281     return Res;
2282   }
2283   case Intrinsic::aarch64_neon_ld2:
2284   case Intrinsic::aarch64_neon_ld3:
2285   case Intrinsic::aarch64_neon_ld4:
2286     if (Inst->getType() == ExpectedType)
2287       return Inst;
2288     return nullptr;
2289   }
2290 }
2291 
2292 bool AArch64TTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
2293                                         MemIntrinsicInfo &Info) {
2294   switch (Inst->getIntrinsicID()) {
2295   default:
2296     break;
2297   case Intrinsic::aarch64_neon_ld2:
2298   case Intrinsic::aarch64_neon_ld3:
2299   case Intrinsic::aarch64_neon_ld4:
2300     Info.ReadMem = true;
2301     Info.WriteMem = false;
2302     Info.PtrVal = Inst->getArgOperand(0);
2303     break;
2304   case Intrinsic::aarch64_neon_st2:
2305   case Intrinsic::aarch64_neon_st3:
2306   case Intrinsic::aarch64_neon_st4:
2307     Info.ReadMem = false;
2308     Info.WriteMem = true;
2309     Info.PtrVal = Inst->getArgOperand(Inst->arg_size() - 1);
2310     break;
2311   }
2312 
2313   switch (Inst->getIntrinsicID()) {
2314   default:
2315     return false;
2316   case Intrinsic::aarch64_neon_ld2:
2317   case Intrinsic::aarch64_neon_st2:
2318     Info.MatchingId = VECTOR_LDST_TWO_ELEMENTS;
2319     break;
2320   case Intrinsic::aarch64_neon_ld3:
2321   case Intrinsic::aarch64_neon_st3:
2322     Info.MatchingId = VECTOR_LDST_THREE_ELEMENTS;
2323     break;
2324   case Intrinsic::aarch64_neon_ld4:
2325   case Intrinsic::aarch64_neon_st4:
2326     Info.MatchingId = VECTOR_LDST_FOUR_ELEMENTS;
2327     break;
2328   }
2329   return true;
2330 }
2331 
2332 /// See if \p I should be considered for address type promotion. We check if \p
2333 /// I is a sext with right type and used in memory accesses. If it used in a
2334 /// "complex" getelementptr, we allow it to be promoted without finding other
2335 /// sext instructions that sign extended the same initial value. A getelementptr
2336 /// is considered as "complex" if it has more than 2 operands.
2337 bool AArch64TTIImpl::shouldConsiderAddressTypePromotion(
2338     const Instruction &I, bool &AllowPromotionWithoutCommonHeader) {
2339   bool Considerable = false;
2340   AllowPromotionWithoutCommonHeader = false;
2341   if (!isa<SExtInst>(&I))
2342     return false;
2343   Type *ConsideredSExtType =
2344       Type::getInt64Ty(I.getParent()->getParent()->getContext());
2345   if (I.getType() != ConsideredSExtType)
2346     return false;
2347   // See if the sext is the one with the right type and used in at least one
2348   // GetElementPtrInst.
2349   for (const User *U : I.users()) {
2350     if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
2351       Considerable = true;
2352       // A getelementptr is considered as "complex" if it has more than 2
2353       // operands. We will promote a SExt used in such complex GEP as we
2354       // expect some computation to be merged if they are done on 64 bits.
2355       if (GEPInst->getNumOperands() > 2) {
2356         AllowPromotionWithoutCommonHeader = true;
2357         break;
2358       }
2359     }
2360   }
2361   return Considerable;
2362 }
2363 
2364 bool AArch64TTIImpl::isLegalToVectorizeReduction(
2365     const RecurrenceDescriptor &RdxDesc, ElementCount VF) const {
2366   if (!VF.isScalable())
2367     return true;
2368 
2369   Type *Ty = RdxDesc.getRecurrenceType();
2370   if (Ty->isBFloatTy() || !isElementTypeLegalForScalableVector(Ty))
2371     return false;
2372 
2373   switch (RdxDesc.getRecurrenceKind()) {
2374   case RecurKind::Add:
2375   case RecurKind::FAdd:
2376   case RecurKind::And:
2377   case RecurKind::Or:
2378   case RecurKind::Xor:
2379   case RecurKind::SMin:
2380   case RecurKind::SMax:
2381   case RecurKind::UMin:
2382   case RecurKind::UMax:
2383   case RecurKind::FMin:
2384   case RecurKind::FMax:
2385   case RecurKind::SelectICmp:
2386   case RecurKind::SelectFCmp:
2387   case RecurKind::FMulAdd:
2388     return true;
2389   default:
2390     return false;
2391   }
2392 }
2393 
2394 InstructionCost
2395 AArch64TTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
2396                                        bool IsUnsigned,
2397                                        TTI::TargetCostKind CostKind) {
2398   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
2399 
2400   if (LT.second.getScalarType() == MVT::f16 && !ST->hasFullFP16())
2401     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
2402 
2403   assert((isa<ScalableVectorType>(Ty) == isa<ScalableVectorType>(CondTy)) &&
2404          "Both vector needs to be equally scalable");
2405 
2406   InstructionCost LegalizationCost = 0;
2407   if (LT.first > 1) {
2408     Type *LegalVTy = EVT(LT.second).getTypeForEVT(Ty->getContext());
2409     unsigned MinMaxOpcode =
2410         Ty->isFPOrFPVectorTy()
2411             ? Intrinsic::maxnum
2412             : (IsUnsigned ? Intrinsic::umin : Intrinsic::smin);
2413     IntrinsicCostAttributes Attrs(MinMaxOpcode, LegalVTy, {LegalVTy, LegalVTy});
2414     LegalizationCost = getIntrinsicInstrCost(Attrs, CostKind) * (LT.first - 1);
2415   }
2416 
2417   return LegalizationCost + /*Cost of horizontal reduction*/ 2;
2418 }
2419 
2420 InstructionCost AArch64TTIImpl::getArithmeticReductionCostSVE(
2421     unsigned Opcode, VectorType *ValTy, TTI::TargetCostKind CostKind) {
2422   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
2423   InstructionCost LegalizationCost = 0;
2424   if (LT.first > 1) {
2425     Type *LegalVTy = EVT(LT.second).getTypeForEVT(ValTy->getContext());
2426     LegalizationCost = getArithmeticInstrCost(Opcode, LegalVTy, CostKind);
2427     LegalizationCost *= LT.first - 1;
2428   }
2429 
2430   int ISD = TLI->InstructionOpcodeToISD(Opcode);
2431   assert(ISD && "Invalid opcode");
2432   // Add the final reduction cost for the legal horizontal reduction
2433   switch (ISD) {
2434   case ISD::ADD:
2435   case ISD::AND:
2436   case ISD::OR:
2437   case ISD::XOR:
2438   case ISD::FADD:
2439     return LegalizationCost + 2;
2440   default:
2441     return InstructionCost::getInvalid();
2442   }
2443 }
2444 
2445 InstructionCost
2446 AArch64TTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy,
2447                                            Optional<FastMathFlags> FMF,
2448                                            TTI::TargetCostKind CostKind) {
2449   if (TTI::requiresOrderedReduction(FMF)) {
2450     if (auto *FixedVTy = dyn_cast<FixedVectorType>(ValTy)) {
2451       InstructionCost BaseCost =
2452           BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
2453       // Add on extra cost to reflect the extra overhead on some CPUs. We still
2454       // end up vectorizing for more computationally intensive loops.
2455       return BaseCost + FixedVTy->getNumElements();
2456     }
2457 
2458     if (Opcode != Instruction::FAdd)
2459       return InstructionCost::getInvalid();
2460 
2461     auto *VTy = cast<ScalableVectorType>(ValTy);
2462     InstructionCost Cost =
2463         getArithmeticInstrCost(Opcode, VTy->getScalarType(), CostKind);
2464     Cost *= getMaxNumElements(VTy->getElementCount());
2465     return Cost;
2466   }
2467 
2468   if (isa<ScalableVectorType>(ValTy))
2469     return getArithmeticReductionCostSVE(Opcode, ValTy, CostKind);
2470 
2471   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
2472   MVT MTy = LT.second;
2473   int ISD = TLI->InstructionOpcodeToISD(Opcode);
2474   assert(ISD && "Invalid opcode");
2475 
2476   // Horizontal adds can use the 'addv' instruction. We model the cost of these
2477   // instructions as twice a normal vector add, plus 1 for each legalization
2478   // step (LT.first). This is the only arithmetic vector reduction operation for
2479   // which we have an instruction.
2480   // OR, XOR and AND costs should match the codegen from:
2481   // OR: llvm/test/CodeGen/AArch64/reduce-or.ll
2482   // XOR: llvm/test/CodeGen/AArch64/reduce-xor.ll
2483   // AND: llvm/test/CodeGen/AArch64/reduce-and.ll
2484   static const CostTblEntry CostTblNoPairwise[]{
2485       {ISD::ADD, MVT::v8i8,   2},
2486       {ISD::ADD, MVT::v16i8,  2},
2487       {ISD::ADD, MVT::v4i16,  2},
2488       {ISD::ADD, MVT::v8i16,  2},
2489       {ISD::ADD, MVT::v4i32,  2},
2490       {ISD::OR,  MVT::v8i8,  15},
2491       {ISD::OR,  MVT::v16i8, 17},
2492       {ISD::OR,  MVT::v4i16,  7},
2493       {ISD::OR,  MVT::v8i16,  9},
2494       {ISD::OR,  MVT::v2i32,  3},
2495       {ISD::OR,  MVT::v4i32,  5},
2496       {ISD::OR,  MVT::v2i64,  3},
2497       {ISD::XOR, MVT::v8i8,  15},
2498       {ISD::XOR, MVT::v16i8, 17},
2499       {ISD::XOR, MVT::v4i16,  7},
2500       {ISD::XOR, MVT::v8i16,  9},
2501       {ISD::XOR, MVT::v2i32,  3},
2502       {ISD::XOR, MVT::v4i32,  5},
2503       {ISD::XOR, MVT::v2i64,  3},
2504       {ISD::AND, MVT::v8i8,  15},
2505       {ISD::AND, MVT::v16i8, 17},
2506       {ISD::AND, MVT::v4i16,  7},
2507       {ISD::AND, MVT::v8i16,  9},
2508       {ISD::AND, MVT::v2i32,  3},
2509       {ISD::AND, MVT::v4i32,  5},
2510       {ISD::AND, MVT::v2i64,  3},
2511   };
2512   switch (ISD) {
2513   default:
2514     break;
2515   case ISD::ADD:
2516     if (const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy))
2517       return (LT.first - 1) + Entry->Cost;
2518     break;
2519   case ISD::XOR:
2520   case ISD::AND:
2521   case ISD::OR:
2522     const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy);
2523     if (!Entry)
2524       break;
2525     auto *ValVTy = cast<FixedVectorType>(ValTy);
2526     if (!ValVTy->getElementType()->isIntegerTy(1) &&
2527         MTy.getVectorNumElements() <= ValVTy->getNumElements() &&
2528         isPowerOf2_32(ValVTy->getNumElements())) {
2529       InstructionCost ExtraCost = 0;
2530       if (LT.first != 1) {
2531         // Type needs to be split, so there is an extra cost of LT.first - 1
2532         // arithmetic ops.
2533         auto *Ty = FixedVectorType::get(ValTy->getElementType(),
2534                                         MTy.getVectorNumElements());
2535         ExtraCost = getArithmeticInstrCost(Opcode, Ty, CostKind);
2536         ExtraCost *= LT.first - 1;
2537       }
2538       return Entry->Cost + ExtraCost;
2539     }
2540     break;
2541   }
2542   return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
2543 }
2544 
2545 InstructionCost AArch64TTIImpl::getSpliceCost(VectorType *Tp, int Index) {
2546   static const CostTblEntry ShuffleTbl[] = {
2547       { TTI::SK_Splice, MVT::nxv16i8,  1 },
2548       { TTI::SK_Splice, MVT::nxv8i16,  1 },
2549       { TTI::SK_Splice, MVT::nxv4i32,  1 },
2550       { TTI::SK_Splice, MVT::nxv2i64,  1 },
2551       { TTI::SK_Splice, MVT::nxv2f16,  1 },
2552       { TTI::SK_Splice, MVT::nxv4f16,  1 },
2553       { TTI::SK_Splice, MVT::nxv8f16,  1 },
2554       { TTI::SK_Splice, MVT::nxv2bf16, 1 },
2555       { TTI::SK_Splice, MVT::nxv4bf16, 1 },
2556       { TTI::SK_Splice, MVT::nxv8bf16, 1 },
2557       { TTI::SK_Splice, MVT::nxv2f32,  1 },
2558       { TTI::SK_Splice, MVT::nxv4f32,  1 },
2559       { TTI::SK_Splice, MVT::nxv2f64,  1 },
2560   };
2561 
2562   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
2563   Type *LegalVTy = EVT(LT.second).getTypeForEVT(Tp->getContext());
2564   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
2565   EVT PromotedVT = LT.second.getScalarType() == MVT::i1
2566                        ? TLI->getPromotedVTForPredicate(EVT(LT.second))
2567                        : LT.second;
2568   Type *PromotedVTy = EVT(PromotedVT).getTypeForEVT(Tp->getContext());
2569   InstructionCost LegalizationCost = 0;
2570   if (Index < 0) {
2571     LegalizationCost =
2572         getCmpSelInstrCost(Instruction::ICmp, PromotedVTy, PromotedVTy,
2573                            CmpInst::BAD_ICMP_PREDICATE, CostKind) +
2574         getCmpSelInstrCost(Instruction::Select, PromotedVTy, LegalVTy,
2575                            CmpInst::BAD_ICMP_PREDICATE, CostKind);
2576   }
2577 
2578   // Predicated splice are promoted when lowering. See AArch64ISelLowering.cpp
2579   // Cost performed on a promoted type.
2580   if (LT.second.getScalarType() == MVT::i1) {
2581     LegalizationCost +=
2582         getCastInstrCost(Instruction::ZExt, PromotedVTy, LegalVTy,
2583                          TTI::CastContextHint::None, CostKind) +
2584         getCastInstrCost(Instruction::Trunc, LegalVTy, PromotedVTy,
2585                          TTI::CastContextHint::None, CostKind);
2586   }
2587   const auto *Entry =
2588       CostTableLookup(ShuffleTbl, TTI::SK_Splice, PromotedVT.getSimpleVT());
2589   assert(Entry && "Illegal Type for Splice");
2590   LegalizationCost += Entry->Cost;
2591   return LegalizationCost * LT.first;
2592 }
2593 
2594 InstructionCost AArch64TTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
2595                                                VectorType *Tp,
2596                                                ArrayRef<int> Mask, int Index,
2597                                                VectorType *SubTp,
2598                                                ArrayRef<const Value *> Args) {
2599   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
2600   // If we have a Mask, and the LT is being legalized somehow, split the Mask
2601   // into smaller vectors and sum the cost of each shuffle.
2602   if (!Mask.empty() && isa<FixedVectorType>(Tp) && LT.second.isVector() &&
2603       Tp->getScalarSizeInBits() == LT.second.getScalarSizeInBits() &&
2604       cast<FixedVectorType>(Tp)->getNumElements() >
2605           LT.second.getVectorNumElements() &&
2606       !Index && !SubTp) {
2607     unsigned TpNumElts = cast<FixedVectorType>(Tp)->getNumElements();
2608     assert(Mask.size() == TpNumElts && "Expected Mask and Tp size to match!");
2609     unsigned LTNumElts = LT.second.getVectorNumElements();
2610     unsigned NumVecs = (TpNumElts + LTNumElts - 1) / LTNumElts;
2611     VectorType *NTp =
2612         VectorType::get(Tp->getScalarType(), LT.second.getVectorElementCount());
2613     InstructionCost Cost;
2614     for (unsigned N = 0; N < NumVecs; N++) {
2615       SmallVector<int> NMask;
2616       // Split the existing mask into chunks of size LTNumElts. Track the source
2617       // sub-vectors to ensure the result has at most 2 inputs.
2618       unsigned Source1, Source2;
2619       unsigned NumSources = 0;
2620       for (unsigned E = 0; E < LTNumElts; E++) {
2621         int MaskElt = (N * LTNumElts + E < TpNumElts) ? Mask[N * LTNumElts + E]
2622                                                       : UndefMaskElem;
2623         if (MaskElt < 0) {
2624           NMask.push_back(UndefMaskElem);
2625           continue;
2626         }
2627 
2628         // Calculate which source from the input this comes from and whether it
2629         // is new to us.
2630         unsigned Source = MaskElt / LTNumElts;
2631         if (NumSources == 0) {
2632           Source1 = Source;
2633           NumSources = 1;
2634         } else if (NumSources == 1 && Source != Source1) {
2635           Source2 = Source;
2636           NumSources = 2;
2637         } else if (NumSources >= 2 && Source != Source1 && Source != Source2) {
2638           NumSources++;
2639         }
2640 
2641         // Add to the new mask. For the NumSources>2 case these are not correct,
2642         // but are only used for the modular lane number.
2643         if (Source == Source1)
2644           NMask.push_back(MaskElt % LTNumElts);
2645         else if (Source == Source2)
2646           NMask.push_back(MaskElt % LTNumElts + LTNumElts);
2647         else
2648           NMask.push_back(MaskElt % LTNumElts);
2649       }
2650       // If the sub-mask has at most 2 input sub-vectors then re-cost it using
2651       // getShuffleCost. If not then cost it using the worst case.
2652       if (NumSources <= 2)
2653         Cost += getShuffleCost(NumSources <= 1 ? TTI::SK_PermuteSingleSrc
2654                                                : TTI::SK_PermuteTwoSrc,
2655                                NTp, NMask, 0, nullptr, Args);
2656       else if (any_of(enumerate(NMask), [&](const auto &ME) {
2657                  return ME.value() % LTNumElts == ME.index();
2658                }))
2659         Cost += LTNumElts - 1;
2660       else
2661         Cost += LTNumElts;
2662     }
2663     return Cost;
2664   }
2665 
2666   Kind = improveShuffleKindFromMask(Kind, Mask);
2667 
2668   // Check for broadcast loads.
2669   if (Kind == TTI::SK_Broadcast) {
2670     bool IsLoad = !Args.empty() && isa<LoadInst>(Args[0]);
2671     if (IsLoad && LT.second.isVector() &&
2672         isLegalBroadcastLoad(Tp->getElementType(),
2673                              LT.second.getVectorElementCount()))
2674       return 0; // broadcast is handled by ld1r
2675   }
2676 
2677   // If we have 4 elements for the shuffle and a Mask, get the cost straight
2678   // from the perfect shuffle tables.
2679   if (Mask.size() == 4 && Tp->getElementCount() == ElementCount::getFixed(4) &&
2680       (Tp->getScalarSizeInBits() == 16 || Tp->getScalarSizeInBits() == 32) &&
2681       all_of(Mask, [](int E) { return E < 8; }))
2682     return getPerfectShuffleCost(Mask);
2683 
2684   if (Kind == TTI::SK_Broadcast || Kind == TTI::SK_Transpose ||
2685       Kind == TTI::SK_Select || Kind == TTI::SK_PermuteSingleSrc ||
2686       Kind == TTI::SK_Reverse) {
2687 
2688     static const CostTblEntry ShuffleTbl[] = {
2689       // Broadcast shuffle kinds can be performed with 'dup'.
2690       { TTI::SK_Broadcast, MVT::v8i8,  1 },
2691       { TTI::SK_Broadcast, MVT::v16i8, 1 },
2692       { TTI::SK_Broadcast, MVT::v4i16, 1 },
2693       { TTI::SK_Broadcast, MVT::v8i16, 1 },
2694       { TTI::SK_Broadcast, MVT::v2i32, 1 },
2695       { TTI::SK_Broadcast, MVT::v4i32, 1 },
2696       { TTI::SK_Broadcast, MVT::v2i64, 1 },
2697       { TTI::SK_Broadcast, MVT::v2f32, 1 },
2698       { TTI::SK_Broadcast, MVT::v4f32, 1 },
2699       { TTI::SK_Broadcast, MVT::v2f64, 1 },
2700       // Transpose shuffle kinds can be performed with 'trn1/trn2' and
2701       // 'zip1/zip2' instructions.
2702       { TTI::SK_Transpose, MVT::v8i8,  1 },
2703       { TTI::SK_Transpose, MVT::v16i8, 1 },
2704       { TTI::SK_Transpose, MVT::v4i16, 1 },
2705       { TTI::SK_Transpose, MVT::v8i16, 1 },
2706       { TTI::SK_Transpose, MVT::v2i32, 1 },
2707       { TTI::SK_Transpose, MVT::v4i32, 1 },
2708       { TTI::SK_Transpose, MVT::v2i64, 1 },
2709       { TTI::SK_Transpose, MVT::v2f32, 1 },
2710       { TTI::SK_Transpose, MVT::v4f32, 1 },
2711       { TTI::SK_Transpose, MVT::v2f64, 1 },
2712       // Select shuffle kinds.
2713       // TODO: handle vXi8/vXi16.
2714       { TTI::SK_Select, MVT::v2i32, 1 }, // mov.
2715       { TTI::SK_Select, MVT::v4i32, 2 }, // rev+trn (or similar).
2716       { TTI::SK_Select, MVT::v2i64, 1 }, // mov.
2717       { TTI::SK_Select, MVT::v2f32, 1 }, // mov.
2718       { TTI::SK_Select, MVT::v4f32, 2 }, // rev+trn (or similar).
2719       { TTI::SK_Select, MVT::v2f64, 1 }, // mov.
2720       // PermuteSingleSrc shuffle kinds.
2721       { TTI::SK_PermuteSingleSrc, MVT::v2i32, 1 }, // mov.
2722       { TTI::SK_PermuteSingleSrc, MVT::v4i32, 3 }, // perfectshuffle worst case.
2723       { TTI::SK_PermuteSingleSrc, MVT::v2i64, 1 }, // mov.
2724       { TTI::SK_PermuteSingleSrc, MVT::v2f32, 1 }, // mov.
2725       { TTI::SK_PermuteSingleSrc, MVT::v4f32, 3 }, // perfectshuffle worst case.
2726       { TTI::SK_PermuteSingleSrc, MVT::v2f64, 1 }, // mov.
2727       { TTI::SK_PermuteSingleSrc, MVT::v4i16, 3 }, // perfectshuffle worst case.
2728       { TTI::SK_PermuteSingleSrc, MVT::v4f16, 3 }, // perfectshuffle worst case.
2729       { TTI::SK_PermuteSingleSrc, MVT::v4bf16, 3 }, // perfectshuffle worst case.
2730       { TTI::SK_PermuteSingleSrc, MVT::v8i16, 8 }, // constpool + load + tbl
2731       { TTI::SK_PermuteSingleSrc, MVT::v8f16, 8 }, // constpool + load + tbl
2732       { TTI::SK_PermuteSingleSrc, MVT::v8bf16, 8 }, // constpool + load + tbl
2733       { TTI::SK_PermuteSingleSrc, MVT::v8i8, 8 }, // constpool + load + tbl
2734       { TTI::SK_PermuteSingleSrc, MVT::v16i8, 8 }, // constpool + load + tbl
2735       // Reverse can be lowered with `rev`.
2736       { TTI::SK_Reverse, MVT::v2i32, 1 }, // mov.
2737       { TTI::SK_Reverse, MVT::v4i32, 2 }, // REV64; EXT
2738       { TTI::SK_Reverse, MVT::v2i64, 1 }, // mov.
2739       { TTI::SK_Reverse, MVT::v2f32, 1 }, // mov.
2740       { TTI::SK_Reverse, MVT::v4f32, 2 }, // REV64; EXT
2741       { TTI::SK_Reverse, MVT::v2f64, 1 }, // mov.
2742       // Broadcast shuffle kinds for scalable vectors
2743       { TTI::SK_Broadcast, MVT::nxv16i8,  1 },
2744       { TTI::SK_Broadcast, MVT::nxv8i16,  1 },
2745       { TTI::SK_Broadcast, MVT::nxv4i32,  1 },
2746       { TTI::SK_Broadcast, MVT::nxv2i64,  1 },
2747       { TTI::SK_Broadcast, MVT::nxv2f16,  1 },
2748       { TTI::SK_Broadcast, MVT::nxv4f16,  1 },
2749       { TTI::SK_Broadcast, MVT::nxv8f16,  1 },
2750       { TTI::SK_Broadcast, MVT::nxv2bf16, 1 },
2751       { TTI::SK_Broadcast, MVT::nxv4bf16, 1 },
2752       { TTI::SK_Broadcast, MVT::nxv8bf16, 1 },
2753       { TTI::SK_Broadcast, MVT::nxv2f32,  1 },
2754       { TTI::SK_Broadcast, MVT::nxv4f32,  1 },
2755       { TTI::SK_Broadcast, MVT::nxv2f64,  1 },
2756       { TTI::SK_Broadcast, MVT::nxv16i1,  1 },
2757       { TTI::SK_Broadcast, MVT::nxv8i1,   1 },
2758       { TTI::SK_Broadcast, MVT::nxv4i1,   1 },
2759       { TTI::SK_Broadcast, MVT::nxv2i1,   1 },
2760       // Handle the cases for vector.reverse with scalable vectors
2761       { TTI::SK_Reverse, MVT::nxv16i8,  1 },
2762       { TTI::SK_Reverse, MVT::nxv8i16,  1 },
2763       { TTI::SK_Reverse, MVT::nxv4i32,  1 },
2764       { TTI::SK_Reverse, MVT::nxv2i64,  1 },
2765       { TTI::SK_Reverse, MVT::nxv2f16,  1 },
2766       { TTI::SK_Reverse, MVT::nxv4f16,  1 },
2767       { TTI::SK_Reverse, MVT::nxv8f16,  1 },
2768       { TTI::SK_Reverse, MVT::nxv2bf16, 1 },
2769       { TTI::SK_Reverse, MVT::nxv4bf16, 1 },
2770       { TTI::SK_Reverse, MVT::nxv8bf16, 1 },
2771       { TTI::SK_Reverse, MVT::nxv2f32,  1 },
2772       { TTI::SK_Reverse, MVT::nxv4f32,  1 },
2773       { TTI::SK_Reverse, MVT::nxv2f64,  1 },
2774       { TTI::SK_Reverse, MVT::nxv16i1,  1 },
2775       { TTI::SK_Reverse, MVT::nxv8i1,   1 },
2776       { TTI::SK_Reverse, MVT::nxv4i1,   1 },
2777       { TTI::SK_Reverse, MVT::nxv2i1,   1 },
2778     };
2779     if (const auto *Entry = CostTableLookup(ShuffleTbl, Kind, LT.second))
2780       return LT.first * Entry->Cost;
2781   }
2782 
2783   if (Kind == TTI::SK_Splice && isa<ScalableVectorType>(Tp))
2784     return getSpliceCost(Tp, Index);
2785 
2786   // Inserting a subvector can often be done with either a D, S or H register
2787   // move, so long as the inserted vector is "aligned".
2788   if (Kind == TTI::SK_InsertSubvector && LT.second.isFixedLengthVector() &&
2789       LT.second.getSizeInBits() <= 128 && SubTp) {
2790     std::pair<InstructionCost, MVT> SubLT =
2791         TLI->getTypeLegalizationCost(DL, SubTp);
2792     if (SubLT.second.isVector()) {
2793       int NumElts = LT.second.getVectorNumElements();
2794       int NumSubElts = SubLT.second.getVectorNumElements();
2795       if ((Index % NumSubElts) == 0 && (NumElts % NumSubElts) == 0)
2796         return SubLT.first;
2797     }
2798   }
2799 
2800   return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp);
2801 }
2802