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