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