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