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