xref: /llvm-project/llvm/lib/Target/ARM/ARMTargetTransformInfo.cpp (revision 86fe4dfdb626d472f88bf8331da7cc98e9631cfe)
1 //===- ARMTargetTransformInfo.cpp - ARM 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 "ARMTargetTransformInfo.h"
10 #include "ARMSubtarget.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "llvm/ADT/APInt.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/CodeGen/CostTable.h"
16 #include "llvm/CodeGen/ISDOpcodes.h"
17 #include "llvm/CodeGen/ValueTypes.h"
18 #include "llvm/IR/BasicBlock.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Instruction.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/IntrinsicsARM.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/MC/SubtargetFeature.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MachineValueType.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Transforms/InstCombine/InstCombiner.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 #include "llvm/Transforms/Utils/LoopUtils.h"
36 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstdint>
40 #include <optional>
41 #include <utility>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "armtti"
46 
47 static cl::opt<bool> EnableMaskedLoadStores(
48   "enable-arm-maskedldst", cl::Hidden, cl::init(true),
49   cl::desc("Enable the generation of masked loads and stores"));
50 
51 static cl::opt<bool> DisableLowOverheadLoops(
52   "disable-arm-loloops", cl::Hidden, cl::init(false),
53   cl::desc("Disable the generation of low-overhead loops"));
54 
55 static cl::opt<bool>
56     AllowWLSLoops("allow-arm-wlsloops", cl::Hidden, cl::init(true),
57                   cl::desc("Enable the generation of WLS loops"));
58 
59 extern cl::opt<TailPredication::Mode> EnableTailPredication;
60 
61 extern cl::opt<bool> EnableMaskedGatherScatters;
62 
63 extern cl::opt<unsigned> MVEMaxSupportedInterleaveFactor;
64 
65 /// Convert a vector load intrinsic into a simple llvm load instruction.
66 /// This is beneficial when the underlying object being addressed comes
67 /// from a constant, since we get constant-folding for free.
68 static Value *simplifyNeonVld1(const IntrinsicInst &II, unsigned MemAlign,
69                                InstCombiner::BuilderTy &Builder) {
70   auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
71 
72   if (!IntrAlign)
73     return nullptr;
74 
75   unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign
76                            ? MemAlign
77                            : IntrAlign->getLimitedValue();
78 
79   if (!isPowerOf2_32(Alignment))
80     return nullptr;
81 
82   auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
83                                           PointerType::get(II.getType(), 0));
84   return Builder.CreateAlignedLoad(II.getType(), BCastInst, Align(Alignment));
85 }
86 
87 bool ARMTTIImpl::areInlineCompatible(const Function *Caller,
88                                      const Function *Callee) const {
89   const TargetMachine &TM = getTLI()->getTargetMachine();
90   const FeatureBitset &CallerBits =
91       TM.getSubtargetImpl(*Caller)->getFeatureBits();
92   const FeatureBitset &CalleeBits =
93       TM.getSubtargetImpl(*Callee)->getFeatureBits();
94 
95   // To inline a callee, all features not in the allowed list must match exactly.
96   bool MatchExact = (CallerBits & ~InlineFeaturesAllowed) ==
97                     (CalleeBits & ~InlineFeaturesAllowed);
98   // For features in the allowed list, the callee's features must be a subset of
99   // the callers'.
100   bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeaturesAllowed) ==
101                      (CalleeBits & InlineFeaturesAllowed);
102   return MatchExact && MatchSubset;
103 }
104 
105 TTI::AddressingModeKind
106 ARMTTIImpl::getPreferredAddressingMode(const Loop *L,
107                                        ScalarEvolution *SE) const {
108   if (ST->hasMVEIntegerOps())
109     return TTI::AMK_PostIndexed;
110 
111   if (L->getHeader()->getParent()->hasOptSize())
112     return TTI::AMK_None;
113 
114   if (ST->isMClass() && ST->isThumb2() &&
115       L->getNumBlocks() == 1)
116     return TTI::AMK_PreIndexed;
117 
118   return TTI::AMK_None;
119 }
120 
121 std::optional<Instruction *>
122 ARMTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
123   using namespace PatternMatch;
124   Intrinsic::ID IID = II.getIntrinsicID();
125   switch (IID) {
126   default:
127     break;
128   case Intrinsic::arm_neon_vld1: {
129     Align MemAlign =
130         getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
131                           &IC.getAssumptionCache(), &IC.getDominatorTree());
132     if (Value *V = simplifyNeonVld1(II, MemAlign.value(), IC.Builder)) {
133       return IC.replaceInstUsesWith(II, V);
134     }
135     break;
136   }
137 
138   case Intrinsic::arm_neon_vld2:
139   case Intrinsic::arm_neon_vld3:
140   case Intrinsic::arm_neon_vld4:
141   case Intrinsic::arm_neon_vld2lane:
142   case Intrinsic::arm_neon_vld3lane:
143   case Intrinsic::arm_neon_vld4lane:
144   case Intrinsic::arm_neon_vst1:
145   case Intrinsic::arm_neon_vst2:
146   case Intrinsic::arm_neon_vst3:
147   case Intrinsic::arm_neon_vst4:
148   case Intrinsic::arm_neon_vst2lane:
149   case Intrinsic::arm_neon_vst3lane:
150   case Intrinsic::arm_neon_vst4lane: {
151     Align MemAlign =
152         getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
153                           &IC.getAssumptionCache(), &IC.getDominatorTree());
154     unsigned AlignArg = II.arg_size() - 1;
155     Value *AlignArgOp = II.getArgOperand(AlignArg);
156     MaybeAlign Align = cast<ConstantInt>(AlignArgOp)->getMaybeAlignValue();
157     if (Align && *Align < MemAlign) {
158       return IC.replaceOperand(
159           II, AlignArg,
160           ConstantInt::get(Type::getInt32Ty(II.getContext()), MemAlign.value(),
161                            false));
162     }
163     break;
164   }
165 
166   case Intrinsic::arm_mve_pred_i2v: {
167     Value *Arg = II.getArgOperand(0);
168     Value *ArgArg;
169     if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(
170                        PatternMatch::m_Value(ArgArg))) &&
171         II.getType() == ArgArg->getType()) {
172       return IC.replaceInstUsesWith(II, ArgArg);
173     }
174     Constant *XorMask;
175     if (match(Arg, m_Xor(PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(
176                              PatternMatch::m_Value(ArgArg)),
177                          PatternMatch::m_Constant(XorMask))) &&
178         II.getType() == ArgArg->getType()) {
179       if (auto *CI = dyn_cast<ConstantInt>(XorMask)) {
180         if (CI->getValue().trunc(16).isAllOnes()) {
181           auto TrueVector = IC.Builder.CreateVectorSplat(
182               cast<FixedVectorType>(II.getType())->getNumElements(),
183               IC.Builder.getTrue());
184           return BinaryOperator::Create(Instruction::Xor, ArgArg, TrueVector);
185         }
186       }
187     }
188     KnownBits ScalarKnown(32);
189     if (IC.SimplifyDemandedBits(&II, 0, APInt::getLowBitsSet(32, 16),
190                                 ScalarKnown, 0)) {
191       return &II;
192     }
193     break;
194   }
195   case Intrinsic::arm_mve_pred_v2i: {
196     Value *Arg = II.getArgOperand(0);
197     Value *ArgArg;
198     if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_i2v>(
199                        PatternMatch::m_Value(ArgArg)))) {
200       return IC.replaceInstUsesWith(II, ArgArg);
201     }
202     if (!II.getMetadata(LLVMContext::MD_range)) {
203       Type *IntTy32 = Type::getInt32Ty(II.getContext());
204       Metadata *M[] = {
205           ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0)),
206           ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0x10000))};
207       II.setMetadata(LLVMContext::MD_range, MDNode::get(II.getContext(), M));
208       return &II;
209     }
210     break;
211   }
212   case Intrinsic::arm_mve_vadc:
213   case Intrinsic::arm_mve_vadc_predicated: {
214     unsigned CarryOp =
215         (II.getIntrinsicID() == Intrinsic::arm_mve_vadc_predicated) ? 3 : 2;
216     assert(II.getArgOperand(CarryOp)->getType()->getScalarSizeInBits() == 32 &&
217            "Bad type for intrinsic!");
218 
219     KnownBits CarryKnown(32);
220     if (IC.SimplifyDemandedBits(&II, CarryOp, APInt::getOneBitSet(32, 29),
221                                 CarryKnown)) {
222       return &II;
223     }
224     break;
225   }
226   case Intrinsic::arm_mve_vmldava: {
227     Instruction *I = cast<Instruction>(&II);
228     if (I->hasOneUse()) {
229       auto *User = cast<Instruction>(*I->user_begin());
230       Value *OpZ;
231       if (match(User, m_c_Add(m_Specific(I), m_Value(OpZ))) &&
232           match(I->getOperand(3), m_Zero())) {
233         Value *OpX = I->getOperand(4);
234         Value *OpY = I->getOperand(5);
235         Type *OpTy = OpX->getType();
236 
237         IC.Builder.SetInsertPoint(User);
238         Value *V =
239             IC.Builder.CreateIntrinsic(Intrinsic::arm_mve_vmldava, {OpTy},
240                                        {I->getOperand(0), I->getOperand(1),
241                                         I->getOperand(2), OpZ, OpX, OpY});
242 
243         IC.replaceInstUsesWith(*User, V);
244         return IC.eraseInstFromFunction(*User);
245       }
246     }
247     return std::nullopt;
248   }
249   }
250   return std::nullopt;
251 }
252 
253 std::optional<Value *> ARMTTIImpl::simplifyDemandedVectorEltsIntrinsic(
254     InstCombiner &IC, IntrinsicInst &II, APInt OrigDemandedElts,
255     APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3,
256     std::function<void(Instruction *, unsigned, APInt, APInt &)>
257         SimplifyAndSetOp) const {
258 
259   // Compute the demanded bits for a narrowing MVE intrinsic. The TopOpc is the
260   // opcode specifying a Top/Bottom instruction, which can change between
261   // instructions.
262   auto SimplifyNarrowInstrTopBottom =[&](unsigned TopOpc) {
263     unsigned NumElts = cast<FixedVectorType>(II.getType())->getNumElements();
264     unsigned IsTop = cast<ConstantInt>(II.getOperand(TopOpc))->getZExtValue();
265 
266     // The only odd/even lanes of operand 0 will only be demanded depending
267     // on whether this is a top/bottom instruction.
268     APInt DemandedElts =
269         APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
270                                        : APInt::getHighBitsSet(2, 1));
271     SimplifyAndSetOp(&II, 0, OrigDemandedElts & DemandedElts, UndefElts);
272     // The other lanes will be defined from the inserted elements.
273     UndefElts &= APInt::getSplat(NumElts, !IsTop ? APInt::getLowBitsSet(2, 1)
274                                                  : APInt::getHighBitsSet(2, 1));
275     return std::nullopt;
276   };
277 
278   switch (II.getIntrinsicID()) {
279   default:
280     break;
281   case Intrinsic::arm_mve_vcvt_narrow:
282     SimplifyNarrowInstrTopBottom(2);
283     break;
284   case Intrinsic::arm_mve_vqmovn:
285     SimplifyNarrowInstrTopBottom(4);
286     break;
287   case Intrinsic::arm_mve_vshrn:
288     SimplifyNarrowInstrTopBottom(7);
289     break;
290   }
291 
292   return std::nullopt;
293 }
294 
295 InstructionCost ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
296                                           TTI::TargetCostKind CostKind) {
297   assert(Ty->isIntegerTy());
298 
299  unsigned Bits = Ty->getPrimitiveSizeInBits();
300  if (Bits == 0 || Imm.getActiveBits() >= 64)
301    return 4;
302 
303   int64_t SImmVal = Imm.getSExtValue();
304   uint64_t ZImmVal = Imm.getZExtValue();
305   if (!ST->isThumb()) {
306     if ((SImmVal >= 0 && SImmVal < 65536) ||
307         (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
308         (ARM_AM::getSOImmVal(~ZImmVal) != -1))
309       return 1;
310     return ST->hasV6T2Ops() ? 2 : 3;
311   }
312   if (ST->isThumb2()) {
313     if ((SImmVal >= 0 && SImmVal < 65536) ||
314         (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
315         (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
316       return 1;
317     return ST->hasV6T2Ops() ? 2 : 3;
318   }
319   // Thumb1, any i8 imm cost 1.
320   if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
321     return 1;
322   if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
323     return 2;
324   // Load from constantpool.
325   return 3;
326 }
327 
328 // Constants smaller than 256 fit in the immediate field of
329 // Thumb1 instructions so we return a zero cost and 1 otherwise.
330 InstructionCost ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
331                                                   const APInt &Imm, Type *Ty) {
332   if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
333     return 0;
334 
335   return 1;
336 }
337 
338 // Checks whether Inst is part of a min(max()) or max(min()) pattern
339 // that will match to an SSAT instruction. Returns the instruction being
340 // saturated, or null if no saturation pattern was found.
341 static Value *isSSATMinMaxPattern(Instruction *Inst, const APInt &Imm) {
342   Value *LHS, *RHS;
343   ConstantInt *C;
344   SelectPatternFlavor InstSPF = matchSelectPattern(Inst, LHS, RHS).Flavor;
345 
346   if (InstSPF == SPF_SMAX &&
347       PatternMatch::match(RHS, PatternMatch::m_ConstantInt(C)) &&
348       C->getValue() == Imm && Imm.isNegative() && Imm.isNegatedPowerOf2()) {
349 
350     auto isSSatMin = [&](Value *MinInst) {
351       if (isa<SelectInst>(MinInst)) {
352         Value *MinLHS, *MinRHS;
353         ConstantInt *MinC;
354         SelectPatternFlavor MinSPF =
355             matchSelectPattern(MinInst, MinLHS, MinRHS).Flavor;
356         if (MinSPF == SPF_SMIN &&
357             PatternMatch::match(MinRHS, PatternMatch::m_ConstantInt(MinC)) &&
358             MinC->getValue() == ((-Imm) - 1))
359           return true;
360       }
361       return false;
362     };
363 
364     if (isSSatMin(Inst->getOperand(1)))
365       return cast<Instruction>(Inst->getOperand(1))->getOperand(1);
366     if (Inst->hasNUses(2) &&
367         (isSSatMin(*Inst->user_begin()) || isSSatMin(*(++Inst->user_begin()))))
368       return Inst->getOperand(1);
369   }
370   return nullptr;
371 }
372 
373 // Look for a FP Saturation pattern, where the instruction can be simplified to
374 // a fptosi.sat. max(min(fptosi)). The constant in this case is always free.
375 static bool isFPSatMinMaxPattern(Instruction *Inst, const APInt &Imm) {
376   if (Imm.getBitWidth() != 64 ||
377       Imm != APInt::getHighBitsSet(64, 33)) // -2147483648
378     return false;
379   Value *FP = isSSATMinMaxPattern(Inst, Imm);
380   if (!FP && isa<ICmpInst>(Inst) && Inst->hasOneUse())
381     FP = isSSATMinMaxPattern(cast<Instruction>(*Inst->user_begin()), Imm);
382   if (!FP)
383     return false;
384   return isa<FPToSIInst>(FP);
385 }
386 
387 InstructionCost ARMTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
388                                               const APInt &Imm, Type *Ty,
389                                               TTI::TargetCostKind CostKind,
390                                               Instruction *Inst) {
391   // Division by a constant can be turned into multiplication, but only if we
392   // know it's constant. So it's not so much that the immediate is cheap (it's
393   // not), but that the alternative is worse.
394   // FIXME: this is probably unneeded with GlobalISel.
395   if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
396        Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
397       Idx == 1)
398     return 0;
399 
400   // Leave any gep offsets for the CodeGenPrepare, which will do a better job at
401   // splitting any large offsets.
402   if (Opcode == Instruction::GetElementPtr && Idx != 0)
403     return 0;
404 
405   if (Opcode == Instruction::And) {
406     // UXTB/UXTH
407     if (Imm == 255 || Imm == 65535)
408       return 0;
409     // Conversion to BIC is free, and means we can use ~Imm instead.
410     return std::min(getIntImmCost(Imm, Ty, CostKind),
411                     getIntImmCost(~Imm, Ty, CostKind));
412   }
413 
414   if (Opcode == Instruction::Add)
415     // Conversion to SUB is free, and means we can use -Imm instead.
416     return std::min(getIntImmCost(Imm, Ty, CostKind),
417                     getIntImmCost(-Imm, Ty, CostKind));
418 
419   if (Opcode == Instruction::ICmp && Imm.isNegative() &&
420       Ty->getIntegerBitWidth() == 32) {
421     int64_t NegImm = -Imm.getSExtValue();
422     if (ST->isThumb2() && NegImm < 1<<12)
423       // icmp X, #-C -> cmn X, #C
424       return 0;
425     if (ST->isThumb() && NegImm < 1<<8)
426       // icmp X, #-C -> adds X, #C
427       return 0;
428   }
429 
430   // xor a, -1 can always be folded to MVN
431   if (Opcode == Instruction::Xor && Imm.isAllOnes())
432     return 0;
433 
434   // Ensures negative constant of min(max()) or max(min()) patterns that
435   // match to SSAT instructions don't get hoisted
436   if (Inst && ((ST->hasV6Ops() && !ST->isThumb()) || ST->isThumb2()) &&
437       Ty->getIntegerBitWidth() <= 32) {
438     if (isSSATMinMaxPattern(Inst, Imm) ||
439         (isa<ICmpInst>(Inst) && Inst->hasOneUse() &&
440          isSSATMinMaxPattern(cast<Instruction>(*Inst->user_begin()), Imm)))
441       return 0;
442   }
443 
444   if (Inst && ST->hasVFP2Base() && isFPSatMinMaxPattern(Inst, Imm))
445     return 0;
446 
447   // We can convert <= -1 to < 0, which is generally quite cheap.
448   if (Inst && Opcode == Instruction::ICmp && Idx == 1 && Imm.isAllOnesValue()) {
449     ICmpInst::Predicate Pred = cast<ICmpInst>(Inst)->getPredicate();
450     if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE)
451       return std::min(getIntImmCost(Imm, Ty, CostKind),
452                       getIntImmCost(Imm + 1, Ty, CostKind));
453   }
454 
455   return getIntImmCost(Imm, Ty, CostKind);
456 }
457 
458 InstructionCost ARMTTIImpl::getCFInstrCost(unsigned Opcode,
459                                            TTI::TargetCostKind CostKind,
460                                            const Instruction *I) {
461   if (CostKind == TTI::TCK_RecipThroughput &&
462       (ST->hasNEON() || ST->hasMVEIntegerOps())) {
463     // FIXME: The vectorizer is highly sensistive to the cost of these
464     // instructions, which suggests that it may be using the costs incorrectly.
465     // But, for now, just make them free to avoid performance regressions for
466     // vector targets.
467     return 0;
468   }
469   return BaseT::getCFInstrCost(Opcode, CostKind, I);
470 }
471 
472 InstructionCost ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst,
473                                              Type *Src,
474                                              TTI::CastContextHint CCH,
475                                              TTI::TargetCostKind CostKind,
476                                              const Instruction *I) {
477   int ISD = TLI->InstructionOpcodeToISD(Opcode);
478   assert(ISD && "Invalid opcode");
479 
480   // TODO: Allow non-throughput costs that aren't binary.
481   auto AdjustCost = [&CostKind](InstructionCost Cost) -> InstructionCost {
482     if (CostKind != TTI::TCK_RecipThroughput)
483       return Cost == 0 ? 0 : 1;
484     return Cost;
485   };
486   auto IsLegalFPType = [this](EVT VT) {
487     EVT EltVT = VT.getScalarType();
488     return (EltVT == MVT::f32 && ST->hasVFP2Base()) ||
489             (EltVT == MVT::f64 && ST->hasFP64()) ||
490             (EltVT == MVT::f16 && ST->hasFullFP16());
491   };
492 
493   EVT SrcTy = TLI->getValueType(DL, Src);
494   EVT DstTy = TLI->getValueType(DL, Dst);
495 
496   if (!SrcTy.isSimple() || !DstTy.isSimple())
497     return AdjustCost(
498         BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
499 
500   // Extending masked load/Truncating masked stores is expensive because we
501   // currently don't split them. This means that we'll likely end up
502   // loading/storing each element individually (hence the high cost).
503   if ((ST->hasMVEIntegerOps() &&
504        (Opcode == Instruction::Trunc || Opcode == Instruction::ZExt ||
505         Opcode == Instruction::SExt)) ||
506       (ST->hasMVEFloatOps() &&
507        (Opcode == Instruction::FPExt || Opcode == Instruction::FPTrunc) &&
508        IsLegalFPType(SrcTy) && IsLegalFPType(DstTy)))
509     if (CCH == TTI::CastContextHint::Masked && DstTy.getSizeInBits() > 128)
510       return 2 * DstTy.getVectorNumElements() *
511              ST->getMVEVectorCostFactor(CostKind);
512 
513   // The extend of other kinds of load is free
514   if (CCH == TTI::CastContextHint::Normal ||
515       CCH == TTI::CastContextHint::Masked) {
516     static const TypeConversionCostTblEntry LoadConversionTbl[] = {
517         {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0},
518         {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0},
519         {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0},
520         {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0},
521         {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0},
522         {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0},
523         {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1},
524         {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1},
525         {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1},
526         {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1},
527         {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1},
528         {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1},
529     };
530     if (const auto *Entry = ConvertCostTableLookup(
531             LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
532       return AdjustCost(Entry->Cost);
533 
534     static const TypeConversionCostTblEntry MVELoadConversionTbl[] = {
535         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0},
536         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0},
537         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0},
538         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0},
539         {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0},
540         {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0},
541         // The following extend from a legal type to an illegal type, so need to
542         // split the load. This introduced an extra load operation, but the
543         // extend is still "free".
544         {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1},
545         {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1},
546         {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 3},
547         {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 3},
548         {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 1},
549         {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 1},
550     };
551     if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
552       if (const auto *Entry =
553               ConvertCostTableLookup(MVELoadConversionTbl, ISD,
554                                      DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
555         return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
556     }
557 
558     static const TypeConversionCostTblEntry MVEFLoadConversionTbl[] = {
559         // FPExtends are similar but also require the VCVT instructions.
560         {ISD::FP_EXTEND, MVT::v4f32, MVT::v4f16, 1},
561         {ISD::FP_EXTEND, MVT::v8f32, MVT::v8f16, 3},
562     };
563     if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
564       if (const auto *Entry =
565               ConvertCostTableLookup(MVEFLoadConversionTbl, ISD,
566                                      DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
567         return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
568     }
569 
570     // The truncate of a store is free. This is the mirror of extends above.
571     static const TypeConversionCostTblEntry MVEStoreConversionTbl[] = {
572         {ISD::TRUNCATE, MVT::v4i32, MVT::v4i16, 0},
573         {ISD::TRUNCATE, MVT::v4i32, MVT::v4i8, 0},
574         {ISD::TRUNCATE, MVT::v8i16, MVT::v8i8, 0},
575         {ISD::TRUNCATE, MVT::v8i32, MVT::v8i16, 1},
576         {ISD::TRUNCATE, MVT::v8i32, MVT::v8i8, 1},
577         {ISD::TRUNCATE, MVT::v16i32, MVT::v16i8, 3},
578         {ISD::TRUNCATE, MVT::v16i16, MVT::v16i8, 1},
579     };
580     if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
581       if (const auto *Entry =
582               ConvertCostTableLookup(MVEStoreConversionTbl, ISD,
583                                      SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
584         return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
585     }
586 
587     static const TypeConversionCostTblEntry MVEFStoreConversionTbl[] = {
588         {ISD::FP_ROUND, MVT::v4f32, MVT::v4f16, 1},
589         {ISD::FP_ROUND, MVT::v8f32, MVT::v8f16, 3},
590     };
591     if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
592       if (const auto *Entry =
593               ConvertCostTableLookup(MVEFStoreConversionTbl, ISD,
594                                      SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
595         return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
596     }
597   }
598 
599   // NEON vector operations that can extend their inputs.
600   if ((ISD == ISD::SIGN_EXTEND || ISD == ISD::ZERO_EXTEND) &&
601       I && I->hasOneUse() && ST->hasNEON() && SrcTy.isVector()) {
602     static const TypeConversionCostTblEntry NEONDoubleWidthTbl[] = {
603       // vaddl
604       { ISD::ADD, MVT::v4i32, MVT::v4i16, 0 },
605       { ISD::ADD, MVT::v8i16, MVT::v8i8,  0 },
606       // vsubl
607       { ISD::SUB, MVT::v4i32, MVT::v4i16, 0 },
608       { ISD::SUB, MVT::v8i16, MVT::v8i8,  0 },
609       // vmull
610       { ISD::MUL, MVT::v4i32, MVT::v4i16, 0 },
611       { ISD::MUL, MVT::v8i16, MVT::v8i8,  0 },
612       // vshll
613       { ISD::SHL, MVT::v4i32, MVT::v4i16, 0 },
614       { ISD::SHL, MVT::v8i16, MVT::v8i8,  0 },
615     };
616 
617     auto *User = cast<Instruction>(*I->user_begin());
618     int UserISD = TLI->InstructionOpcodeToISD(User->getOpcode());
619     if (auto *Entry = ConvertCostTableLookup(NEONDoubleWidthTbl, UserISD,
620                                              DstTy.getSimpleVT(),
621                                              SrcTy.getSimpleVT())) {
622       return AdjustCost(Entry->Cost);
623     }
624   }
625 
626   // Single to/from double precision conversions.
627   if (Src->isVectorTy() && ST->hasNEON() &&
628       ((ISD == ISD::FP_ROUND && SrcTy.getScalarType() == MVT::f64 &&
629         DstTy.getScalarType() == MVT::f32) ||
630        (ISD == ISD::FP_EXTEND && SrcTy.getScalarType() == MVT::f32 &&
631         DstTy.getScalarType() == MVT::f64))) {
632     static const CostTblEntry NEONFltDblTbl[] = {
633         // Vector fptrunc/fpext conversions.
634         {ISD::FP_ROUND, MVT::v2f64, 2},
635         {ISD::FP_EXTEND, MVT::v2f32, 2},
636         {ISD::FP_EXTEND, MVT::v4f32, 4}};
637 
638     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Src);
639     if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
640       return AdjustCost(LT.first * Entry->Cost);
641   }
642 
643   // Some arithmetic, load and store operations have specific instructions
644   // to cast up/down their types automatically at no extra cost.
645   // TODO: Get these tables to know at least what the related operations are.
646   static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
647     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
648     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
649     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
650     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
651     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 0 },
652     { ISD::TRUNCATE,    MVT::v4i16, MVT::v4i32, 1 },
653 
654     // The number of vmovl instructions for the extension.
655     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8,  1 },
656     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8,  1 },
657     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8,  2 },
658     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8,  2 },
659     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8,  3 },
660     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8,  3 },
661     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
662     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
663     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
664     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
665     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
666     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
667     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
668     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
669     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
670     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
671     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
672     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
673 
674     // Operations that we legalize using splitting.
675     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i32, 6 },
676     { ISD::TRUNCATE,    MVT::v8i8, MVT::v8i32, 3 },
677 
678     // Vector float <-> i32 conversions.
679     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
680     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
681 
682     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
683     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
684     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
685     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
686     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
687     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
688     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
689     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
690     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
691     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
692     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
693     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
694     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
695     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
696     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
697     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
698     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
699     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
700     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
701     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
702 
703     { ISD::FP_TO_SINT,  MVT::v4i32, MVT::v4f32, 1 },
704     { ISD::FP_TO_UINT,  MVT::v4i32, MVT::v4f32, 1 },
705     { ISD::FP_TO_SINT,  MVT::v4i8, MVT::v4f32, 3 },
706     { ISD::FP_TO_UINT,  MVT::v4i8, MVT::v4f32, 3 },
707     { ISD::FP_TO_SINT,  MVT::v4i16, MVT::v4f32, 2 },
708     { ISD::FP_TO_UINT,  MVT::v4i16, MVT::v4f32, 2 },
709 
710     // Vector double <-> i32 conversions.
711     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
712     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
713 
714     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
715     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
716     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
717     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
718     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
719     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
720 
721     { ISD::FP_TO_SINT,  MVT::v2i32, MVT::v2f64, 2 },
722     { ISD::FP_TO_UINT,  MVT::v2i32, MVT::v2f64, 2 },
723     { ISD::FP_TO_SINT,  MVT::v8i16, MVT::v8f32, 4 },
724     { ISD::FP_TO_UINT,  MVT::v8i16, MVT::v8f32, 4 },
725     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v16f32, 8 },
726     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v16f32, 8 }
727   };
728 
729   if (SrcTy.isVector() && ST->hasNEON()) {
730     if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
731                                                    DstTy.getSimpleVT(),
732                                                    SrcTy.getSimpleVT()))
733       return AdjustCost(Entry->Cost);
734   }
735 
736   // Scalar float to integer conversions.
737   static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
738     { ISD::FP_TO_SINT,  MVT::i1, MVT::f32, 2 },
739     { ISD::FP_TO_UINT,  MVT::i1, MVT::f32, 2 },
740     { ISD::FP_TO_SINT,  MVT::i1, MVT::f64, 2 },
741     { ISD::FP_TO_UINT,  MVT::i1, MVT::f64, 2 },
742     { ISD::FP_TO_SINT,  MVT::i8, MVT::f32, 2 },
743     { ISD::FP_TO_UINT,  MVT::i8, MVT::f32, 2 },
744     { ISD::FP_TO_SINT,  MVT::i8, MVT::f64, 2 },
745     { ISD::FP_TO_UINT,  MVT::i8, MVT::f64, 2 },
746     { ISD::FP_TO_SINT,  MVT::i16, MVT::f32, 2 },
747     { ISD::FP_TO_UINT,  MVT::i16, MVT::f32, 2 },
748     { ISD::FP_TO_SINT,  MVT::i16, MVT::f64, 2 },
749     { ISD::FP_TO_UINT,  MVT::i16, MVT::f64, 2 },
750     { ISD::FP_TO_SINT,  MVT::i32, MVT::f32, 2 },
751     { ISD::FP_TO_UINT,  MVT::i32, MVT::f32, 2 },
752     { ISD::FP_TO_SINT,  MVT::i32, MVT::f64, 2 },
753     { ISD::FP_TO_UINT,  MVT::i32, MVT::f64, 2 },
754     { ISD::FP_TO_SINT,  MVT::i64, MVT::f32, 10 },
755     { ISD::FP_TO_UINT,  MVT::i64, MVT::f32, 10 },
756     { ISD::FP_TO_SINT,  MVT::i64, MVT::f64, 10 },
757     { ISD::FP_TO_UINT,  MVT::i64, MVT::f64, 10 }
758   };
759   if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
760     if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
761                                                    DstTy.getSimpleVT(),
762                                                    SrcTy.getSimpleVT()))
763       return AdjustCost(Entry->Cost);
764   }
765 
766   // Scalar integer to float conversions.
767   static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
768     { ISD::SINT_TO_FP,  MVT::f32, MVT::i1, 2 },
769     { ISD::UINT_TO_FP,  MVT::f32, MVT::i1, 2 },
770     { ISD::SINT_TO_FP,  MVT::f64, MVT::i1, 2 },
771     { ISD::UINT_TO_FP,  MVT::f64, MVT::i1, 2 },
772     { ISD::SINT_TO_FP,  MVT::f32, MVT::i8, 2 },
773     { ISD::UINT_TO_FP,  MVT::f32, MVT::i8, 2 },
774     { ISD::SINT_TO_FP,  MVT::f64, MVT::i8, 2 },
775     { ISD::UINT_TO_FP,  MVT::f64, MVT::i8, 2 },
776     { ISD::SINT_TO_FP,  MVT::f32, MVT::i16, 2 },
777     { ISD::UINT_TO_FP,  MVT::f32, MVT::i16, 2 },
778     { ISD::SINT_TO_FP,  MVT::f64, MVT::i16, 2 },
779     { ISD::UINT_TO_FP,  MVT::f64, MVT::i16, 2 },
780     { ISD::SINT_TO_FP,  MVT::f32, MVT::i32, 2 },
781     { ISD::UINT_TO_FP,  MVT::f32, MVT::i32, 2 },
782     { ISD::SINT_TO_FP,  MVT::f64, MVT::i32, 2 },
783     { ISD::UINT_TO_FP,  MVT::f64, MVT::i32, 2 },
784     { ISD::SINT_TO_FP,  MVT::f32, MVT::i64, 10 },
785     { ISD::UINT_TO_FP,  MVT::f32, MVT::i64, 10 },
786     { ISD::SINT_TO_FP,  MVT::f64, MVT::i64, 10 },
787     { ISD::UINT_TO_FP,  MVT::f64, MVT::i64, 10 }
788   };
789 
790   if (SrcTy.isInteger() && ST->hasNEON()) {
791     if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
792                                                    ISD, DstTy.getSimpleVT(),
793                                                    SrcTy.getSimpleVT()))
794       return AdjustCost(Entry->Cost);
795   }
796 
797   // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one
798   // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext
799   // are linearised so take more.
800   static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = {
801     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
802     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
803     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
804     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
805     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 },
806     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 },
807     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
808     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
809     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 },
810     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
811     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 },
812     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 },
813   };
814 
815   if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
816     if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl,
817                                                    ISD, DstTy.getSimpleVT(),
818                                                    SrcTy.getSimpleVT()))
819       return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
820   }
821 
822   if (ISD == ISD::FP_ROUND || ISD == ISD::FP_EXTEND) {
823     // As general rule, fp converts that were not matched above are scalarized
824     // and cost 1 vcvt for each lane, so long as the instruction is available.
825     // If not it will become a series of function calls.
826     const InstructionCost CallCost =
827         getCallInstrCost(nullptr, Dst, {Src}, CostKind);
828     int Lanes = 1;
829     if (SrcTy.isFixedLengthVector())
830       Lanes = SrcTy.getVectorNumElements();
831 
832     if (IsLegalFPType(SrcTy) && IsLegalFPType(DstTy))
833       return Lanes;
834     else
835       return Lanes * CallCost;
836   }
837 
838   if (ISD == ISD::TRUNCATE && ST->hasMVEIntegerOps() &&
839       SrcTy.isFixedLengthVector()) {
840     // Treat a truncate with larger than legal source (128bits for MVE) as
841     // expensive, 2 instructions per lane.
842     if ((SrcTy.getScalarType() == MVT::i8 ||
843          SrcTy.getScalarType() == MVT::i16 ||
844          SrcTy.getScalarType() == MVT::i32) &&
845         SrcTy.getSizeInBits() > 128 &&
846         SrcTy.getSizeInBits() > DstTy.getSizeInBits())
847       return SrcTy.getVectorNumElements() * 2;
848   }
849 
850   // Scalar integer conversion costs.
851   static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
852     // i16 -> i64 requires two dependent operations.
853     { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
854 
855     // Truncates on i64 are assumed to be free.
856     { ISD::TRUNCATE,    MVT::i32, MVT::i64, 0 },
857     { ISD::TRUNCATE,    MVT::i16, MVT::i64, 0 },
858     { ISD::TRUNCATE,    MVT::i8,  MVT::i64, 0 },
859     { ISD::TRUNCATE,    MVT::i1,  MVT::i64, 0 }
860   };
861 
862   if (SrcTy.isInteger()) {
863     if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
864                                                    DstTy.getSimpleVT(),
865                                                    SrcTy.getSimpleVT()))
866       return AdjustCost(Entry->Cost);
867   }
868 
869   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
870                      ? ST->getMVEVectorCostFactor(CostKind)
871                      : 1;
872   return AdjustCost(
873       BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
874 }
875 
876 InstructionCost ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
877                                                unsigned Index) {
878   // Penalize inserting into an D-subregister. We end up with a three times
879   // lower estimated throughput on swift.
880   if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
881       ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
882     return 3;
883 
884   if (ST->hasNEON() && (Opcode == Instruction::InsertElement ||
885                         Opcode == Instruction::ExtractElement)) {
886     // Cross-class copies are expensive on many microarchitectures,
887     // so assume they are expensive by default.
888     if (cast<VectorType>(ValTy)->getElementType()->isIntegerTy())
889       return 3;
890 
891     // Even if it's not a cross class copy, this likely leads to mixing
892     // of NEON and VFP code and should be therefore penalized.
893     if (ValTy->isVectorTy() &&
894         ValTy->getScalarSizeInBits() <= 32)
895       return std::max<InstructionCost>(
896           BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U);
897   }
898 
899   if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement ||
900                                  Opcode == Instruction::ExtractElement)) {
901     // Integer cross-lane moves are more expensive than float, which can
902     // sometimes just be vmovs. Integer involve being passes to GPR registers,
903     // causing more of a delay.
904     std::pair<InstructionCost, MVT> LT =
905         getTypeLegalizationCost(ValTy->getScalarType());
906     return LT.first * (ValTy->getScalarType()->isIntegerTy() ? 4 : 1);
907   }
908 
909   return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
910 }
911 
912 InstructionCost ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
913                                                Type *CondTy,
914                                                CmpInst::Predicate VecPred,
915                                                TTI::TargetCostKind CostKind,
916                                                const Instruction *I) {
917   int ISD = TLI->InstructionOpcodeToISD(Opcode);
918 
919   // Thumb scalar code size cost for select.
920   if (CostKind == TTI::TCK_CodeSize && ISD == ISD::SELECT &&
921       ST->isThumb() && !ValTy->isVectorTy()) {
922     // Assume expensive structs.
923     if (TLI->getValueType(DL, ValTy, true) == MVT::Other)
924       return TTI::TCC_Expensive;
925 
926     // Select costs can vary because they:
927     // - may require one or more conditional mov (including an IT),
928     // - can't operate directly on immediates,
929     // - require live flags, which we can't copy around easily.
930     InstructionCost Cost = getTypeLegalizationCost(ValTy).first;
931 
932     // Possible IT instruction for Thumb2, or more for Thumb1.
933     ++Cost;
934 
935     // i1 values may need rematerialising by using mov immediates and/or
936     // flag setting instructions.
937     if (ValTy->isIntegerTy(1))
938       ++Cost;
939 
940     return Cost;
941   }
942 
943   // If this is a vector min/max/abs, use the cost of that intrinsic directly
944   // instead. Hopefully when min/max intrinsics are more prevalent this code
945   // will not be needed.
946   const Instruction *Sel = I;
947   if ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && Sel &&
948       Sel->hasOneUse())
949     Sel = cast<Instruction>(Sel->user_back());
950   if (Sel && ValTy->isVectorTy() &&
951       (ValTy->isIntOrIntVectorTy() || ValTy->isFPOrFPVectorTy())) {
952     const Value *LHS, *RHS;
953     SelectPatternFlavor SPF = matchSelectPattern(Sel, LHS, RHS).Flavor;
954     unsigned IID = 0;
955     switch (SPF) {
956     case SPF_ABS:
957       IID = Intrinsic::abs;
958       break;
959     case SPF_SMIN:
960       IID = Intrinsic::smin;
961       break;
962     case SPF_SMAX:
963       IID = Intrinsic::smax;
964       break;
965     case SPF_UMIN:
966       IID = Intrinsic::umin;
967       break;
968     case SPF_UMAX:
969       IID = Intrinsic::umax;
970       break;
971     case SPF_FMINNUM:
972       IID = Intrinsic::minnum;
973       break;
974     case SPF_FMAXNUM:
975       IID = Intrinsic::maxnum;
976       break;
977     default:
978       break;
979     }
980     if (IID) {
981       // The ICmp is free, the select gets the cost of the min/max/etc
982       if (Sel != I)
983         return 0;
984       IntrinsicCostAttributes CostAttrs(IID, ValTy, {ValTy, ValTy});
985       return getIntrinsicInstrCost(CostAttrs, CostKind);
986     }
987   }
988 
989   // On NEON a vector select gets lowered to vbsl.
990   if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT && CondTy) {
991     // Lowering of some vector selects is currently far from perfect.
992     static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
993       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
994       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
995       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
996     };
997 
998     EVT SelCondTy = TLI->getValueType(DL, CondTy);
999     EVT SelValTy = TLI->getValueType(DL, ValTy);
1000     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
1001       if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
1002                                                      SelCondTy.getSimpleVT(),
1003                                                      SelValTy.getSimpleVT()))
1004         return Entry->Cost;
1005     }
1006 
1007     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1008     return LT.first;
1009   }
1010 
1011   if (ST->hasMVEIntegerOps() && ValTy->isVectorTy() &&
1012       (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
1013       cast<FixedVectorType>(ValTy)->getNumElements() > 1) {
1014     FixedVectorType *VecValTy = cast<FixedVectorType>(ValTy);
1015     FixedVectorType *VecCondTy = dyn_cast_or_null<FixedVectorType>(CondTy);
1016     if (!VecCondTy)
1017       VecCondTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(VecValTy));
1018 
1019     // If we don't have mve.fp any fp operations will need to be scalarized.
1020     if (Opcode == Instruction::FCmp && !ST->hasMVEFloatOps()) {
1021       // One scalaization insert, one scalarization extract and the cost of the
1022       // fcmps.
1023       return BaseT::getScalarizationOverhead(VecValTy, false, true) +
1024              BaseT::getScalarizationOverhead(VecCondTy, true, false) +
1025              VecValTy->getNumElements() *
1026                  getCmpSelInstrCost(Opcode, ValTy->getScalarType(),
1027                                     VecCondTy->getScalarType(), VecPred, CostKind,
1028                                     I);
1029     }
1030 
1031     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1032     int BaseCost = ST->getMVEVectorCostFactor(CostKind);
1033     // There are two types - the input that specifies the type of the compare
1034     // and the output vXi1 type. Because we don't know how the output will be
1035     // split, we may need an expensive shuffle to get two in sync. This has the
1036     // effect of making larger than legal compares (v8i32 for example)
1037     // expensive.
1038     if (LT.second.isVector() && LT.second.getVectorNumElements() > 2) {
1039       if (LT.first > 1)
1040         return LT.first * BaseCost +
1041                BaseT::getScalarizationOverhead(VecCondTy, true, false);
1042       return BaseCost;
1043     }
1044   }
1045 
1046   // Default to cheap (throughput/size of 1 instruction) but adjust throughput
1047   // for "multiple beats" potentially needed by MVE instructions.
1048   int BaseCost = 1;
1049   if (ST->hasMVEIntegerOps() && ValTy->isVectorTy())
1050     BaseCost = ST->getMVEVectorCostFactor(CostKind);
1051 
1052   return BaseCost *
1053          BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
1054 }
1055 
1056 InstructionCost ARMTTIImpl::getAddressComputationCost(Type *Ty,
1057                                                       ScalarEvolution *SE,
1058                                                       const SCEV *Ptr) {
1059   // Address computations in vectorized code with non-consecutive addresses will
1060   // likely result in more instructions compared to scalar code where the
1061   // computation can more often be merged into the index mode. The resulting
1062   // extra micro-ops can significantly decrease throughput.
1063   unsigned NumVectorInstToHideOverhead = 10;
1064   int MaxMergeDistance = 64;
1065 
1066   if (ST->hasNEON()) {
1067     if (Ty->isVectorTy() && SE &&
1068         !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
1069       return NumVectorInstToHideOverhead;
1070 
1071     // In many cases the address computation is not merged into the instruction
1072     // addressing mode.
1073     return 1;
1074   }
1075   return BaseT::getAddressComputationCost(Ty, SE, Ptr);
1076 }
1077 
1078 bool ARMTTIImpl::isProfitableLSRChainElement(Instruction *I) {
1079   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1080     // If a VCTP is part of a chain, it's already profitable and shouldn't be
1081     // optimized, else LSR may block tail-predication.
1082     switch (II->getIntrinsicID()) {
1083     case Intrinsic::arm_mve_vctp8:
1084     case Intrinsic::arm_mve_vctp16:
1085     case Intrinsic::arm_mve_vctp32:
1086     case Intrinsic::arm_mve_vctp64:
1087       return true;
1088     default:
1089       break;
1090     }
1091   }
1092   return false;
1093 }
1094 
1095 bool ARMTTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) {
1096   if (!EnableMaskedLoadStores || !ST->hasMVEIntegerOps())
1097     return false;
1098 
1099   if (auto *VecTy = dyn_cast<FixedVectorType>(DataTy)) {
1100     // Don't support v2i1 yet.
1101     if (VecTy->getNumElements() == 2)
1102       return false;
1103 
1104     // We don't support extending fp types.
1105      unsigned VecWidth = DataTy->getPrimitiveSizeInBits();
1106     if (VecWidth != 128 && VecTy->getElementType()->isFloatingPointTy())
1107       return false;
1108   }
1109 
1110   unsigned EltWidth = DataTy->getScalarSizeInBits();
1111   return (EltWidth == 32 && Alignment >= 4) ||
1112          (EltWidth == 16 && Alignment >= 2) || (EltWidth == 8);
1113 }
1114 
1115 bool ARMTTIImpl::isLegalMaskedGather(Type *Ty, Align Alignment) {
1116   if (!EnableMaskedGatherScatters || !ST->hasMVEIntegerOps())
1117     return false;
1118 
1119   unsigned EltWidth = Ty->getScalarSizeInBits();
1120   return ((EltWidth == 32 && Alignment >= 4) ||
1121           (EltWidth == 16 && Alignment >= 2) || EltWidth == 8);
1122 }
1123 
1124 /// Given a memcpy/memset/memmove instruction, return the number of memory
1125 /// operations performed, via querying findOptimalMemOpLowering. Returns -1 if a
1126 /// call is used.
1127 int ARMTTIImpl::getNumMemOps(const IntrinsicInst *I) const {
1128   MemOp MOp;
1129   unsigned DstAddrSpace = ~0u;
1130   unsigned SrcAddrSpace = ~0u;
1131   const Function *F = I->getParent()->getParent();
1132 
1133   if (const auto *MC = dyn_cast<MemTransferInst>(I)) {
1134     ConstantInt *C = dyn_cast<ConstantInt>(MC->getLength());
1135     // If 'size' is not a constant, a library call will be generated.
1136     if (!C)
1137       return -1;
1138 
1139     const unsigned Size = C->getValue().getZExtValue();
1140     const Align DstAlign = *MC->getDestAlign();
1141     const Align SrcAlign = *MC->getSourceAlign();
1142 
1143     MOp = MemOp::Copy(Size, /*DstAlignCanChange*/ false, DstAlign, SrcAlign,
1144                       /*IsVolatile*/ false);
1145     DstAddrSpace = MC->getDestAddressSpace();
1146     SrcAddrSpace = MC->getSourceAddressSpace();
1147   }
1148   else if (const auto *MS = dyn_cast<MemSetInst>(I)) {
1149     ConstantInt *C = dyn_cast<ConstantInt>(MS->getLength());
1150     // If 'size' is not a constant, a library call will be generated.
1151     if (!C)
1152       return -1;
1153 
1154     const unsigned Size = C->getValue().getZExtValue();
1155     const Align DstAlign = *MS->getDestAlign();
1156 
1157     MOp = MemOp::Set(Size, /*DstAlignCanChange*/ false, DstAlign,
1158                      /*IsZeroMemset*/ false, /*IsVolatile*/ false);
1159     DstAddrSpace = MS->getDestAddressSpace();
1160   }
1161   else
1162     llvm_unreachable("Expected a memcpy/move or memset!");
1163 
1164   unsigned Limit, Factor = 2;
1165   switch(I->getIntrinsicID()) {
1166     case Intrinsic::memcpy:
1167       Limit = TLI->getMaxStoresPerMemcpy(F->hasMinSize());
1168       break;
1169     case Intrinsic::memmove:
1170       Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize());
1171       break;
1172     case Intrinsic::memset:
1173       Limit = TLI->getMaxStoresPerMemset(F->hasMinSize());
1174       Factor = 1;
1175       break;
1176     default:
1177       llvm_unreachable("Expected a memcpy/move or memset!");
1178   }
1179 
1180   // MemOps will be poplulated with a list of data types that needs to be
1181   // loaded and stored. That's why we multiply the number of elements by 2 to
1182   // get the cost for this memcpy.
1183   std::vector<EVT> MemOps;
1184   if (getTLI()->findOptimalMemOpLowering(
1185           MemOps, Limit, MOp, DstAddrSpace,
1186           SrcAddrSpace, F->getAttributes()))
1187     return MemOps.size() * Factor;
1188 
1189   // If we can't find an optimal memop lowering, return the default cost
1190   return -1;
1191 }
1192 
1193 InstructionCost ARMTTIImpl::getMemcpyCost(const Instruction *I) {
1194   int NumOps = getNumMemOps(cast<IntrinsicInst>(I));
1195 
1196   // To model the cost of a library call, we assume 1 for the call, and
1197   // 3 for the argument setup.
1198   if (NumOps == -1)
1199     return 4;
1200   return NumOps;
1201 }
1202 
1203 InstructionCost ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
1204                                            VectorType *Tp, ArrayRef<int> Mask,
1205                                            TTI::TargetCostKind CostKind,
1206                                            int Index, VectorType *SubTp,
1207                                            ArrayRef<const Value *> Args) {
1208   Kind = improveShuffleKindFromMask(Kind, Mask);
1209   if (ST->hasNEON()) {
1210     if (Kind == TTI::SK_Broadcast) {
1211       static const CostTblEntry NEONDupTbl[] = {
1212           // VDUP handles these cases.
1213           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1214           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1215           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1216           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1217           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
1218           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
1219 
1220           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
1221           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
1222           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
1223           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
1224 
1225       std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
1226       if (const auto *Entry =
1227               CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second))
1228         return LT.first * Entry->Cost;
1229     }
1230     if (Kind == TTI::SK_Reverse) {
1231       static const CostTblEntry NEONShuffleTbl[] = {
1232           // Reverse shuffle cost one instruction if we are shuffling within a
1233           // double word (vrev) or two if we shuffle a quad word (vrev, vext).
1234           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1235           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1236           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1237           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1238           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
1239           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
1240 
1241           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
1242           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
1243           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
1244           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
1245 
1246       std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
1247       if (const auto *Entry =
1248               CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second))
1249         return LT.first * Entry->Cost;
1250     }
1251     if (Kind == TTI::SK_Select) {
1252       static const CostTblEntry NEONSelShuffleTbl[] = {
1253           // Select shuffle cost table for ARM. Cost is the number of
1254           // instructions
1255           // required to create the shuffled vector.
1256 
1257           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1258           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1259           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1260           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1261 
1262           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
1263           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
1264           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
1265 
1266           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
1267 
1268           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
1269 
1270       std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
1271       if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
1272                                               ISD::VECTOR_SHUFFLE, LT.second))
1273         return LT.first * Entry->Cost;
1274     }
1275   }
1276   if (ST->hasMVEIntegerOps()) {
1277     if (Kind == TTI::SK_Broadcast) {
1278       static const CostTblEntry MVEDupTbl[] = {
1279           // VDUP handles these cases.
1280           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
1281           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
1282           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1},
1283           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
1284           {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}};
1285 
1286       std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
1287       if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE,
1288                                               LT.second))
1289         return LT.first * Entry->Cost *
1290                ST->getMVEVectorCostFactor(TTI::TCK_RecipThroughput);
1291     }
1292 
1293     if (!Mask.empty()) {
1294       std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
1295       if (LT.second.isVector() &&
1296           Mask.size() <= LT.second.getVectorNumElements() &&
1297           (isVREVMask(Mask, LT.second, 16) || isVREVMask(Mask, LT.second, 32) ||
1298            isVREVMask(Mask, LT.second, 64)))
1299         return ST->getMVEVectorCostFactor(TTI::TCK_RecipThroughput) * LT.first;
1300     }
1301   }
1302 
1303   int BaseCost = ST->hasMVEIntegerOps() && Tp->isVectorTy()
1304                      ? ST->getMVEVectorCostFactor(TTI::TCK_RecipThroughput)
1305                      : 1;
1306   return BaseCost *
1307          BaseT::getShuffleCost(Kind, Tp, Mask, CostKind, Index, SubTp);
1308 }
1309 
1310 InstructionCost ARMTTIImpl::getArithmeticInstrCost(
1311     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
1312     TTI::OperandValueInfo Op1Info, TTI::OperandValueInfo Op2Info,
1313     ArrayRef<const Value *> Args,
1314     const Instruction *CxtI) {
1315   int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
1316   if (ST->isThumb() && CostKind == TTI::TCK_CodeSize && Ty->isIntegerTy(1)) {
1317     // Make operations on i1 relatively expensive as this often involves
1318     // combining predicates. AND and XOR should be easier to handle with IT
1319     // blocks.
1320     switch (ISDOpcode) {
1321     default:
1322       break;
1323     case ISD::AND:
1324     case ISD::XOR:
1325       return 2;
1326     case ISD::OR:
1327       return 3;
1328     }
1329   }
1330 
1331   std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
1332 
1333   if (ST->hasNEON()) {
1334     const unsigned FunctionCallDivCost = 20;
1335     const unsigned ReciprocalDivCost = 10;
1336     static const CostTblEntry CostTbl[] = {
1337       // Division.
1338       // These costs are somewhat random. Choose a cost of 20 to indicate that
1339       // vectorizing devision (added function call) is going to be very expensive.
1340       // Double registers types.
1341       { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1342       { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1343       { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
1344       { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
1345       { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1346       { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1347       { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
1348       { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
1349       { ISD::SDIV, MVT::v4i16,     ReciprocalDivCost},
1350       { ISD::UDIV, MVT::v4i16,     ReciprocalDivCost},
1351       { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
1352       { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
1353       { ISD::SDIV, MVT::v8i8,      ReciprocalDivCost},
1354       { ISD::UDIV, MVT::v8i8,      ReciprocalDivCost},
1355       { ISD::SREM, MVT::v8i8,  8 * FunctionCallDivCost},
1356       { ISD::UREM, MVT::v8i8,  8 * FunctionCallDivCost},
1357       // Quad register types.
1358       { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1359       { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1360       { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
1361       { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
1362       { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1363       { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1364       { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
1365       { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
1366       { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1367       { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1368       { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
1369       { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
1370       { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1371       { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1372       { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
1373       { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
1374       // Multiplication.
1375     };
1376 
1377     if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
1378       return LT.first * Entry->Cost;
1379 
1380     InstructionCost Cost = BaseT::getArithmeticInstrCost(
1381         Opcode, Ty, CostKind, Op1Info, Op2Info);
1382 
1383     // This is somewhat of a hack. The problem that we are facing is that SROA
1384     // creates a sequence of shift, and, or instructions to construct values.
1385     // These sequences are recognized by the ISel and have zero-cost. Not so for
1386     // the vectorized code. Because we have support for v2i64 but not i64 those
1387     // sequences look particularly beneficial to vectorize.
1388     // To work around this we increase the cost of v2i64 operations to make them
1389     // seem less beneficial.
1390     if (LT.second == MVT::v2i64 && Op2Info.isUniform() && Op2Info.isConstant())
1391       Cost += 4;
1392 
1393     return Cost;
1394   }
1395 
1396   // If this operation is a shift on arm/thumb2, it might well be folded into
1397   // the following instruction, hence having a cost of 0.
1398   auto LooksLikeAFreeShift = [&]() {
1399     if (ST->isThumb1Only() || Ty->isVectorTy())
1400       return false;
1401 
1402     if (!CxtI || !CxtI->hasOneUse() || !CxtI->isShift())
1403       return false;
1404     if (!Op2Info.isUniform() || !Op2Info.isConstant())
1405       return false;
1406 
1407     // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB
1408     switch (cast<Instruction>(CxtI->user_back())->getOpcode()) {
1409     case Instruction::Add:
1410     case Instruction::Sub:
1411     case Instruction::And:
1412     case Instruction::Xor:
1413     case Instruction::Or:
1414     case Instruction::ICmp:
1415       return true;
1416     default:
1417       return false;
1418     }
1419   };
1420   if (LooksLikeAFreeShift())
1421     return 0;
1422 
1423   // Default to cheap (throughput/size of 1 instruction) but adjust throughput
1424   // for "multiple beats" potentially needed by MVE instructions.
1425   int BaseCost = 1;
1426   if (ST->hasMVEIntegerOps() && Ty->isVectorTy())
1427     BaseCost = ST->getMVEVectorCostFactor(CostKind);
1428 
1429   // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost,
1430   // without treating floats as more expensive that scalars or increasing the
1431   // costs for custom operations. The results is also multiplied by the
1432   // MVEVectorCostFactor where appropriate.
1433   if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second))
1434     return LT.first * BaseCost;
1435 
1436   // Else this is expand, assume that we need to scalarize this op.
1437   if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
1438     unsigned Num = VTy->getNumElements();
1439     InstructionCost Cost =
1440         getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind);
1441     // Return the cost of multiple scalar invocation plus the cost of
1442     // inserting and extracting the values.
1443     SmallVector<Type *> Tys(Args.size(), Ty);
1444     return BaseT::getScalarizationOverhead(VTy, Args, Tys) + Num * Cost;
1445   }
1446 
1447   return BaseCost;
1448 }
1449 
1450 InstructionCost ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
1451                                             MaybeAlign Alignment,
1452                                             unsigned AddressSpace,
1453                                             TTI::TargetCostKind CostKind,
1454                                             TTI::OperandValueInfo OpInfo,
1455                                             const Instruction *I) {
1456   // TODO: Handle other cost kinds.
1457   if (CostKind != TTI::TCK_RecipThroughput)
1458     return 1;
1459 
1460   // Type legalization can't handle structs
1461   if (TLI->getValueType(DL, Src, true) == MVT::Other)
1462     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1463                                   CostKind);
1464 
1465   if (ST->hasNEON() && Src->isVectorTy() &&
1466       (Alignment && *Alignment != Align(16)) &&
1467       cast<VectorType>(Src)->getElementType()->isDoubleTy()) {
1468     // Unaligned loads/stores are extremely inefficient.
1469     // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
1470     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Src);
1471     return LT.first * 4;
1472   }
1473 
1474   // MVE can optimize a fpext(load(4xhalf)) using an extending integer load.
1475   // Same for stores.
1476   if (ST->hasMVEFloatOps() && isa<FixedVectorType>(Src) && I &&
1477       ((Opcode == Instruction::Load && I->hasOneUse() &&
1478         isa<FPExtInst>(*I->user_begin())) ||
1479        (Opcode == Instruction::Store && isa<FPTruncInst>(I->getOperand(0))))) {
1480     FixedVectorType *SrcVTy = cast<FixedVectorType>(Src);
1481     Type *DstTy =
1482         Opcode == Instruction::Load
1483             ? (*I->user_begin())->getType()
1484             : cast<Instruction>(I->getOperand(0))->getOperand(0)->getType();
1485     if (SrcVTy->getNumElements() == 4 && SrcVTy->getScalarType()->isHalfTy() &&
1486         DstTy->getScalarType()->isFloatTy())
1487       return ST->getMVEVectorCostFactor(CostKind);
1488   }
1489 
1490   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
1491                      ? ST->getMVEVectorCostFactor(CostKind)
1492                      : 1;
1493   return BaseCost * BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1494                                            CostKind, OpInfo, I);
1495 }
1496 
1497 InstructionCost
1498 ARMTTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
1499                                   unsigned AddressSpace,
1500                                   TTI::TargetCostKind CostKind) {
1501   if (ST->hasMVEIntegerOps()) {
1502     if (Opcode == Instruction::Load && isLegalMaskedLoad(Src, Alignment))
1503       return ST->getMVEVectorCostFactor(CostKind);
1504     if (Opcode == Instruction::Store && isLegalMaskedStore(Src, Alignment))
1505       return ST->getMVEVectorCostFactor(CostKind);
1506   }
1507   if (!isa<FixedVectorType>(Src))
1508     return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1509                                         CostKind);
1510   // Scalar cost, which is currently very high due to the efficiency of the
1511   // generated code.
1512   return cast<FixedVectorType>(Src)->getNumElements() * 8;
1513 }
1514 
1515 InstructionCost ARMTTIImpl::getInterleavedMemoryOpCost(
1516     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1517     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1518     bool UseMaskForCond, bool UseMaskForGaps) {
1519   assert(Factor >= 2 && "Invalid interleave factor");
1520   assert(isa<VectorType>(VecTy) && "Expect a vector type");
1521 
1522   // vldN/vstN doesn't support vector types of i64/f64 element.
1523   bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
1524 
1525   if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
1526       !UseMaskForCond && !UseMaskForGaps) {
1527     unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1528     auto *SubVecTy =
1529         FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
1530 
1531     // vldN/vstN only support legal vector types of size 64 or 128 in bits.
1532     // Accesses having vector types that are a multiple of 128 bits can be
1533     // matched to more than one vldN/vstN instruction.
1534     int BaseCost =
1535         ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor(CostKind) : 1;
1536     if (NumElts % Factor == 0 &&
1537         TLI->isLegalInterleavedAccessType(Factor, SubVecTy, Alignment, DL))
1538       return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL);
1539 
1540     // Some smaller than legal interleaved patterns are cheap as we can make
1541     // use of the vmovn or vrev patterns to interleave a standard load. This is
1542     // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is
1543     // promoted differently). The cost of 2 here is then a load and vrev or
1544     // vmovn.
1545     if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 &&
1546         VecTy->isIntOrIntVectorTy() &&
1547         DL.getTypeSizeInBits(SubVecTy).getFixedSize() <= 64)
1548       return 2 * BaseCost;
1549   }
1550 
1551   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1552                                            Alignment, AddressSpace, CostKind,
1553                                            UseMaskForCond, UseMaskForGaps);
1554 }
1555 
1556 InstructionCost ARMTTIImpl::getGatherScatterOpCost(
1557     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
1558     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) {
1559   using namespace PatternMatch;
1560   if (!ST->hasMVEIntegerOps() || !EnableMaskedGatherScatters)
1561     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
1562                                          Alignment, CostKind, I);
1563 
1564   assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!");
1565   auto *VTy = cast<FixedVectorType>(DataTy);
1566 
1567   // TODO: Splitting, once we do that.
1568 
1569   unsigned NumElems = VTy->getNumElements();
1570   unsigned EltSize = VTy->getScalarSizeInBits();
1571   std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(DataTy);
1572 
1573   // For now, it is assumed that for the MVE gather instructions the loads are
1574   // all effectively serialised. This means the cost is the scalar cost
1575   // multiplied by the number of elements being loaded. This is possibly very
1576   // conservative, but even so we still end up vectorising loops because the
1577   // cost per iteration for many loops is lower than for scalar loops.
1578   InstructionCost VectorCost =
1579       NumElems * LT.first * ST->getMVEVectorCostFactor(CostKind);
1580   // The scalarization cost should be a lot higher. We use the number of vector
1581   // elements plus the scalarization overhead.
1582   InstructionCost ScalarCost =
1583       NumElems * LT.first + BaseT::getScalarizationOverhead(VTy, true, false) +
1584       BaseT::getScalarizationOverhead(VTy, false, true);
1585 
1586   if (EltSize < 8 || Alignment < EltSize / 8)
1587     return ScalarCost;
1588 
1589   unsigned ExtSize = EltSize;
1590   // Check whether there's a single user that asks for an extended type
1591   if (I != nullptr) {
1592     // Dependent of the caller of this function, a gather instruction will
1593     // either have opcode Instruction::Load or be a call to the masked_gather
1594     // intrinsic
1595     if ((I->getOpcode() == Instruction::Load ||
1596          match(I, m_Intrinsic<Intrinsic::masked_gather>())) &&
1597         I->hasOneUse()) {
1598       const User *Us = *I->users().begin();
1599       if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) {
1600         // only allow valid type combinations
1601         unsigned TypeSize =
1602             cast<Instruction>(Us)->getType()->getScalarSizeInBits();
1603         if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) ||
1604              (TypeSize == 16 && EltSize == 8)) &&
1605             TypeSize * NumElems == 128) {
1606           ExtSize = TypeSize;
1607         }
1608       }
1609     }
1610     // Check whether the input data needs to be truncated
1611     TruncInst *T;
1612     if ((I->getOpcode() == Instruction::Store ||
1613          match(I, m_Intrinsic<Intrinsic::masked_scatter>())) &&
1614         (T = dyn_cast<TruncInst>(I->getOperand(0)))) {
1615       // Only allow valid type combinations
1616       unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits();
1617       if (((EltSize == 16 && TypeSize == 32) ||
1618            (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) &&
1619           TypeSize * NumElems == 128)
1620         ExtSize = TypeSize;
1621     }
1622   }
1623 
1624   if (ExtSize * NumElems != 128 || NumElems < 4)
1625     return ScalarCost;
1626 
1627   // Any (aligned) i32 gather will not need to be scalarised.
1628   if (ExtSize == 32)
1629     return VectorCost;
1630   // For smaller types, we need to ensure that the gep's inputs are correctly
1631   // extended from a small enough value. Other sizes (including i64) are
1632   // scalarized for now.
1633   if (ExtSize != 8 && ExtSize != 16)
1634     return ScalarCost;
1635 
1636   if (const auto *BC = dyn_cast<BitCastInst>(Ptr))
1637     Ptr = BC->getOperand(0);
1638   if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1639     if (GEP->getNumOperands() != 2)
1640       return ScalarCost;
1641     unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType());
1642     // Scale needs to be correct (which is only relevant for i16s).
1643     if (Scale != 1 && Scale * 8 != ExtSize)
1644       return ScalarCost;
1645     // And we need to zext (not sext) the indexes from a small enough type.
1646     if (const auto *ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) {
1647       if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize)
1648         return VectorCost;
1649     }
1650     return ScalarCost;
1651   }
1652   return ScalarCost;
1653 }
1654 
1655 InstructionCost
1656 ARMTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy,
1657                                        std::optional<FastMathFlags> FMF,
1658                                        TTI::TargetCostKind CostKind) {
1659   if (TTI::requiresOrderedReduction(FMF))
1660     return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
1661 
1662   EVT ValVT = TLI->getValueType(DL, ValTy);
1663   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1664   if (!ST->hasMVEIntegerOps() || !ValVT.isSimple() || ISD != ISD::ADD)
1665     return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
1666 
1667   std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1668 
1669   static const CostTblEntry CostTblAdd[]{
1670       {ISD::ADD, MVT::v16i8, 1},
1671       {ISD::ADD, MVT::v8i16, 1},
1672       {ISD::ADD, MVT::v4i32, 1},
1673   };
1674   if (const auto *Entry = CostTableLookup(CostTblAdd, ISD, LT.second))
1675     return Entry->Cost * ST->getMVEVectorCostFactor(CostKind) * LT.first;
1676 
1677   return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
1678 }
1679 
1680 InstructionCost ARMTTIImpl::getExtendedReductionCost(
1681     unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *ValTy,
1682     std::optional<FastMathFlags> FMF, TTI::TargetCostKind CostKind) {
1683   EVT ValVT = TLI->getValueType(DL, ValTy);
1684   EVT ResVT = TLI->getValueType(DL, ResTy);
1685 
1686   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1687 
1688   switch (ISD) {
1689   case ISD::ADD:
1690     if (ST->hasMVEIntegerOps() && ValVT.isSimple() && ResVT.isSimple()) {
1691       std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1692 
1693       // The legal cases are:
1694       //   VADDV u/s 8/16/32
1695       //   VADDLV u/s 32
1696       // Codegen currently cannot always handle larger than legal vectors very
1697       // well, especially for predicated reductions where the mask needs to be
1698       // split, so restrict to 128bit or smaller input types.
1699       unsigned RevVTSize = ResVT.getSizeInBits();
1700       if (ValVT.getSizeInBits() <= 128 &&
1701           ((LT.second == MVT::v16i8 && RevVTSize <= 32) ||
1702            (LT.second == MVT::v8i16 && RevVTSize <= 32) ||
1703            (LT.second == MVT::v4i32 && RevVTSize <= 64)))
1704         return ST->getMVEVectorCostFactor(CostKind) * LT.first;
1705     }
1706     break;
1707   default:
1708     break;
1709   }
1710   return BaseT::getExtendedReductionCost(Opcode, IsUnsigned, ResTy, ValTy, FMF,
1711                                          CostKind);
1712 }
1713 
1714 InstructionCost
1715 ARMTTIImpl::getMulAccReductionCost(bool IsUnsigned, Type *ResTy,
1716                                    VectorType *ValTy,
1717                                    TTI::TargetCostKind CostKind) {
1718   EVT ValVT = TLI->getValueType(DL, ValTy);
1719   EVT ResVT = TLI->getValueType(DL, ResTy);
1720 
1721   if (ST->hasMVEIntegerOps() && ValVT.isSimple() && ResVT.isSimple()) {
1722     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1723 
1724     // The legal cases are:
1725     //   VMLAV u/s 8/16/32
1726     //   VMLALV u/s 16/32
1727     // Codegen currently cannot always handle larger than legal vectors very
1728     // well, especially for predicated reductions where the mask needs to be
1729     // split, so restrict to 128bit or smaller input types.
1730     unsigned RevVTSize = ResVT.getSizeInBits();
1731     if (ValVT.getSizeInBits() <= 128 &&
1732         ((LT.second == MVT::v16i8 && RevVTSize <= 32) ||
1733          (LT.second == MVT::v8i16 && RevVTSize <= 64) ||
1734          (LT.second == MVT::v4i32 && RevVTSize <= 64)))
1735       return ST->getMVEVectorCostFactor(CostKind) * LT.first;
1736   }
1737 
1738   return BaseT::getMulAccReductionCost(IsUnsigned, ResTy, ValTy, CostKind);
1739 }
1740 
1741 InstructionCost
1742 ARMTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1743                                   TTI::TargetCostKind CostKind) {
1744   switch (ICA.getID()) {
1745   case Intrinsic::get_active_lane_mask:
1746     // Currently we make a somewhat optimistic assumption that
1747     // active_lane_mask's are always free. In reality it may be freely folded
1748     // into a tail predicated loop, expanded into a VCPT or expanded into a lot
1749     // of add/icmp code. We may need to improve this in the future, but being
1750     // able to detect if it is free or not involves looking at a lot of other
1751     // code. We currently assume that the vectorizer inserted these, and knew
1752     // what it was doing in adding one.
1753     if (ST->hasMVEIntegerOps())
1754       return 0;
1755     break;
1756   case Intrinsic::sadd_sat:
1757   case Intrinsic::ssub_sat:
1758   case Intrinsic::uadd_sat:
1759   case Intrinsic::usub_sat: {
1760     if (!ST->hasMVEIntegerOps())
1761       break;
1762     Type *VT = ICA.getReturnType();
1763 
1764     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VT);
1765     if (LT.second == MVT::v4i32 || LT.second == MVT::v8i16 ||
1766         LT.second == MVT::v16i8) {
1767       // This is a base cost of 1 for the vqadd, plus 3 extract shifts if we
1768       // need to extend the type, as it uses shr(qadd(shl, shl)).
1769       unsigned Instrs =
1770           LT.second.getScalarSizeInBits() == VT->getScalarSizeInBits() ? 1 : 4;
1771       return LT.first * ST->getMVEVectorCostFactor(CostKind) * Instrs;
1772     }
1773     break;
1774   }
1775   case Intrinsic::abs:
1776   case Intrinsic::smin:
1777   case Intrinsic::smax:
1778   case Intrinsic::umin:
1779   case Intrinsic::umax: {
1780     if (!ST->hasMVEIntegerOps())
1781       break;
1782     Type *VT = ICA.getReturnType();
1783 
1784     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VT);
1785     if (LT.second == MVT::v4i32 || LT.second == MVT::v8i16 ||
1786         LT.second == MVT::v16i8)
1787       return LT.first * ST->getMVEVectorCostFactor(CostKind);
1788     break;
1789   }
1790   case Intrinsic::minnum:
1791   case Intrinsic::maxnum: {
1792     if (!ST->hasMVEFloatOps())
1793       break;
1794     Type *VT = ICA.getReturnType();
1795     std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VT);
1796     if (LT.second == MVT::v4f32 || LT.second == MVT::v8f16)
1797       return LT.first * ST->getMVEVectorCostFactor(CostKind);
1798     break;
1799   }
1800   case Intrinsic::fptosi_sat:
1801   case Intrinsic::fptoui_sat: {
1802     if (ICA.getArgTypes().empty())
1803       break;
1804     bool IsSigned = ICA.getID() == Intrinsic::fptosi_sat;
1805     auto LT = getTypeLegalizationCost(ICA.getArgTypes()[0]);
1806     EVT MTy = TLI->getValueType(DL, ICA.getReturnType());
1807     // Check for the legal types, with the corect subtarget features.
1808     if ((ST->hasVFP2Base() && LT.second == MVT::f32 && MTy == MVT::i32) ||
1809         (ST->hasFP64() && LT.second == MVT::f64 && MTy == MVT::i32) ||
1810         (ST->hasFullFP16() && LT.second == MVT::f16 && MTy == MVT::i32))
1811       return LT.first;
1812 
1813     // Equally for MVE vector types
1814     if (ST->hasMVEFloatOps() &&
1815         (LT.second == MVT::v4f32 || LT.second == MVT::v8f16) &&
1816         LT.second.getScalarSizeInBits() == MTy.getScalarSizeInBits())
1817       return LT.first * ST->getMVEVectorCostFactor(CostKind);
1818 
1819     // Otherwise we use a legal convert followed by a min+max
1820     if (((ST->hasVFP2Base() && LT.second == MVT::f32) ||
1821          (ST->hasFP64() && LT.second == MVT::f64) ||
1822          (ST->hasFullFP16() && LT.second == MVT::f16) ||
1823          (ST->hasMVEFloatOps() &&
1824           (LT.second == MVT::v4f32 || LT.second == MVT::v8f16))) &&
1825         LT.second.getScalarSizeInBits() >= MTy.getScalarSizeInBits()) {
1826       Type *LegalTy = Type::getIntNTy(ICA.getReturnType()->getContext(),
1827                                       LT.second.getScalarSizeInBits());
1828       InstructionCost Cost =
1829           LT.second.isVector() ? ST->getMVEVectorCostFactor(CostKind) : 1;
1830       IntrinsicCostAttributes Attrs1(IsSigned ? Intrinsic::smin
1831                                               : Intrinsic::umin,
1832                                      LegalTy, {LegalTy, LegalTy});
1833       Cost += getIntrinsicInstrCost(Attrs1, CostKind);
1834       IntrinsicCostAttributes Attrs2(IsSigned ? Intrinsic::smax
1835                                               : Intrinsic::umax,
1836                                      LegalTy, {LegalTy, LegalTy});
1837       Cost += getIntrinsicInstrCost(Attrs2, CostKind);
1838       return LT.first * Cost;
1839     }
1840     break;
1841   }
1842   }
1843 
1844   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1845 }
1846 
1847 bool ARMTTIImpl::isLoweredToCall(const Function *F) {
1848   if (!F->isIntrinsic())
1849     return BaseT::isLoweredToCall(F);
1850 
1851   // Assume all Arm-specific intrinsics map to an instruction.
1852   if (F->getName().startswith("llvm.arm"))
1853     return false;
1854 
1855   switch (F->getIntrinsicID()) {
1856   default: break;
1857   case Intrinsic::powi:
1858   case Intrinsic::sin:
1859   case Intrinsic::cos:
1860   case Intrinsic::pow:
1861   case Intrinsic::log:
1862   case Intrinsic::log10:
1863   case Intrinsic::log2:
1864   case Intrinsic::exp:
1865   case Intrinsic::exp2:
1866     return true;
1867   case Intrinsic::sqrt:
1868   case Intrinsic::fabs:
1869   case Intrinsic::copysign:
1870   case Intrinsic::floor:
1871   case Intrinsic::ceil:
1872   case Intrinsic::trunc:
1873   case Intrinsic::rint:
1874   case Intrinsic::nearbyint:
1875   case Intrinsic::round:
1876   case Intrinsic::canonicalize:
1877   case Intrinsic::lround:
1878   case Intrinsic::llround:
1879   case Intrinsic::lrint:
1880   case Intrinsic::llrint:
1881     if (F->getReturnType()->isDoubleTy() && !ST->hasFP64())
1882       return true;
1883     if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16())
1884       return true;
1885     // Some operations can be handled by vector instructions and assume
1886     // unsupported vectors will be expanded into supported scalar ones.
1887     // TODO Handle scalar operations properly.
1888     return !ST->hasFPARMv8Base() && !ST->hasVFP2Base();
1889   case Intrinsic::masked_store:
1890   case Intrinsic::masked_load:
1891   case Intrinsic::masked_gather:
1892   case Intrinsic::masked_scatter:
1893     return !ST->hasMVEIntegerOps();
1894   case Intrinsic::sadd_with_overflow:
1895   case Intrinsic::uadd_with_overflow:
1896   case Intrinsic::ssub_with_overflow:
1897   case Intrinsic::usub_with_overflow:
1898   case Intrinsic::sadd_sat:
1899   case Intrinsic::uadd_sat:
1900   case Intrinsic::ssub_sat:
1901   case Intrinsic::usub_sat:
1902     return false;
1903   }
1904 
1905   return BaseT::isLoweredToCall(F);
1906 }
1907 
1908 bool ARMTTIImpl::maybeLoweredToCall(Instruction &I) {
1909   unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode());
1910   EVT VT = TLI->getValueType(DL, I.getType(), true);
1911   if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall)
1912     return true;
1913 
1914   // Check if an intrinsic will be lowered to a call and assume that any
1915   // other CallInst will generate a bl.
1916   if (auto *Call = dyn_cast<CallInst>(&I)) {
1917     if (auto *II = dyn_cast<IntrinsicInst>(Call)) {
1918       switch(II->getIntrinsicID()) {
1919         case Intrinsic::memcpy:
1920         case Intrinsic::memset:
1921         case Intrinsic::memmove:
1922           return getNumMemOps(II) == -1;
1923         default:
1924           if (const Function *F = Call->getCalledFunction())
1925             return isLoweredToCall(F);
1926       }
1927     }
1928     return true;
1929   }
1930 
1931   // FPv5 provides conversions between integer, double-precision,
1932   // single-precision, and half-precision formats.
1933   switch (I.getOpcode()) {
1934   default:
1935     break;
1936   case Instruction::FPToSI:
1937   case Instruction::FPToUI:
1938   case Instruction::SIToFP:
1939   case Instruction::UIToFP:
1940   case Instruction::FPTrunc:
1941   case Instruction::FPExt:
1942     return !ST->hasFPARMv8Base();
1943   }
1944 
1945   // FIXME: Unfortunately the approach of checking the Operation Action does
1946   // not catch all cases of Legalization that use library calls. Our
1947   // Legalization step categorizes some transformations into library calls as
1948   // Custom, Expand or even Legal when doing type legalization. So for now
1949   // we have to special case for instance the SDIV of 64bit integers and the
1950   // use of floating point emulation.
1951   if (VT.isInteger() && VT.getSizeInBits() >= 64) {
1952     switch (ISD) {
1953     default:
1954       break;
1955     case ISD::SDIV:
1956     case ISD::UDIV:
1957     case ISD::SREM:
1958     case ISD::UREM:
1959     case ISD::SDIVREM:
1960     case ISD::UDIVREM:
1961       return true;
1962     }
1963   }
1964 
1965   // Assume all other non-float operations are supported.
1966   if (!VT.isFloatingPoint())
1967     return false;
1968 
1969   // We'll need a library call to handle most floats when using soft.
1970   if (TLI->useSoftFloat()) {
1971     switch (I.getOpcode()) {
1972     default:
1973       return true;
1974     case Instruction::Alloca:
1975     case Instruction::Load:
1976     case Instruction::Store:
1977     case Instruction::Select:
1978     case Instruction::PHI:
1979       return false;
1980     }
1981   }
1982 
1983   // We'll need a libcall to perform double precision operations on a single
1984   // precision only FPU.
1985   if (I.getType()->isDoubleTy() && !ST->hasFP64())
1986     return true;
1987 
1988   // Likewise for half precision arithmetic.
1989   if (I.getType()->isHalfTy() && !ST->hasFullFP16())
1990     return true;
1991 
1992   return false;
1993 }
1994 
1995 bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1996                                           AssumptionCache &AC,
1997                                           TargetLibraryInfo *LibInfo,
1998                                           HardwareLoopInfo &HWLoopInfo) {
1999   // Low-overhead branches are only supported in the 'low-overhead branch'
2000   // extension of v8.1-m.
2001   if (!ST->hasLOB() || DisableLowOverheadLoops) {
2002     LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n");
2003     return false;
2004   }
2005 
2006   if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
2007     LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n");
2008     return false;
2009   }
2010 
2011   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2012   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2013     LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n");
2014     return false;
2015   }
2016 
2017   const SCEV *TripCountSCEV =
2018     SE.getAddExpr(BackedgeTakenCount,
2019                   SE.getOne(BackedgeTakenCount->getType()));
2020 
2021   // We need to store the trip count in LR, a 32-bit register.
2022   if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) {
2023     LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n");
2024     return false;
2025   }
2026 
2027   // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little
2028   // point in generating a hardware loop if that's going to happen.
2029 
2030   auto IsHardwareLoopIntrinsic = [](Instruction &I) {
2031     if (auto *Call = dyn_cast<IntrinsicInst>(&I)) {
2032       switch (Call->getIntrinsicID()) {
2033       default:
2034         break;
2035       case Intrinsic::start_loop_iterations:
2036       case Intrinsic::test_start_loop_iterations:
2037       case Intrinsic::loop_decrement:
2038       case Intrinsic::loop_decrement_reg:
2039         return true;
2040       }
2041     }
2042     return false;
2043   };
2044 
2045   // Scan the instructions to see if there's any that we know will turn into a
2046   // call or if this loop is already a low-overhead loop or will become a tail
2047   // predicated loop.
2048   bool IsTailPredLoop = false;
2049   auto ScanLoop = [&](Loop *L) {
2050     for (auto *BB : L->getBlocks()) {
2051       for (auto &I : *BB) {
2052         if (maybeLoweredToCall(I) || IsHardwareLoopIntrinsic(I) ||
2053             isa<InlineAsm>(I)) {
2054           LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n");
2055           return false;
2056         }
2057         if (auto *II = dyn_cast<IntrinsicInst>(&I))
2058           IsTailPredLoop |=
2059               II->getIntrinsicID() == Intrinsic::get_active_lane_mask ||
2060               II->getIntrinsicID() == Intrinsic::arm_mve_vctp8 ||
2061               II->getIntrinsicID() == Intrinsic::arm_mve_vctp16 ||
2062               II->getIntrinsicID() == Intrinsic::arm_mve_vctp32 ||
2063               II->getIntrinsicID() == Intrinsic::arm_mve_vctp64;
2064       }
2065     }
2066     return true;
2067   };
2068 
2069   // Visit inner loops.
2070   for (auto *Inner : *L)
2071     if (!ScanLoop(Inner))
2072       return false;
2073 
2074   if (!ScanLoop(L))
2075     return false;
2076 
2077   // TODO: Check whether the trip count calculation is expensive. If L is the
2078   // inner loop but we know it has a low trip count, calculating that trip
2079   // count (in the parent loop) may be detrimental.
2080 
2081   LLVMContext &C = L->getHeader()->getContext();
2082   HWLoopInfo.CounterInReg = true;
2083   HWLoopInfo.IsNestingLegal = false;
2084   HWLoopInfo.PerformEntryTest = AllowWLSLoops && !IsTailPredLoop;
2085   HWLoopInfo.CountType = Type::getInt32Ty(C);
2086   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
2087   return true;
2088 }
2089 
2090 static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) {
2091   // We don't allow icmp's, and because we only look at single block loops,
2092   // we simply count the icmps, i.e. there should only be 1 for the backedge.
2093   if (isa<ICmpInst>(&I) && ++ICmpCount > 1)
2094     return false;
2095   // FIXME: This is a workaround for poor cost modelling. Min/Max intrinsics are
2096   // not currently canonical, but soon will be. Code without them uses icmp, and
2097   // so is not tail predicated as per the condition above. In order to get the
2098   // same performance we treat min and max the same as an icmp for tailpred
2099   // purposes for the moment (we often rely on non-tailpred and higher VF's to
2100   // pick more optimial instructions like VQDMULH. They need to be recognized
2101   // directly by the vectorizer).
2102   if (auto *II = dyn_cast<IntrinsicInst>(&I))
2103     if ((II->getIntrinsicID() == Intrinsic::smin ||
2104          II->getIntrinsicID() == Intrinsic::smax ||
2105          II->getIntrinsicID() == Intrinsic::umin ||
2106          II->getIntrinsicID() == Intrinsic::umax) &&
2107         ++ICmpCount > 1)
2108       return false;
2109 
2110   if (isa<FCmpInst>(&I))
2111     return false;
2112 
2113   // We could allow extending/narrowing FP loads/stores, but codegen is
2114   // too inefficient so reject this for now.
2115   if (isa<FPExtInst>(&I) || isa<FPTruncInst>(&I))
2116     return false;
2117 
2118   // Extends have to be extending-loads
2119   if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) )
2120     if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0)))
2121       return false;
2122 
2123   // Truncs have to be narrowing-stores
2124   if (isa<TruncInst>(&I) )
2125     if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin()))
2126       return false;
2127 
2128   return true;
2129 }
2130 
2131 // To set up a tail-predicated loop, we need to know the total number of
2132 // elements processed by that loop. Thus, we need to determine the element
2133 // size and:
2134 // 1) it should be uniform for all operations in the vector loop, so we
2135 //    e.g. don't want any widening/narrowing operations.
2136 // 2) it should be smaller than i64s because we don't have vector operations
2137 //    that work on i64s.
2138 // 3) we don't want elements to be reversed or shuffled, to make sure the
2139 //    tail-predication masks/predicates the right lanes.
2140 //
2141 static bool canTailPredicateLoop(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
2142                                  const DataLayout &DL,
2143                                  const LoopAccessInfo *LAI) {
2144   LLVM_DEBUG(dbgs() << "Tail-predication: checking allowed instructions\n");
2145 
2146   // If there are live-out values, it is probably a reduction. We can predicate
2147   // most reduction operations freely under MVE using a combination of
2148   // prefer-predicated-reduction-select and inloop reductions. We limit this to
2149   // floating point and integer reductions, but don't check for operators
2150   // specifically here. If the value ends up not being a reduction (and so the
2151   // vectorizer cannot tailfold the loop), we should fall back to standard
2152   // vectorization automatically.
2153   SmallVector< Instruction *, 8 > LiveOuts;
2154   LiveOuts = llvm::findDefsUsedOutsideOfLoop(L);
2155   bool ReductionsDisabled =
2156       EnableTailPredication == TailPredication::EnabledNoReductions ||
2157       EnableTailPredication == TailPredication::ForceEnabledNoReductions;
2158 
2159   for (auto *I : LiveOuts) {
2160     if (!I->getType()->isIntegerTy() && !I->getType()->isFloatTy() &&
2161         !I->getType()->isHalfTy()) {
2162       LLVM_DEBUG(dbgs() << "Don't tail-predicate loop with non-integer/float "
2163                            "live-out value\n");
2164       return false;
2165     }
2166     if (ReductionsDisabled) {
2167       LLVM_DEBUG(dbgs() << "Reductions not enabled\n");
2168       return false;
2169     }
2170   }
2171 
2172   // Next, check that all instructions can be tail-predicated.
2173   PredicatedScalarEvolution PSE = LAI->getPSE();
2174   SmallVector<Instruction *, 16> LoadStores;
2175   int ICmpCount = 0;
2176 
2177   for (BasicBlock *BB : L->blocks()) {
2178     for (Instruction &I : BB->instructionsWithoutDebug()) {
2179       if (isa<PHINode>(&I))
2180         continue;
2181       if (!canTailPredicateInstruction(I, ICmpCount)) {
2182         LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump());
2183         return false;
2184       }
2185 
2186       Type *T  = I.getType();
2187       if (T->getScalarSizeInBits() > 32) {
2188         LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump());
2189         return false;
2190       }
2191       if (isa<StoreInst>(I) || isa<LoadInst>(I)) {
2192         Value *Ptr = getLoadStorePointerOperand(&I);
2193         Type *AccessTy = getLoadStoreType(&I);
2194         int64_t NextStride = getPtrStride(PSE, AccessTy, Ptr, L).value_or(0);
2195         if (NextStride == 1) {
2196           // TODO: for now only allow consecutive strides of 1. We could support
2197           // other strides as long as it is uniform, but let's keep it simple
2198           // for now.
2199           continue;
2200         } else if (NextStride == -1 ||
2201                    (NextStride == 2 && MVEMaxSupportedInterleaveFactor >= 2) ||
2202                    (NextStride == 4 && MVEMaxSupportedInterleaveFactor >= 4)) {
2203           LLVM_DEBUG(dbgs()
2204                      << "Consecutive strides of 2 found, vld2/vstr2 can't "
2205                         "be tail-predicated\n.");
2206           return false;
2207           // TODO: don't tail predicate if there is a reversed load?
2208         } else if (EnableMaskedGatherScatters) {
2209           // Gather/scatters do allow loading from arbitrary strides, at
2210           // least if they are loop invariant.
2211           // TODO: Loop variant strides should in theory work, too, but
2212           // this requires further testing.
2213           const SCEV *PtrScev = PSE.getSE()->getSCEV(Ptr);
2214           if (auto AR = dyn_cast<SCEVAddRecExpr>(PtrScev)) {
2215             const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
2216             if (PSE.getSE()->isLoopInvariant(Step, L))
2217               continue;
2218           }
2219         }
2220         LLVM_DEBUG(dbgs() << "Bad stride found, can't "
2221                              "tail-predicate\n.");
2222         return false;
2223       }
2224     }
2225   }
2226 
2227   LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n");
2228   return true;
2229 }
2230 
2231 bool ARMTTIImpl::preferPredicateOverEpilogue(
2232     Loop *L, LoopInfo *LI, ScalarEvolution &SE, AssumptionCache &AC,
2233     TargetLibraryInfo *TLI, DominatorTree *DT, LoopVectorizationLegality *LVL,
2234     InterleavedAccessInfo *IAI) {
2235   if (!EnableTailPredication) {
2236     LLVM_DEBUG(dbgs() << "Tail-predication not enabled.\n");
2237     return false;
2238   }
2239 
2240   // Creating a predicated vector loop is the first step for generating a
2241   // tail-predicated hardware loop, for which we need the MVE masked
2242   // load/stores instructions:
2243   if (!ST->hasMVEIntegerOps())
2244     return false;
2245 
2246   // For now, restrict this to single block loops.
2247   if (L->getNumBlocks() > 1) {
2248     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: not a single block "
2249                          "loop.\n");
2250     return false;
2251   }
2252 
2253   assert(L->isInnermost() && "preferPredicateOverEpilogue: inner-loop expected");
2254 
2255   HardwareLoopInfo HWLoopInfo(L);
2256   if (!HWLoopInfo.canAnalyze(*LI)) {
2257     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
2258                          "analyzable.\n");
2259     return false;
2260   }
2261 
2262   // This checks if we have the low-overhead branch architecture
2263   // extension, and if we will create a hardware-loop:
2264   if (!isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) {
2265     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
2266                          "profitable.\n");
2267     return false;
2268   }
2269 
2270   if (!HWLoopInfo.isHardwareLoopCandidate(SE, *LI, *DT)) {
2271     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
2272                          "a candidate.\n");
2273     return false;
2274   }
2275 
2276   return canTailPredicateLoop(L, LI, SE, DL, LVL->getLAI());
2277 }
2278 
2279 PredicationStyle ARMTTIImpl::emitGetActiveLaneMask() const {
2280   if (!ST->hasMVEIntegerOps() || !EnableTailPredication)
2281     return PredicationStyle::None;
2282 
2283   // Intrinsic @llvm.get.active.lane.mask is supported.
2284   // It is used in the MVETailPredication pass, which requires the number of
2285   // elements processed by this vector loop to setup the tail-predicated
2286   // loop.
2287   return PredicationStyle::Data;
2288 }
2289 void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
2290                                          TTI::UnrollingPreferences &UP,
2291                                          OptimizationRemarkEmitter *ORE) {
2292   // Enable Upper bound unrolling universally, not dependant upon the conditions
2293   // below.
2294   UP.UpperBound = true;
2295 
2296   // Only currently enable these preferences for M-Class cores.
2297   if (!ST->isMClass())
2298     return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP, ORE);
2299 
2300   // Disable loop unrolling for Oz and Os.
2301   UP.OptSizeThreshold = 0;
2302   UP.PartialOptSizeThreshold = 0;
2303   if (L->getHeader()->getParent()->hasOptSize())
2304     return;
2305 
2306   SmallVector<BasicBlock*, 4> ExitingBlocks;
2307   L->getExitingBlocks(ExitingBlocks);
2308   LLVM_DEBUG(dbgs() << "Loop has:\n"
2309                     << "Blocks: " << L->getNumBlocks() << "\n"
2310                     << "Exit blocks: " << ExitingBlocks.size() << "\n");
2311 
2312   // Only allow another exit other than the latch. This acts as an early exit
2313   // as it mirrors the profitability calculation of the runtime unroller.
2314   if (ExitingBlocks.size() > 2)
2315     return;
2316 
2317   // Limit the CFG of the loop body for targets with a branch predictor.
2318   // Allowing 4 blocks permits if-then-else diamonds in the body.
2319   if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
2320     return;
2321 
2322   // Don't unroll vectorized loops, including the remainder loop
2323   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
2324     return;
2325 
2326   // Scan the loop: don't unroll loops with calls as this could prevent
2327   // inlining.
2328   InstructionCost Cost = 0;
2329   for (auto *BB : L->getBlocks()) {
2330     for (auto &I : *BB) {
2331       // Don't unroll vectorised loop. MVE does not benefit from it as much as
2332       // scalar code.
2333       if (I.getType()->isVectorTy())
2334         return;
2335 
2336       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
2337         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
2338           if (!isLoweredToCall(F))
2339             continue;
2340         }
2341         return;
2342       }
2343 
2344       SmallVector<const Value*, 4> Operands(I.operand_values());
2345       Cost += getInstructionCost(&I, Operands,
2346                                  TargetTransformInfo::TCK_SizeAndLatency);
2347     }
2348   }
2349 
2350   // On v6m cores, there are very few registers available. We can easily end up
2351   // spilling and reloading more registers in an unrolled loop. Look at the
2352   // number of LCSSA phis as a rough measure of how many registers will need to
2353   // be live out of the loop, reducing the default unroll count if more than 1
2354   // value is needed.  In the long run, all of this should be being learnt by a
2355   // machine.
2356   unsigned UnrollCount = 4;
2357   if (ST->isThumb1Only()) {
2358     unsigned ExitingValues = 0;
2359     SmallVector<BasicBlock *, 4> ExitBlocks;
2360     L->getExitBlocks(ExitBlocks);
2361     for (auto *Exit : ExitBlocks) {
2362       // Count the number of LCSSA phis. Exclude values coming from GEP's as
2363       // only the last is expected to be needed for address operands.
2364       unsigned LiveOuts = count_if(Exit->phis(), [](auto &PH) {
2365         return PH.getNumOperands() != 1 ||
2366                !isa<GetElementPtrInst>(PH.getOperand(0));
2367       });
2368       ExitingValues = ExitingValues < LiveOuts ? LiveOuts : ExitingValues;
2369     }
2370     if (ExitingValues)
2371       UnrollCount /= ExitingValues;
2372     if (UnrollCount <= 1)
2373       return;
2374   }
2375 
2376   LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
2377   LLVM_DEBUG(dbgs() << "Default Runtime Unroll Count: " << UnrollCount << "\n");
2378 
2379   UP.Partial = true;
2380   UP.Runtime = true;
2381   UP.UnrollRemainder = true;
2382   UP.DefaultUnrollRuntimeCount = UnrollCount;
2383   UP.UnrollAndJam = true;
2384   UP.UnrollAndJamInnerLoopThreshold = 60;
2385 
2386   // Force unrolling small loops can be very useful because of the branch
2387   // taken cost of the backedge.
2388   if (Cost < 12)
2389     UP.Force = true;
2390 }
2391 
2392 void ARMTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
2393                                        TTI::PeelingPreferences &PP) {
2394   BaseT::getPeelingPreferences(L, SE, PP);
2395 }
2396 
2397 bool ARMTTIImpl::preferInLoopReduction(unsigned Opcode, Type *Ty,
2398                                        TTI::ReductionFlags Flags) const {
2399   if (!ST->hasMVEIntegerOps())
2400     return false;
2401 
2402   unsigned ScalarBits = Ty->getScalarSizeInBits();
2403   switch (Opcode) {
2404   case Instruction::Add:
2405     return ScalarBits <= 64;
2406   default:
2407     return false;
2408   }
2409 }
2410 
2411 bool ARMTTIImpl::preferPredicatedReductionSelect(
2412     unsigned Opcode, Type *Ty, TTI::ReductionFlags Flags) const {
2413   if (!ST->hasMVEIntegerOps())
2414     return false;
2415   return true;
2416 }
2417 
2418 InstructionCost ARMTTIImpl::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
2419                                                  int64_t BaseOffset,
2420                                                  bool HasBaseReg, int64_t Scale,
2421                                                  unsigned AddrSpace) const {
2422   TargetLoweringBase::AddrMode AM;
2423   AM.BaseGV = BaseGV;
2424   AM.BaseOffs = BaseOffset;
2425   AM.HasBaseReg = HasBaseReg;
2426   AM.Scale = Scale;
2427   if (getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace)) {
2428     if (ST->hasFPAO())
2429       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
2430     return 0;
2431   }
2432   return -1;
2433 }
2434