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   // TODO: Handle more cost kinds.
1043   if (CostKind != TTI::TCK_RecipThroughput)
1044     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
1045                                          Op2Info, Opd1PropInfo,
1046                                          Opd2PropInfo, Args, CxtI);
1047 
1048   int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
1049   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
1050 
1051   if (ST->hasNEON()) {
1052     const unsigned FunctionCallDivCost = 20;
1053     const unsigned ReciprocalDivCost = 10;
1054     static const CostTblEntry CostTbl[] = {
1055       // Division.
1056       // These costs are somewhat random. Choose a cost of 20 to indicate that
1057       // vectorizing devision (added function call) is going to be very expensive.
1058       // Double registers types.
1059       { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1060       { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1061       { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
1062       { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
1063       { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1064       { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1065       { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
1066       { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
1067       { ISD::SDIV, MVT::v4i16,     ReciprocalDivCost},
1068       { ISD::UDIV, MVT::v4i16,     ReciprocalDivCost},
1069       { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
1070       { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
1071       { ISD::SDIV, MVT::v8i8,      ReciprocalDivCost},
1072       { ISD::UDIV, MVT::v8i8,      ReciprocalDivCost},
1073       { ISD::SREM, MVT::v8i8,  8 * FunctionCallDivCost},
1074       { ISD::UREM, MVT::v8i8,  8 * FunctionCallDivCost},
1075       // Quad register types.
1076       { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1077       { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1078       { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
1079       { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
1080       { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1081       { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1082       { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
1083       { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
1084       { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1085       { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1086       { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
1087       { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
1088       { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1089       { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1090       { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
1091       { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
1092       // Multiplication.
1093     };
1094 
1095     if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
1096       return LT.first * Entry->Cost;
1097 
1098     int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
1099                                              Op2Info,
1100                                              Opd1PropInfo, Opd2PropInfo);
1101 
1102     // This is somewhat of a hack. The problem that we are facing is that SROA
1103     // creates a sequence of shift, and, or instructions to construct values.
1104     // These sequences are recognized by the ISel and have zero-cost. Not so for
1105     // the vectorized code. Because we have support for v2i64 but not i64 those
1106     // sequences look particularly beneficial to vectorize.
1107     // To work around this we increase the cost of v2i64 operations to make them
1108     // seem less beneficial.
1109     if (LT.second == MVT::v2i64 &&
1110         Op2Info == TargetTransformInfo::OK_UniformConstantValue)
1111       Cost += 4;
1112 
1113     return Cost;
1114   }
1115 
1116   // If this operation is a shift on arm/thumb2, it might well be folded into
1117   // the following instruction, hence having a cost of 0.
1118   auto LooksLikeAFreeShift = [&]() {
1119     if (ST->isThumb1Only() || Ty->isVectorTy())
1120       return false;
1121 
1122     if (!CxtI || !CxtI->hasOneUse() || !CxtI->isShift())
1123       return false;
1124     if (Op2Info != TargetTransformInfo::OK_UniformConstantValue)
1125       return false;
1126 
1127     // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB
1128     switch (cast<Instruction>(CxtI->user_back())->getOpcode()) {
1129     case Instruction::Add:
1130     case Instruction::Sub:
1131     case Instruction::And:
1132     case Instruction::Xor:
1133     case Instruction::Or:
1134     case Instruction::ICmp:
1135       return true;
1136     default:
1137       return false;
1138     }
1139   };
1140   if (LooksLikeAFreeShift())
1141     return 0;
1142 
1143   int BaseCost = ST->hasMVEIntegerOps() && Ty->isVectorTy()
1144                      ? ST->getMVEVectorCostFactor()
1145                      : 1;
1146 
1147   // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost,
1148   // without treating floats as more expensive that scalars or increasing the
1149   // costs for custom operations. The results is also multiplied by the
1150   // MVEVectorCostFactor where appropriate.
1151   if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second))
1152     return LT.first * BaseCost;
1153 
1154   // Else this is expand, assume that we need to scalarize this op.
1155   if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
1156     unsigned Num = VTy->getNumElements();
1157     unsigned Cost = getArithmeticInstrCost(Opcode, Ty->getScalarType(),
1158                                            CostKind);
1159     // Return the cost of multiple scalar invocation plus the cost of
1160     // inserting and extracting the values.
1161     return BaseT::getScalarizationOverhead(VTy, Args) + Num * Cost;
1162   }
1163 
1164   return BaseCost;
1165 }
1166 
1167 int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
1168                                 MaybeAlign Alignment, unsigned AddressSpace,
1169                                 TTI::TargetCostKind CostKind,
1170                                 const Instruction *I) {
1171   // TODO: Handle other cost kinds.
1172   if (CostKind != TTI::TCK_RecipThroughput)
1173     return 1;
1174 
1175   // Type legalization can't handle structs
1176   if (TLI->getValueType(DL, Src, true) == MVT::Other)
1177     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1178                                   CostKind);
1179 
1180   if (ST->hasNEON() && Src->isVectorTy() &&
1181       (Alignment && *Alignment != Align(16)) &&
1182       cast<VectorType>(Src)->getElementType()->isDoubleTy()) {
1183     // Unaligned loads/stores are extremely inefficient.
1184     // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
1185     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
1186     return LT.first * 4;
1187   }
1188 
1189   // MVE can optimize a fpext(load(4xhalf)) using an extending integer load.
1190   // Same for stores.
1191   if (ST->hasMVEFloatOps() && isa<FixedVectorType>(Src) && I &&
1192       ((Opcode == Instruction::Load && I->hasOneUse() &&
1193         isa<FPExtInst>(*I->user_begin())) ||
1194        (Opcode == Instruction::Store && isa<FPTruncInst>(I->getOperand(0))))) {
1195     FixedVectorType *SrcVTy = cast<FixedVectorType>(Src);
1196     Type *DstTy =
1197         Opcode == Instruction::Load
1198             ? (*I->user_begin())->getType()
1199             : cast<Instruction>(I->getOperand(0))->getOperand(0)->getType();
1200     if (SrcVTy->getNumElements() == 4 && SrcVTy->getScalarType()->isHalfTy() &&
1201         DstTy->getScalarType()->isFloatTy())
1202       return ST->getMVEVectorCostFactor();
1203   }
1204 
1205   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
1206                      ? ST->getMVEVectorCostFactor()
1207                      : 1;
1208   return BaseCost * BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1209                                            CostKind, I);
1210 }
1211 
1212 int ARMTTIImpl::getInterleavedMemoryOpCost(
1213     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1214     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1215     bool UseMaskForCond, bool UseMaskForGaps) {
1216   assert(Factor >= 2 && "Invalid interleave factor");
1217   assert(isa<VectorType>(VecTy) && "Expect a vector type");
1218 
1219   // vldN/vstN doesn't support vector types of i64/f64 element.
1220   bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
1221 
1222   if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
1223       !UseMaskForCond && !UseMaskForGaps) {
1224     unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1225     auto *SubVecTy =
1226         FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
1227 
1228     // vldN/vstN only support legal vector types of size 64 or 128 in bits.
1229     // Accesses having vector types that are a multiple of 128 bits can be
1230     // matched to more than one vldN/vstN instruction.
1231     int BaseCost = ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor() : 1;
1232     if (NumElts % Factor == 0 &&
1233         TLI->isLegalInterleavedAccessType(Factor, SubVecTy, DL))
1234       return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL);
1235 
1236     // Some smaller than legal interleaved patterns are cheap as we can make
1237     // use of the vmovn or vrev patterns to interleave a standard load. This is
1238     // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is
1239     // promoted differently). The cost of 2 here is then a load and vrev or
1240     // vmovn.
1241     if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 &&
1242         VecTy->isIntOrIntVectorTy() && DL.getTypeSizeInBits(SubVecTy) <= 64)
1243       return 2 * BaseCost;
1244   }
1245 
1246   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1247                                            Alignment, AddressSpace, CostKind,
1248                                            UseMaskForCond, UseMaskForGaps);
1249 }
1250 
1251 unsigned ARMTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
1252                                             const Value *Ptr, bool VariableMask,
1253                                             Align Alignment,
1254                                             TTI::TargetCostKind CostKind,
1255                                             const Instruction *I) {
1256   using namespace PatternMatch;
1257   if (!ST->hasMVEIntegerOps() || !EnableMaskedGatherScatters)
1258     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
1259                                          Alignment, CostKind, I);
1260 
1261   assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!");
1262   auto *VTy = cast<FixedVectorType>(DataTy);
1263 
1264   // TODO: Splitting, once we do that.
1265 
1266   unsigned NumElems = VTy->getNumElements();
1267   unsigned EltSize = VTy->getScalarSizeInBits();
1268   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, DataTy);
1269 
1270   // For now, it is assumed that for the MVE gather instructions the loads are
1271   // all effectively serialised. This means the cost is the scalar cost
1272   // multiplied by the number of elements being loaded. This is possibly very
1273   // conservative, but even so we still end up vectorising loops because the
1274   // cost per iteration for many loops is lower than for scalar loops.
1275   unsigned VectorCost = NumElems * LT.first * ST->getMVEVectorCostFactor();
1276   // The scalarization cost should be a lot higher. We use the number of vector
1277   // elements plus the scalarization overhead.
1278   unsigned ScalarCost =
1279       NumElems * LT.first + BaseT::getScalarizationOverhead(VTy, {});
1280 
1281   if (Alignment < EltSize / 8)
1282     return ScalarCost;
1283 
1284   unsigned ExtSize = EltSize;
1285   // Check whether there's a single user that asks for an extended type
1286   if (I != nullptr) {
1287     // Dependent of the caller of this function, a gather instruction will
1288     // either have opcode Instruction::Load or be a call to the masked_gather
1289     // intrinsic
1290     if ((I->getOpcode() == Instruction::Load ||
1291          match(I, m_Intrinsic<Intrinsic::masked_gather>())) &&
1292         I->hasOneUse()) {
1293       const User *Us = *I->users().begin();
1294       if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) {
1295         // only allow valid type combinations
1296         unsigned TypeSize =
1297             cast<Instruction>(Us)->getType()->getScalarSizeInBits();
1298         if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) ||
1299              (TypeSize == 16 && EltSize == 8)) &&
1300             TypeSize * NumElems == 128) {
1301           ExtSize = TypeSize;
1302         }
1303       }
1304     }
1305     // Check whether the input data needs to be truncated
1306     TruncInst *T;
1307     if ((I->getOpcode() == Instruction::Store ||
1308          match(I, m_Intrinsic<Intrinsic::masked_scatter>())) &&
1309         (T = dyn_cast<TruncInst>(I->getOperand(0)))) {
1310       // Only allow valid type combinations
1311       unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits();
1312       if (((EltSize == 16 && TypeSize == 32) ||
1313            (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) &&
1314           TypeSize * NumElems == 128)
1315         ExtSize = TypeSize;
1316     }
1317   }
1318 
1319   if (ExtSize * NumElems != 128 || NumElems < 4)
1320     return ScalarCost;
1321 
1322   // Any (aligned) i32 gather will not need to be scalarised.
1323   if (ExtSize == 32)
1324     return VectorCost;
1325   // For smaller types, we need to ensure that the gep's inputs are correctly
1326   // extended from a small enough value. Other sizes (including i64) are
1327   // scalarized for now.
1328   if (ExtSize != 8 && ExtSize != 16)
1329     return ScalarCost;
1330 
1331   if (const auto *BC = dyn_cast<BitCastInst>(Ptr))
1332     Ptr = BC->getOperand(0);
1333   if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1334     if (GEP->getNumOperands() != 2)
1335       return ScalarCost;
1336     unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType());
1337     // Scale needs to be correct (which is only relevant for i16s).
1338     if (Scale != 1 && Scale * 8 != ExtSize)
1339       return ScalarCost;
1340     // And we need to zext (not sext) the indexes from a small enough type.
1341     if (const auto *ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) {
1342       if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize)
1343         return VectorCost;
1344     }
1345     return ScalarCost;
1346   }
1347   return ScalarCost;
1348 }
1349 
1350 bool ARMTTIImpl::isLoweredToCall(const Function *F) {
1351   if (!F->isIntrinsic())
1352     BaseT::isLoweredToCall(F);
1353 
1354   // Assume all Arm-specific intrinsics map to an instruction.
1355   if (F->getName().startswith("llvm.arm"))
1356     return false;
1357 
1358   switch (F->getIntrinsicID()) {
1359   default: break;
1360   case Intrinsic::powi:
1361   case Intrinsic::sin:
1362   case Intrinsic::cos:
1363   case Intrinsic::pow:
1364   case Intrinsic::log:
1365   case Intrinsic::log10:
1366   case Intrinsic::log2:
1367   case Intrinsic::exp:
1368   case Intrinsic::exp2:
1369     return true;
1370   case Intrinsic::sqrt:
1371   case Intrinsic::fabs:
1372   case Intrinsic::copysign:
1373   case Intrinsic::floor:
1374   case Intrinsic::ceil:
1375   case Intrinsic::trunc:
1376   case Intrinsic::rint:
1377   case Intrinsic::nearbyint:
1378   case Intrinsic::round:
1379   case Intrinsic::canonicalize:
1380   case Intrinsic::lround:
1381   case Intrinsic::llround:
1382   case Intrinsic::lrint:
1383   case Intrinsic::llrint:
1384     if (F->getReturnType()->isDoubleTy() && !ST->hasFP64())
1385       return true;
1386     if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16())
1387       return true;
1388     // Some operations can be handled by vector instructions and assume
1389     // unsupported vectors will be expanded into supported scalar ones.
1390     // TODO Handle scalar operations properly.
1391     return !ST->hasFPARMv8Base() && !ST->hasVFP2Base();
1392   case Intrinsic::masked_store:
1393   case Intrinsic::masked_load:
1394   case Intrinsic::masked_gather:
1395   case Intrinsic::masked_scatter:
1396     return !ST->hasMVEIntegerOps();
1397   case Intrinsic::sadd_with_overflow:
1398   case Intrinsic::uadd_with_overflow:
1399   case Intrinsic::ssub_with_overflow:
1400   case Intrinsic::usub_with_overflow:
1401   case Intrinsic::sadd_sat:
1402   case Intrinsic::uadd_sat:
1403   case Intrinsic::ssub_sat:
1404   case Intrinsic::usub_sat:
1405     return false;
1406   }
1407 
1408   return BaseT::isLoweredToCall(F);
1409 }
1410 
1411 bool ARMTTIImpl::maybeLoweredToCall(Instruction &I) {
1412   unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode());
1413   EVT VT = TLI->getValueType(DL, I.getType(), true);
1414   if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall)
1415     return true;
1416 
1417   // Check if an intrinsic will be lowered to a call and assume that any
1418   // other CallInst will generate a bl.
1419   if (auto *Call = dyn_cast<CallInst>(&I)) {
1420     if (isa<IntrinsicInst>(Call)) {
1421       if (const Function *F = Call->getCalledFunction())
1422         return isLoweredToCall(F);
1423     }
1424     return true;
1425   }
1426 
1427   // FPv5 provides conversions between integer, double-precision,
1428   // single-precision, and half-precision formats.
1429   switch (I.getOpcode()) {
1430   default:
1431     break;
1432   case Instruction::FPToSI:
1433   case Instruction::FPToUI:
1434   case Instruction::SIToFP:
1435   case Instruction::UIToFP:
1436   case Instruction::FPTrunc:
1437   case Instruction::FPExt:
1438     return !ST->hasFPARMv8Base();
1439   }
1440 
1441   // FIXME: Unfortunately the approach of checking the Operation Action does
1442   // not catch all cases of Legalization that use library calls. Our
1443   // Legalization step categorizes some transformations into library calls as
1444   // Custom, Expand or even Legal when doing type legalization. So for now
1445   // we have to special case for instance the SDIV of 64bit integers and the
1446   // use of floating point emulation.
1447   if (VT.isInteger() && VT.getSizeInBits() >= 64) {
1448     switch (ISD) {
1449     default:
1450       break;
1451     case ISD::SDIV:
1452     case ISD::UDIV:
1453     case ISD::SREM:
1454     case ISD::UREM:
1455     case ISD::SDIVREM:
1456     case ISD::UDIVREM:
1457       return true;
1458     }
1459   }
1460 
1461   // Assume all other non-float operations are supported.
1462   if (!VT.isFloatingPoint())
1463     return false;
1464 
1465   // We'll need a library call to handle most floats when using soft.
1466   if (TLI->useSoftFloat()) {
1467     switch (I.getOpcode()) {
1468     default:
1469       return true;
1470     case Instruction::Alloca:
1471     case Instruction::Load:
1472     case Instruction::Store:
1473     case Instruction::Select:
1474     case Instruction::PHI:
1475       return false;
1476     }
1477   }
1478 
1479   // We'll need a libcall to perform double precision operations on a single
1480   // precision only FPU.
1481   if (I.getType()->isDoubleTy() && !ST->hasFP64())
1482     return true;
1483 
1484   // Likewise for half precision arithmetic.
1485   if (I.getType()->isHalfTy() && !ST->hasFullFP16())
1486     return true;
1487 
1488   return false;
1489 }
1490 
1491 bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1492                                           AssumptionCache &AC,
1493                                           TargetLibraryInfo *LibInfo,
1494                                           HardwareLoopInfo &HWLoopInfo) {
1495   // Low-overhead branches are only supported in the 'low-overhead branch'
1496   // extension of v8.1-m.
1497   if (!ST->hasLOB() || DisableLowOverheadLoops) {
1498     LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n");
1499     return false;
1500   }
1501 
1502   if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
1503     LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n");
1504     return false;
1505   }
1506 
1507   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1508   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
1509     LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n");
1510     return false;
1511   }
1512 
1513   const SCEV *TripCountSCEV =
1514     SE.getAddExpr(BackedgeTakenCount,
1515                   SE.getOne(BackedgeTakenCount->getType()));
1516 
1517   // We need to store the trip count in LR, a 32-bit register.
1518   if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) {
1519     LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n");
1520     return false;
1521   }
1522 
1523   // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little
1524   // point in generating a hardware loop if that's going to happen.
1525 
1526   auto IsHardwareLoopIntrinsic = [](Instruction &I) {
1527     if (auto *Call = dyn_cast<IntrinsicInst>(&I)) {
1528       switch (Call->getIntrinsicID()) {
1529       default:
1530         break;
1531       case Intrinsic::set_loop_iterations:
1532       case Intrinsic::test_set_loop_iterations:
1533       case Intrinsic::loop_decrement:
1534       case Intrinsic::loop_decrement_reg:
1535         return true;
1536       }
1537     }
1538     return false;
1539   };
1540 
1541   // Scan the instructions to see if there's any that we know will turn into a
1542   // call or if this loop is already a low-overhead loop.
1543   auto ScanLoop = [&](Loop *L) {
1544     for (auto *BB : L->getBlocks()) {
1545       for (auto &I : *BB) {
1546         if (maybeLoweredToCall(I) || IsHardwareLoopIntrinsic(I)) {
1547           LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n");
1548           return false;
1549         }
1550       }
1551     }
1552     return true;
1553   };
1554 
1555   // Visit inner loops.
1556   for (auto Inner : *L)
1557     if (!ScanLoop(Inner))
1558       return false;
1559 
1560   if (!ScanLoop(L))
1561     return false;
1562 
1563   // TODO: Check whether the trip count calculation is expensive. If L is the
1564   // inner loop but we know it has a low trip count, calculating that trip
1565   // count (in the parent loop) may be detrimental.
1566 
1567   LLVMContext &C = L->getHeader()->getContext();
1568   HWLoopInfo.CounterInReg = true;
1569   HWLoopInfo.IsNestingLegal = false;
1570   HWLoopInfo.PerformEntryTest = true;
1571   HWLoopInfo.CountType = Type::getInt32Ty(C);
1572   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
1573   return true;
1574 }
1575 
1576 static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) {
1577   // We don't allow icmp's, and because we only look at single block loops,
1578   // we simply count the icmps, i.e. there should only be 1 for the backedge.
1579   if (isa<ICmpInst>(&I) && ++ICmpCount > 1)
1580     return false;
1581 
1582   if (isa<FCmpInst>(&I))
1583     return false;
1584 
1585   // We could allow extending/narrowing FP loads/stores, but codegen is
1586   // too inefficient so reject this for now.
1587   if (isa<FPExtInst>(&I) || isa<FPTruncInst>(&I))
1588     return false;
1589 
1590   // Extends have to be extending-loads
1591   if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) )
1592     if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0)))
1593       return false;
1594 
1595   // Truncs have to be narrowing-stores
1596   if (isa<TruncInst>(&I) )
1597     if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin()))
1598       return false;
1599 
1600   return true;
1601 }
1602 
1603 // To set up a tail-predicated loop, we need to know the total number of
1604 // elements processed by that loop. Thus, we need to determine the element
1605 // size and:
1606 // 1) it should be uniform for all operations in the vector loop, so we
1607 //    e.g. don't want any widening/narrowing operations.
1608 // 2) it should be smaller than i64s because we don't have vector operations
1609 //    that work on i64s.
1610 // 3) we don't want elements to be reversed or shuffled, to make sure the
1611 //    tail-predication masks/predicates the right lanes.
1612 //
1613 static bool canTailPredicateLoop(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
1614                                  const DataLayout &DL,
1615                                  const LoopAccessInfo *LAI) {
1616   LLVM_DEBUG(dbgs() << "Tail-predication: checking allowed instructions\n");
1617 
1618   // If there are live-out values, it is probably a reduction. We can predicate
1619   // most reduction operations freely under MVE using a combination of
1620   // prefer-predicated-reduction-select and inloop reductions. We limit this to
1621   // floating point and integer reductions, but don't check for operators
1622   // specifically here. If the value ends up not being a reduction (and so the
1623   // vectorizer cannot tailfold the loop), we should fall back to standard
1624   // vectorization automatically.
1625   SmallVector< Instruction *, 8 > LiveOuts;
1626   LiveOuts = llvm::findDefsUsedOutsideOfLoop(L);
1627   bool ReductionsDisabled =
1628       EnableTailPredication == TailPredication::EnabledNoReductions ||
1629       EnableTailPredication == TailPredication::ForceEnabledNoReductions;
1630 
1631   for (auto *I : LiveOuts) {
1632     if (!I->getType()->isIntegerTy() && !I->getType()->isFloatTy() &&
1633         !I->getType()->isHalfTy()) {
1634       LLVM_DEBUG(dbgs() << "Don't tail-predicate loop with non-integer/float "
1635                            "live-out value\n");
1636       return false;
1637     }
1638     if (ReductionsDisabled) {
1639       LLVM_DEBUG(dbgs() << "Reductions not enabled\n");
1640       return false;
1641     }
1642   }
1643 
1644   // Next, check that all instructions can be tail-predicated.
1645   PredicatedScalarEvolution PSE = LAI->getPSE();
1646   SmallVector<Instruction *, 16> LoadStores;
1647   int ICmpCount = 0;
1648 
1649   for (BasicBlock *BB : L->blocks()) {
1650     for (Instruction &I : BB->instructionsWithoutDebug()) {
1651       if (isa<PHINode>(&I))
1652         continue;
1653       if (!canTailPredicateInstruction(I, ICmpCount)) {
1654         LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump());
1655         return false;
1656       }
1657 
1658       Type *T  = I.getType();
1659       if (T->isPointerTy())
1660         T = T->getPointerElementType();
1661 
1662       if (T->getScalarSizeInBits() > 32) {
1663         LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump());
1664         return false;
1665       }
1666       if (isa<StoreInst>(I) || isa<LoadInst>(I)) {
1667         Value *Ptr = isa<LoadInst>(I) ? I.getOperand(0) : I.getOperand(1);
1668         int64_t NextStride = getPtrStride(PSE, Ptr, L);
1669         if (NextStride == 1) {
1670           // TODO: for now only allow consecutive strides of 1. We could support
1671           // other strides as long as it is uniform, but let's keep it simple
1672           // for now.
1673           continue;
1674         } else if (NextStride == -1 ||
1675                    (NextStride == 2 && MVEMaxSupportedInterleaveFactor >= 2) ||
1676                    (NextStride == 4 && MVEMaxSupportedInterleaveFactor >= 4)) {
1677           LLVM_DEBUG(dbgs()
1678                      << "Consecutive strides of 2 found, vld2/vstr2 can't "
1679                         "be tail-predicated\n.");
1680           return false;
1681           // TODO: don't tail predicate if there is a reversed load?
1682         } else if (EnableMaskedGatherScatters) {
1683           // Gather/scatters do allow loading from arbitrary strides, at
1684           // least if they are loop invariant.
1685           // TODO: Loop variant strides should in theory work, too, but
1686           // this requires further testing.
1687           const SCEV *PtrScev =
1688               replaceSymbolicStrideSCEV(PSE, llvm::ValueToValueMap(), Ptr);
1689           if (auto AR = dyn_cast<SCEVAddRecExpr>(PtrScev)) {
1690             const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1691             if (PSE.getSE()->isLoopInvariant(Step, L))
1692               continue;
1693           }
1694         }
1695         LLVM_DEBUG(dbgs() << "Bad stride found, can't "
1696                              "tail-predicate\n.");
1697         return false;
1698       }
1699     }
1700   }
1701 
1702   LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n");
1703   return true;
1704 }
1705 
1706 bool ARMTTIImpl::preferPredicateOverEpilogue(Loop *L, LoopInfo *LI,
1707                                              ScalarEvolution &SE,
1708                                              AssumptionCache &AC,
1709                                              TargetLibraryInfo *TLI,
1710                                              DominatorTree *DT,
1711                                              const LoopAccessInfo *LAI) {
1712   if (!EnableTailPredication) {
1713     LLVM_DEBUG(dbgs() << "Tail-predication not enabled.\n");
1714     return false;
1715   }
1716 
1717   // Creating a predicated vector loop is the first step for generating a
1718   // tail-predicated hardware loop, for which we need the MVE masked
1719   // load/stores instructions:
1720   if (!ST->hasMVEIntegerOps())
1721     return false;
1722 
1723   // For now, restrict this to single block loops.
1724   if (L->getNumBlocks() > 1) {
1725     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: not a single block "
1726                          "loop.\n");
1727     return false;
1728   }
1729 
1730   assert(L->empty() && "preferPredicateOverEpilogue: inner-loop expected");
1731 
1732   HardwareLoopInfo HWLoopInfo(L);
1733   if (!HWLoopInfo.canAnalyze(*LI)) {
1734     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1735                          "analyzable.\n");
1736     return false;
1737   }
1738 
1739   // This checks if we have the low-overhead branch architecture
1740   // extension, and if we will create a hardware-loop:
1741   if (!isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) {
1742     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1743                          "profitable.\n");
1744     return false;
1745   }
1746 
1747   if (!HWLoopInfo.isHardwareLoopCandidate(SE, *LI, *DT)) {
1748     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1749                          "a candidate.\n");
1750     return false;
1751   }
1752 
1753   return canTailPredicateLoop(L, LI, SE, DL, LAI);
1754 }
1755 
1756 bool ARMTTIImpl::emitGetActiveLaneMask() const {
1757   if (!ST->hasMVEIntegerOps() || !EnableTailPredication)
1758     return false;
1759 
1760   // Intrinsic @llvm.get.active.lane.mask is supported.
1761   // It is used in the MVETailPredication pass, which requires the number of
1762   // elements processed by this vector loop to setup the tail-predicated
1763   // loop.
1764   return true;
1765 }
1766 void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1767                                          TTI::UnrollingPreferences &UP) {
1768   // Only currently enable these preferences for M-Class cores.
1769   if (!ST->isMClass())
1770     return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP);
1771 
1772   // Disable loop unrolling for Oz and Os.
1773   UP.OptSizeThreshold = 0;
1774   UP.PartialOptSizeThreshold = 0;
1775   if (L->getHeader()->getParent()->hasOptSize())
1776     return;
1777 
1778   // Only enable on Thumb-2 targets.
1779   if (!ST->isThumb2())
1780     return;
1781 
1782   SmallVector<BasicBlock*, 4> ExitingBlocks;
1783   L->getExitingBlocks(ExitingBlocks);
1784   LLVM_DEBUG(dbgs() << "Loop has:\n"
1785                     << "Blocks: " << L->getNumBlocks() << "\n"
1786                     << "Exit blocks: " << ExitingBlocks.size() << "\n");
1787 
1788   // Only allow another exit other than the latch. This acts as an early exit
1789   // as it mirrors the profitability calculation of the runtime unroller.
1790   if (ExitingBlocks.size() > 2)
1791     return;
1792 
1793   // Limit the CFG of the loop body for targets with a branch predictor.
1794   // Allowing 4 blocks permits if-then-else diamonds in the body.
1795   if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
1796     return;
1797 
1798   // Scan the loop: don't unroll loops with calls as this could prevent
1799   // inlining.
1800   unsigned Cost = 0;
1801   for (auto *BB : L->getBlocks()) {
1802     for (auto &I : *BB) {
1803       // Don't unroll vectorised loop. MVE does not benefit from it as much as
1804       // scalar code.
1805       if (I.getType()->isVectorTy())
1806         return;
1807 
1808       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1809         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
1810           if (!isLoweredToCall(F))
1811             continue;
1812         }
1813         return;
1814       }
1815 
1816       SmallVector<const Value*, 4> Operands(I.value_op_begin(),
1817                                             I.value_op_end());
1818       Cost +=
1819         getUserCost(&I, Operands, TargetTransformInfo::TCK_SizeAndLatency);
1820     }
1821   }
1822 
1823   LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
1824 
1825   UP.Partial = true;
1826   UP.Runtime = true;
1827   UP.UpperBound = true;
1828   UP.UnrollRemainder = true;
1829   UP.DefaultUnrollRuntimeCount = 4;
1830   UP.UnrollAndJam = true;
1831   UP.UnrollAndJamInnerLoopThreshold = 60;
1832 
1833   // Force unrolling small loops can be very useful because of the branch
1834   // taken cost of the backedge.
1835   if (Cost < 12)
1836     UP.Force = true;
1837 }
1838 
1839 void ARMTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
1840                                        TTI::PeelingPreferences &PP) {
1841   BaseT::getPeelingPreferences(L, SE, PP);
1842 }
1843 
1844 bool ARMTTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
1845                                        TTI::ReductionFlags Flags) const {
1846   return ST->hasMVEIntegerOps();
1847 }
1848 
1849 bool ARMTTIImpl::preferPredicatedReductionSelect(
1850     unsigned Opcode, Type *Ty, TTI::ReductionFlags Flags) const {
1851   if (!ST->hasMVEIntegerOps())
1852     return false;
1853   return true;
1854 }
1855