LLVM  5.0.0
BasicTTIImpl.h
Go to the documentation of this file.
1 //===- BasicTTIImpl.h -------------------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file provides a helper that implements much of the TTI interface in
11 /// terms of the target-independent code generator and TargetLowering
12 /// interfaces.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_CODEGEN_BASICTTIIMPL_H
17 #define LLVM_CODEGEN_BASICTTIIMPL_H
18 
19 #include "llvm/Analysis/LoopInfo.h"
25 
26 namespace llvm {
27 
28 extern cl::opt<unsigned> PartialUnrollingThreshold;
29 
30 /// \brief Base class which can be used to help build a TTI implementation.
31 ///
32 /// This class provides as much implementation of the TTI interface as is
33 /// possible using the target independent parts of the code generator.
34 ///
35 /// In order to subclass it, your class must implement a getST() method to
36 /// return the subtarget, and a getTLI() method to return the target lowering.
37 /// We need these methods implemented in the derived class so that this class
38 /// doesn't have to duplicate storage for them.
39 template <typename T>
41 private:
43  typedef TargetTransformInfo TTI;
44 
45  /// Estimate a cost of shuffle as a sequence of extract and insert
46  /// operations.
47  unsigned getPermuteShuffleOverhead(Type *Ty) {
48  assert(Ty->isVectorTy() && "Can only shuffle vectors");
49  unsigned Cost = 0;
50  // Shuffle cost is equal to the cost of extracting element from its argument
51  // plus the cost of inserting them onto the result vector.
52 
53  // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
54  // index 0 of first vector, index 1 of second vector,index 2 of first
55  // vector and finally index 3 of second vector and insert them at index
56  // <0,1,2,3> of result vector.
57  for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
58  Cost += static_cast<T *>(this)
59  ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
60  Cost += static_cast<T *>(this)
61  ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
62  }
63  return Cost;
64  }
65 
66  /// \brief Local query method delegates up to T which *must* implement this!
67  const TargetSubtargetInfo *getST() const {
68  return static_cast<const T *>(this)->getST();
69  }
70 
71  /// \brief Local query method delegates up to T which *must* implement this!
72  const TargetLoweringBase *getTLI() const {
73  return static_cast<const T *>(this)->getTLI();
74  }
75 
76 protected:
77  explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
78  : BaseT(DL) {}
79 
81 
82 public:
83  /// \name Scalar TTI Implementations
84  /// @{
86  unsigned BitWidth, unsigned AddressSpace,
87  unsigned Alignment, bool *Fast) const {
88  EVT E = EVT::getIntegerVT(Context, BitWidth);
89  return getTLI()->allowsMisalignedMemoryAccesses(E, AddressSpace, Alignment, Fast);
90  }
91 
92  bool hasBranchDivergence() { return false; }
93 
94  bool isSourceOfDivergence(const Value *V) { return false; }
95 
96  bool isAlwaysUniform(const Value *V) { return false; }
97 
98  unsigned getFlatAddressSpace() {
99  // Return an invalid address space.
100  return -1;
101  }
102 
103  bool isLegalAddImmediate(int64_t imm) {
104  return getTLI()->isLegalAddImmediate(imm);
105  }
106 
107  bool isLegalICmpImmediate(int64_t imm) {
108  return getTLI()->isLegalICmpImmediate(imm);
109  }
110 
111  bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
112  bool HasBaseReg, int64_t Scale,
113  unsigned AddrSpace) {
115  AM.BaseGV = BaseGV;
116  AM.BaseOffs = BaseOffset;
117  AM.HasBaseReg = HasBaseReg;
118  AM.Scale = Scale;
119  return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace);
120  }
121 
124  }
125 
126  int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
127  bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
129  AM.BaseGV = BaseGV;
130  AM.BaseOffs = BaseOffset;
131  AM.HasBaseReg = HasBaseReg;
132  AM.Scale = Scale;
133  return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
134  }
135 
137  return getTLI()->isFoldableMemAccessOffset(I, Offset);
138  }
139 
140  bool isTruncateFree(Type *Ty1, Type *Ty2) {
141  return getTLI()->isTruncateFree(Ty1, Ty2);
142  }
143 
145  return getTLI()->isProfitableToHoist(I);
146  }
147 
148  bool isTypeLegal(Type *Ty) {
149  EVT VT = getTLI()->getValueType(DL, Ty);
150  return getTLI()->isTypeLegal(VT);
151  }
152 
153  int getGEPCost(Type *PointeeType, const Value *Ptr,
154  ArrayRef<const Value *> Operands) {
155  return BaseT::getGEPCost(PointeeType, Ptr, Operands);
156  }
157 
158  int getExtCost(const Instruction *I, const Value *Src) {
159  if (getTLI()->isExtFree(I))
161 
162  if (isa<ZExtInst>(I) || isa<SExtInst>(I))
163  if (const LoadInst *LI = dyn_cast<LoadInst>(Src))
164  if (getTLI()->isExtLoad(LI, I, DL))
166 
168  }
169 
170  unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
171  ArrayRef<const Value *> Arguments) {
172  return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
173  }
174 
175  unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
176  ArrayRef<Type *> ParamTys) {
177  if (IID == Intrinsic::cttz) {
178  if (getTLI()->isCheapToSpeculateCttz())
181  }
182 
183  if (IID == Intrinsic::ctlz) {
184  if (getTLI()->isCheapToSpeculateCtlz())
187  }
188 
189  return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
190  }
191 
193  unsigned &JumpTableSize) {
194  /// Try to find the estimated number of clusters. Note that the number of
195  /// clusters identified in this function could be different from the actural
196  /// numbers found in lowering. This function ignore switches that are
197  /// lowered with a mix of jump table / bit test / BTree. This function was
198  /// initially intended to be used when estimating the cost of switch in
199  /// inline cost heuristic, but it's a generic cost model to be used in other
200  /// places (e.g., in loop unrolling).
201  unsigned N = SI.getNumCases();
202  const TargetLoweringBase *TLI = getTLI();
203  const DataLayout &DL = this->getDataLayout();
204 
205  JumpTableSize = 0;
206  bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
207 
208  // Early exit if both a jump table and bit test are not allowed.
209  if (N < 1 || (!IsJTAllowed && DL.getPointerSizeInBits() < N))
210  return N;
211 
212  APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
213  APInt MinCaseVal = MaxCaseVal;
214  for (auto CI : SI.cases()) {
215  const APInt &CaseVal = CI.getCaseValue()->getValue();
216  if (CaseVal.sgt(MaxCaseVal))
217  MaxCaseVal = CaseVal;
218  if (CaseVal.slt(MinCaseVal))
219  MinCaseVal = CaseVal;
220  }
221 
222  // Check if suitable for a bit test
223  if (N <= DL.getPointerSizeInBits()) {
225  for (auto I : SI.cases())
226  Dests.insert(I.getCaseSuccessor());
227 
228  if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
229  DL))
230  return 1;
231  }
232 
233  // Check if suitable for a jump table.
234  if (IsJTAllowed) {
235  if (N < 2 || N < TLI->getMinimumJumpTableEntries())
236  return N;
237  uint64_t Range =
238  (MaxCaseVal - MinCaseVal).getLimitedValue(UINT64_MAX - 1) + 1;
239  // Check whether a range of clusters is dense enough for a jump table
240  if (TLI->isSuitableForJumpTable(&SI, N, Range)) {
241  JumpTableSize = Range;
242  return 1;
243  }
244  }
245  return N;
246  }
247 
248  unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
249 
250  unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
251 
253  const TargetLoweringBase *TLI = getTLI();
256  }
257 
258  bool haveFastSqrt(Type *Ty) {
259  const TargetLoweringBase *TLI = getTLI();
260  EVT VT = TLI->getValueType(DL, Ty);
261  return TLI->isTypeLegal(VT) &&
263  }
264 
265  unsigned getFPOpCost(Type *Ty) {
266  // By default, FP instructions are no more expensive since they are
267  // implemented in HW. Target specific TTI can override this.
269  }
270 
271  unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
272  const TargetLoweringBase *TLI = getTLI();
273  switch (Opcode) {
274  default: break;
275  case Instruction::Trunc: {
276  if (TLI->isTruncateFree(OpTy, Ty))
279  }
280  case Instruction::ZExt: {
281  if (TLI->isZExtFree(OpTy, Ty))
284  }
285  }
286 
287  return BaseT::getOperationCost(Opcode, Ty, OpTy);
288  }
289 
290  unsigned getInliningThresholdMultiplier() { return 1; }
291 
294  // This unrolling functionality is target independent, but to provide some
295  // motivation for its intended use, for x86:
296 
297  // According to the Intel 64 and IA-32 Architectures Optimization Reference
298  // Manual, Intel Core models and later have a loop stream detector (and
299  // associated uop queue) that can benefit from partial unrolling.
300  // The relevant requirements are:
301  // - The loop must have no more than 4 (8 for Nehalem and later) branches
302  // taken, and none of them may be calls.
303  // - The loop can have no more than 18 (28 for Nehalem and later) uops.
304 
305  // According to the Software Optimization Guide for AMD Family 15h
306  // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
307  // and loop buffer which can benefit from partial unrolling.
308  // The relevant requirements are:
309  // - The loop must have fewer than 16 branches
310  // - The loop must have less than 40 uops in all executed loop branches
311 
312  // The number of taken branches in a loop is hard to estimate here, and
313  // benchmarking has revealed that it is better not to be conservative when
314  // estimating the branch count. As a result, we'll ignore the branch limits
315  // until someone finds a case where it matters in practice.
316 
317  unsigned MaxOps;
318  const TargetSubtargetInfo *ST = getST();
319  if (PartialUnrollingThreshold.getNumOccurrences() > 0)
320  MaxOps = PartialUnrollingThreshold;
321  else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
322  MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
323  else
324  return;
325 
326  // Scan the loop: don't unroll loops with calls.
327  for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
328  ++I) {
329  BasicBlock *BB = *I;
330 
331  for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
332  if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
333  ImmutableCallSite CS(&*J);
334  if (const Function *F = CS.getCalledFunction()) {
335  if (!static_cast<T *>(this)->isLoweredToCall(F))
336  continue;
337  }
338 
339  return;
340  }
341  }
342 
343  // Enable runtime and partial unrolling up to the specified size.
344  // Enable using trip count upper bound to unroll loops.
345  UP.Partial = UP.Runtime = UP.UpperBound = true;
346  UP.PartialThreshold = MaxOps;
347 
348  // Avoid unrolling when optimizing for size.
349  UP.OptSizeThreshold = 0;
351 
352  // Set number of instructions optimized when "back edge"
353  // becomes "fall through" to default value of 2.
354  UP.BEInsns = 2;
355  }
356 
357  /// @}
358 
359  /// \name Vector TTI Implementations
360  /// @{
361 
362  unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
363 
364  unsigned getRegisterBitWidth(bool Vector) const { return 32; }
365 
366  /// Estimate the overhead of scalarizing an instruction. Insert and Extract
367  /// are set if the result needs to be inserted and/or extracted from vectors.
368  unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
369  assert(Ty->isVectorTy() && "Can only scalarize vectors");
370  unsigned Cost = 0;
371 
372  for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
373  if (Insert)
374  Cost += static_cast<T *>(this)
375  ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
376  if (Extract)
377  Cost += static_cast<T *>(this)
378  ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
379  }
380 
381  return Cost;
382  }
383 
384  /// Estimate the overhead of scalarizing an instructions unique
385  /// non-constant operands. The types of the arguments are ordinarily
386  /// scalar, in which case the costs are multiplied with VF.
388  unsigned VF) {
389  unsigned Cost = 0;
390  SmallPtrSet<const Value*, 4> UniqueOperands;
391  for (const Value *A : Args) {
392  if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
393  Type *VecTy = nullptr;
394  if (A->getType()->isVectorTy()) {
395  VecTy = A->getType();
396  // If A is a vector operand, VF should be 1 or correspond to A.
397  assert ((VF == 1 || VF == VecTy->getVectorNumElements()) &&
398  "Vector argument does not match VF");
399  }
400  else
401  VecTy = VectorType::get(A->getType(), VF);
402 
403  Cost += getScalarizationOverhead(VecTy, false, true);
404  }
405  }
406 
407  return Cost;
408  }
409 
411  assert (VecTy->isVectorTy());
412 
413  unsigned Cost = 0;
414 
415  Cost += getScalarizationOverhead(VecTy, true, false);
416  if (!Args.empty())
418  VecTy->getVectorNumElements());
419  else
420  // When no information on arguments is provided, we add the cost
421  // associated with one argument as a heuristic.
422  Cost += getScalarizationOverhead(VecTy, false, true);
423 
424  return Cost;
425  }
426 
427  unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
428 
430  unsigned Opcode, Type *Ty,
436  // Check if any of the operands are vector operands.
437  const TargetLoweringBase *TLI = getTLI();
438  int ISD = TLI->InstructionOpcodeToISD(Opcode);
439  assert(ISD && "Invalid opcode");
440 
441  std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
442 
443  bool IsFloat = Ty->isFPOrFPVectorTy();
444  // Assume that floating point arithmetic operations cost twice as much as
445  // integer operations.
446  unsigned OpCost = (IsFloat ? 2 : 1);
447 
448  if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
449  // The operation is legal. Assume it costs 1.
450  // TODO: Once we have extract/insert subvector cost we need to use them.
451  return LT.first * OpCost;
452  }
453 
454  if (!TLI->isOperationExpand(ISD, LT.second)) {
455  // If the operation is custom lowered, then assume that the code is twice
456  // as expensive.
457  return LT.first * 2 * OpCost;
458  }
459 
460  // Else, assume that we need to scalarize this op.
461  // TODO: If one of the types get legalized by splitting, handle this
462  // similarly to what getCastInstrCost() does.
463  if (Ty->isVectorTy()) {
464  unsigned Num = Ty->getVectorNumElements();
465  unsigned Cost = static_cast<T *>(this)
466  ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
467  // Return the cost of multiple scalar invocation plus the cost of
468  // inserting and extracting the values.
469  return getScalarizationOverhead(Ty, Args) + Num * Cost;
470  }
471 
472  // We don't know anything about this scalar instruction.
473  return OpCost;
474  }
475 
476  unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
477  Type *SubTp) {
478  if (Kind == TTI::SK_Alternate || Kind == TTI::SK_PermuteTwoSrc ||
479  Kind == TTI::SK_PermuteSingleSrc) {
480  return getPermuteShuffleOverhead(Tp);
481  }
482  return 1;
483  }
484 
485  unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
486  const Instruction *I = nullptr) {
487  const TargetLoweringBase *TLI = getTLI();
488  int ISD = TLI->InstructionOpcodeToISD(Opcode);
489  assert(ISD && "Invalid opcode");
490  std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
491  std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
492 
493  // Check for NOOP conversions.
494  if (SrcLT.first == DstLT.first &&
495  SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
496 
497  // Bitcast between types that are legalized to the same type are free.
498  if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
499  return 0;
500  }
501 
502  if (Opcode == Instruction::Trunc &&
503  TLI->isTruncateFree(SrcLT.second, DstLT.second))
504  return 0;
505 
506  if (Opcode == Instruction::ZExt &&
507  TLI->isZExtFree(SrcLT.second, DstLT.second))
508  return 0;
509 
510  if (Opcode == Instruction::AddrSpaceCast &&
512  Dst->getPointerAddressSpace()))
513  return 0;
514 
515  // If this is a zext/sext of a load, return 0 if the corresponding
516  // extending load exists on target.
517  if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
518  I && isa<LoadInst>(I->getOperand(0))) {
519  EVT ExtVT = EVT::getEVT(Dst);
520  EVT LoadVT = EVT::getEVT(Src);
521  unsigned LType =
522  ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
523  if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
524  return 0;
525  }
526 
527  // If the cast is marked as legal (or promote) then assume low cost.
528  if (SrcLT.first == DstLT.first &&
529  TLI->isOperationLegalOrPromote(ISD, DstLT.second))
530  return 1;
531 
532  // Handle scalar conversions.
533  if (!Src->isVectorTy() && !Dst->isVectorTy()) {
534 
535  // Scalar bitcasts are usually free.
536  if (Opcode == Instruction::BitCast)
537  return 0;
538 
539  // Just check the op cost. If the operation is legal then assume it costs
540  // 1.
541  if (!TLI->isOperationExpand(ISD, DstLT.second))
542  return 1;
543 
544  // Assume that illegal scalar instruction are expensive.
545  return 4;
546  }
547 
548  // Check vector-to-vector casts.
549  if (Dst->isVectorTy() && Src->isVectorTy()) {
550 
551  // If the cast is between same-sized registers, then the check is simple.
552  if (SrcLT.first == DstLT.first &&
553  SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
554 
555  // Assume that Zext is done using AND.
556  if (Opcode == Instruction::ZExt)
557  return 1;
558 
559  // Assume that sext is done using SHL and SRA.
560  if (Opcode == Instruction::SExt)
561  return 2;
562 
563  // Just check the op cost. If the operation is legal then assume it
564  // costs
565  // 1 and multiply by the type-legalization overhead.
566  if (!TLI->isOperationExpand(ISD, DstLT.second))
567  return SrcLT.first * 1;
568  }
569 
570  // If we are legalizing by splitting, query the concrete TTI for the cost
571  // of casting the original vector twice. We also need to factor int the
572  // cost of the split itself. Count that as 1, to be consistent with
573  // TLI->getTypeLegalizationCost().
574  if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
576  (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
578  Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
579  Dst->getVectorNumElements() / 2);
580  Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
581  Src->getVectorNumElements() / 2);
582  T *TTI = static_cast<T *>(this);
583  return TTI->getVectorSplitCost() +
584  (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
585  }
586 
587  // In other cases where the source or destination are illegal, assume
588  // the operation will get scalarized.
589  unsigned Num = Dst->getVectorNumElements();
590  unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
591  Opcode, Dst->getScalarType(), Src->getScalarType(), I);
592 
593  // Return the cost of multiple scalar invocation plus the cost of
594  // inserting and extracting the values.
595  return getScalarizationOverhead(Dst, true, true) + Num * Cost;
596  }
597 
598  // We already handled vector-to-vector and scalar-to-scalar conversions.
599  // This
600  // is where we handle bitcast between vectors and scalars. We need to assume
601  // that the conversion is scalarized in one way or another.
602  if (Opcode == Instruction::BitCast)
603  // Illegal bitcasts are done by storing and loading from a stack slot.
604  return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
605  : 0) +
606  (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
607  : 0);
608 
609  llvm_unreachable("Unhandled cast");
610  }
611 
612  unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
613  VectorType *VecTy, unsigned Index) {
614  return static_cast<T *>(this)->getVectorInstrCost(
615  Instruction::ExtractElement, VecTy, Index) +
616  static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
617  VecTy->getElementType());
618  }
619 
620  unsigned getCFInstrCost(unsigned Opcode) {
621  // Branches are assumed to be predicted.
622  return 0;
623  }
624 
625  unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
626  const Instruction *I) {
627  const TargetLoweringBase *TLI = getTLI();
628  int ISD = TLI->InstructionOpcodeToISD(Opcode);
629  assert(ISD && "Invalid opcode");
630 
631  // Selects on vectors are actually vector selects.
632  if (ISD == ISD::SELECT) {
633  assert(CondTy && "CondTy must exist");
634  if (CondTy->isVectorTy())
635  ISD = ISD::VSELECT;
636  }
637  std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
638 
639  if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
640  !TLI->isOperationExpand(ISD, LT.second)) {
641  // The operation is legal. Assume it costs 1. Multiply
642  // by the type-legalization overhead.
643  return LT.first * 1;
644  }
645 
646  // Otherwise, assume that the cast is scalarized.
647  // TODO: If one of the types get legalized by splitting, handle this
648  // similarly to what getCastInstrCost() does.
649  if (ValTy->isVectorTy()) {
650  unsigned Num = ValTy->getVectorNumElements();
651  if (CondTy)
652  CondTy = CondTy->getScalarType();
653  unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
654  Opcode, ValTy->getScalarType(), CondTy, I);
655 
656  // Return the cost of multiple scalar invocation plus the cost of
657  // inserting and extracting the values.
658  return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
659  }
660 
661  // Unknown scalar opcode.
662  return 1;
663  }
664 
665  unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
666  std::pair<unsigned, MVT> LT =
667  getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
668 
669  return LT.first;
670  }
671 
672  unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
673  unsigned AddressSpace, const Instruction *I = nullptr) {
674  assert(!Src->isVoidTy() && "Invalid type");
675  std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
676 
677  // Assuming that all loads of legal types cost 1.
678  unsigned Cost = LT.first;
679 
680  if (Src->isVectorTy() &&
681  Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
682  // This is a vector load that legalizes to a larger type than the vector
683  // itself. Unless the corresponding extending load or truncating store is
684  // legal, then this will scalarize.
686  EVT MemVT = getTLI()->getValueType(DL, Src);
687  if (Opcode == Instruction::Store)
688  LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
689  else
690  LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
691 
692  if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
693  // This is a vector load/store for some illegal type that is scalarized.
694  // We must account for the cost of building or decomposing the vector.
695  Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
696  Opcode == Instruction::Store);
697  }
698  }
699 
700  return Cost;
701  }
702 
703  unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
704  unsigned Factor,
705  ArrayRef<unsigned> Indices,
706  unsigned Alignment,
707  unsigned AddressSpace) {
708  VectorType *VT = dyn_cast<VectorType>(VecTy);
709  assert(VT && "Expect a vector type for interleaved memory op");
710 
711  unsigned NumElts = VT->getNumElements();
712  assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
713 
714  unsigned NumSubElts = NumElts / Factor;
715  VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
716 
717  // Firstly, the cost of load/store operation.
718  unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
719  Opcode, VecTy, Alignment, AddressSpace);
720 
721  // Legalize the vector type, and get the legalized and unlegalized type
722  // sizes.
723  MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
724  unsigned VecTySize =
725  static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
726  unsigned VecTyLTSize = VecTyLT.getStoreSize();
727 
728  // Return the ceiling of dividing A by B.
729  auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
730 
731  // Scale the cost of the memory operation by the fraction of legalized
732  // instructions that will actually be used. We shouldn't account for the
733  // cost of dead instructions since they will be removed.
734  //
735  // E.g., An interleaved load of factor 8:
736  // %vec = load <16 x i64>, <16 x i64>* %ptr
737  // %v0 = shufflevector %vec, undef, <0, 8>
738  //
739  // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
740  // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
741  // type). The other loads are unused.
742  //
743  // We only scale the cost of loads since interleaved store groups aren't
744  // allowed to have gaps.
745  if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
746 
747  // The number of loads of a legal type it will take to represent a load
748  // of the unlegalized vector type.
749  unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
750 
751  // The number of elements of the unlegalized type that correspond to a
752  // single legal instruction.
753  unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
754 
755  // Determine which legal instructions will be used.
756  BitVector UsedInsts(NumLegalInsts, false);
757  for (unsigned Index : Indices)
758  for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
759  UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
760 
761  // Scale the cost of the load by the fraction of legal instructions that
762  // will be used.
763  Cost *= UsedInsts.count() / NumLegalInsts;
764  }
765 
766  // Then plus the cost of interleave operation.
767  if (Opcode == Instruction::Load) {
768  // The interleave cost is similar to extract sub vectors' elements
769  // from the wide vector, and insert them into sub vectors.
770  //
771  // E.g. An interleaved load of factor 2 (with one member of index 0):
772  // %vec = load <8 x i32>, <8 x i32>* %ptr
773  // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
774  // The cost is estimated as extract elements at 0, 2, 4, 6 from the
775  // <8 x i32> vector and insert them into a <4 x i32> vector.
776 
777  assert(Indices.size() <= Factor &&
778  "Interleaved memory op has too many members");
779 
780  for (unsigned Index : Indices) {
781  assert(Index < Factor && "Invalid index for interleaved memory op");
782 
783  // Extract elements from loaded vector for each sub vector.
784  for (unsigned i = 0; i < NumSubElts; i++)
785  Cost += static_cast<T *>(this)->getVectorInstrCost(
786  Instruction::ExtractElement, VT, Index + i * Factor);
787  }
788 
789  unsigned InsSubCost = 0;
790  for (unsigned i = 0; i < NumSubElts; i++)
791  InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
792  Instruction::InsertElement, SubVT, i);
793 
794  Cost += Indices.size() * InsSubCost;
795  } else {
796  // The interleave cost is extract all elements from sub vectors, and
797  // insert them into the wide vector.
798  //
799  // E.g. An interleaved store of factor 2:
800  // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
801  // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
802  // The cost is estimated as extract all elements from both <4 x i32>
803  // vectors and insert into the <8 x i32> vector.
804 
805  unsigned ExtSubCost = 0;
806  for (unsigned i = 0; i < NumSubElts; i++)
807  ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
808  Instruction::ExtractElement, SubVT, i);
809  Cost += ExtSubCost * Factor;
810 
811  for (unsigned i = 0; i < NumElts; i++)
812  Cost += static_cast<T *>(this)
813  ->getVectorInstrCost(Instruction::InsertElement, VT, i);
814  }
815 
816  return Cost;
817  }
818 
819  /// Get intrinsic cost based on arguments.
822  unsigned VF = 1) {
823  unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
824  assert ((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type");
825 
826  switch (IID) {
827  default: {
828  // Assume that we need to scalarize this intrinsic.
830  for (Value *Op : Args) {
831  Type *OpTy = Op->getType();
832  assert (VF == 1 || !OpTy->isVectorTy());
833  Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
834  }
835 
836  if (VF > 1 && !RetTy->isVoidTy())
837  RetTy = VectorType::get(RetTy, VF);
838 
839  // Compute the scalarization overhead based on Args for a vector
840  // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
841  // CostModel will pass a vector RetTy and VF is 1.
842  unsigned ScalarizationCost = UINT_MAX;
843  if (RetVF > 1 || VF > 1) {
844  ScalarizationCost = 0;
845  if (!RetTy->isVoidTy())
846  ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
847  ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
848  }
849 
850  return static_cast<T *>(this)->
851  getIntrinsicInstrCost(IID, RetTy, Types, FMF, ScalarizationCost);
852  }
853  case Intrinsic::masked_scatter: {
854  assert (VF == 1 && "Can't vectorize types here.");
855  Value *Mask = Args[3];
856  bool VarMask = !isa<Constant>(Mask);
857  unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
858  return
859  static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Store,
860  Args[0]->getType(),
861  Args[1], VarMask,
862  Alignment);
863  }
864  case Intrinsic::masked_gather: {
865  assert (VF == 1 && "Can't vectorize types here.");
866  Value *Mask = Args[2];
867  bool VarMask = !isa<Constant>(Mask);
868  unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
869  return
870  static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Load,
871  RetTy, Args[0], VarMask,
872  Alignment);
873  }
874  }
875  }
876 
877  /// Get intrinsic cost based on argument types.
878  /// If ScalarizationCostPassed is UINT_MAX, the cost of scalarizing the
879  /// arguments and the return value will be computed based on types.
882  unsigned ScalarizationCostPassed = UINT_MAX) {
884  unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
885  switch (IID) {
886  default: {
887  // Assume that we need to scalarize this intrinsic.
888  unsigned ScalarizationCost = ScalarizationCostPassed;
889  unsigned ScalarCalls = 1;
890  Type *ScalarRetTy = RetTy;
891  if (RetTy->isVectorTy()) {
892  if (ScalarizationCostPassed == UINT_MAX)
893  ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
894  ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
895  ScalarRetTy = RetTy->getScalarType();
896  }
897  SmallVector<Type *, 4> ScalarTys;
898  for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
899  Type *Ty = Tys[i];
900  if (Ty->isVectorTy()) {
901  if (ScalarizationCostPassed == UINT_MAX)
902  ScalarizationCost += getScalarizationOverhead(Ty, false, true);
903  ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
904  Ty = Ty->getScalarType();
905  }
906  ScalarTys.push_back(Ty);
907  }
908  if (ScalarCalls == 1)
909  return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
910 
911  unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
912  IID, ScalarRetTy, ScalarTys, FMF);
913 
914  return ScalarCalls * ScalarCost + ScalarizationCost;
915  }
916  // Look for intrinsics that can be lowered directly or turned into a scalar
917  // intrinsic call.
918  case Intrinsic::sqrt:
919  ISDs.push_back(ISD::FSQRT);
920  break;
921  case Intrinsic::sin:
922  ISDs.push_back(ISD::FSIN);
923  break;
924  case Intrinsic::cos:
925  ISDs.push_back(ISD::FCOS);
926  break;
927  case Intrinsic::exp:
928  ISDs.push_back(ISD::FEXP);
929  break;
930  case Intrinsic::exp2:
931  ISDs.push_back(ISD::FEXP2);
932  break;
933  case Intrinsic::log:
934  ISDs.push_back(ISD::FLOG);
935  break;
936  case Intrinsic::log10:
937  ISDs.push_back(ISD::FLOG10);
938  break;
939  case Intrinsic::log2:
940  ISDs.push_back(ISD::FLOG2);
941  break;
942  case Intrinsic::fabs:
943  ISDs.push_back(ISD::FABS);
944  break;
945  case Intrinsic::minnum:
946  ISDs.push_back(ISD::FMINNUM);
947  if (FMF.noNaNs())
948  ISDs.push_back(ISD::FMINNAN);
949  break;
950  case Intrinsic::maxnum:
951  ISDs.push_back(ISD::FMAXNUM);
952  if (FMF.noNaNs())
953  ISDs.push_back(ISD::FMAXNAN);
954  break;
955  case Intrinsic::copysign:
957  break;
958  case Intrinsic::floor:
959  ISDs.push_back(ISD::FFLOOR);
960  break;
961  case Intrinsic::ceil:
962  ISDs.push_back(ISD::FCEIL);
963  break;
964  case Intrinsic::trunc:
965  ISDs.push_back(ISD::FTRUNC);
966  break;
967  case Intrinsic::nearbyint:
969  break;
970  case Intrinsic::rint:
971  ISDs.push_back(ISD::FRINT);
972  break;
973  case Intrinsic::round:
974  ISDs.push_back(ISD::FROUND);
975  break;
976  case Intrinsic::pow:
977  ISDs.push_back(ISD::FPOW);
978  break;
979  case Intrinsic::fma:
980  ISDs.push_back(ISD::FMA);
981  break;
982  case Intrinsic::fmuladd:
983  ISDs.push_back(ISD::FMA);
984  break;
985  // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
986  case Intrinsic::lifetime_start:
987  case Intrinsic::lifetime_end:
988  return 0;
989  case Intrinsic::masked_store:
990  return static_cast<T *>(this)
991  ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
992  case Intrinsic::masked_load:
993  return static_cast<T *>(this)
995  case Intrinsic::ctpop:
996  ISDs.push_back(ISD::CTPOP);
997  // In case of legalization use TCC_Expensive. This is cheaper than a
998  // library call but still not a cheap instruction.
999  SingleCallCost = TargetTransformInfo::TCC_Expensive;
1000  break;
1001  // FIXME: ctlz, cttz, ...
1002  }
1003 
1004  const TargetLoweringBase *TLI = getTLI();
1005  std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
1006 
1007  SmallVector<unsigned, 2> LegalCost;
1008  SmallVector<unsigned, 2> CustomCost;
1009  for (unsigned ISD : ISDs) {
1010  if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
1011  if (IID == Intrinsic::fabs && TLI->isFAbsFree(LT.second)) {
1012  return 0;
1013  }
1014 
1015  // The operation is legal. Assume it costs 1.
1016  // If the type is split to multiple registers, assume that there is some
1017  // overhead to this.
1018  // TODO: Once we have extract/insert subvector cost we need to use them.
1019  if (LT.first > 1)
1020  LegalCost.push_back(LT.first * 2);
1021  else
1022  LegalCost.push_back(LT.first * 1);
1023  } else if (!TLI->isOperationExpand(ISD, LT.second)) {
1024  // If the operation is custom lowered then assume
1025  // that the code is twice as expensive.
1026  CustomCost.push_back(LT.first * 2);
1027  }
1028  }
1029 
1030  auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
1031  if (MinLegalCostI != LegalCost.end())
1032  return *MinLegalCostI;
1033 
1034  auto MinCustomCostI = std::min_element(CustomCost.begin(), CustomCost.end());
1035  if (MinCustomCostI != CustomCost.end())
1036  return *MinCustomCostI;
1037 
1038  // If we can't lower fmuladd into an FMA estimate the cost as a floating
1039  // point mul followed by an add.
1040  if (IID == Intrinsic::fmuladd)
1041  return static_cast<T *>(this)
1042  ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
1043  static_cast<T *>(this)
1044  ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
1045 
1046  // Else, assume that we need to scalarize this intrinsic. For math builtins
1047  // this will emit a costly libcall, adding call overhead and spills. Make it
1048  // very expensive.
1049  if (RetTy->isVectorTy()) {
1050  unsigned ScalarizationCost = ((ScalarizationCostPassed != UINT_MAX) ?
1051  ScalarizationCostPassed : getScalarizationOverhead(RetTy, true, false));
1052  unsigned ScalarCalls = RetTy->getVectorNumElements();
1053  SmallVector<Type *, 4> ScalarTys;
1054  for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1055  Type *Ty = Tys[i];
1056  if (Ty->isVectorTy())
1057  Ty = Ty->getScalarType();
1058  ScalarTys.push_back(Ty);
1059  }
1060  unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
1061  IID, RetTy->getScalarType(), ScalarTys, FMF);
1062  for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1063  if (Tys[i]->isVectorTy()) {
1064  if (ScalarizationCostPassed == UINT_MAX)
1065  ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
1066  ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
1067  }
1068  }
1069 
1070  return ScalarCalls * ScalarCost + ScalarizationCost;
1071  }
1072 
1073  // This is going to be turned into a library call, make it expensive.
1074  return SingleCallCost;
1075  }
1076 
1077  /// \brief Compute a cost of the given call instruction.
1078  ///
1079  /// Compute the cost of calling function F with return type RetTy and
1080  /// argument types Tys. F might be nullptr, in this case the cost of an
1081  /// arbitrary call with the specified signature will be returned.
1082  /// This is used, for instance, when we estimate call of a vector
1083  /// counterpart of the given function.
1084  /// \param F Called function, might be nullptr.
1085  /// \param RetTy Return value types.
1086  /// \param Tys Argument types.
1087  /// \returns The cost of Call instruction.
1089  return 10;
1090  }
1091 
1092  unsigned getNumberOfParts(Type *Tp) {
1093  std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
1094  return LT.first;
1095  }
1096 
1098  const SCEV *) {
1099  return 0;
1100  }
1101 
1102  /// Try to calculate arithmetic and shuffle op costs for reduction operations.
1103  /// We're assuming that reduction operation are performing the following way:
1104  /// 1. Non-pairwise reduction
1105  /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1106  /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
1107  /// \----------------v-------------/ \----------v------------/
1108  /// n/2 elements n/2 elements
1109  /// %red1 = op <n x t> %val, <n x t> val1
1110  /// After this operation we have a vector %red1 where only the first n/2
1111  /// elements are meaningful, the second n/2 elements are undefined and can be
1112  /// dropped. All other operations are actually working with the vector of
1113  /// length n/2, not n, though the real vector length is still n.
1114  /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
1115  /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
1116  /// \----------------v-------------/ \----------v------------/
1117  /// n/4 elements 3*n/4 elements
1118  /// %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
1119  /// length n/2, the resulting vector has length n/4 etc.
1120  /// 2. Pairwise reduction:
1121  /// Everything is the same except for an additional shuffle operation which
1122  /// is used to produce operands for pairwise kind of reductions.
1123  /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1124  /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
1125  /// \-------------v----------/ \----------v------------/
1126  /// n/2 elements n/2 elements
1127  /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
1128  /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
1129  /// \-------------v----------/ \----------v------------/
1130  /// n/2 elements n/2 elements
1131  /// %red1 = op <n x t> %val1, <n x t> val2
1132  /// Again, the operation is performed on <n x t> vector, but the resulting
1133  /// vector %red1 is <n/2 x t> vector.
1134  ///
1135  /// The cost model should take into account that the actual length of the
1136  /// vector is reduced on each iteration.
1137  unsigned getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwise) {
1138  assert(Ty->isVectorTy() && "Expect a vector type");
1139  Type *ScalarTy = Ty->getVectorElementType();
1140  unsigned NumVecElts = Ty->getVectorNumElements();
1141  unsigned NumReduxLevels = Log2_32(NumVecElts);
1142  unsigned ArithCost = 0;
1143  unsigned ShuffleCost = 0;
1144  auto *ConcreteTTI = static_cast<T *>(this);
1145  std::pair<unsigned, MVT> LT =
1146  ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1147  unsigned LongVectorCount = 0;
1148  unsigned MVTLen =
1149  LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1150  while (NumVecElts > MVTLen) {
1151  NumVecElts /= 2;
1152  // Assume the pairwise shuffles add a cost.
1153  ShuffleCost += (IsPairwise + 1) *
1154  ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1155  NumVecElts, Ty);
1156  ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1157  Ty = VectorType::get(ScalarTy, NumVecElts);
1158  ++LongVectorCount;
1159  }
1160  // The minimal length of the vector is limited by the real length of vector
1161  // operations performed on the current platform. That's why several final
1162  // reduction opertions are perfomed on the vectors with the same
1163  // architecture-dependent length.
1164  ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1165  ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1166  NumVecElts, Ty);
1167  ArithCost += (NumReduxLevels - LongVectorCount) *
1168  ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1169  return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
1170  }
1171 
1172  unsigned getVectorSplitCost() { return 1; }
1173 
1174  /// @}
1175 };
1176 
1177 /// \brief Concrete BasicTTIImpl that can be used if no further customization
1178 /// is needed.
1179 class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
1182 
1183  const TargetSubtargetInfo *ST;
1184  const TargetLoweringBase *TLI;
1185 
1186  const TargetSubtargetInfo *getST() const { return ST; }
1187  const TargetLoweringBase *getTLI() const { return TLI; }
1188 
1189 public:
1190  explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);
1191 };
1192 
1193 }
1194 
1195 #endif
MachineLoop * L
Base class for use as a mix-in that aids implementing a TargetTransformInfo-compatible class...
bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps, const APInt &Low, const APInt &High, const DataLayout &DL) const
Return true if lowering to a bit test is suitable for a set of case clusters which contains NumDests ...
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
Definition: ISDOpcodes.h:568
BitVector & set()
Definition: BitVector.h:398
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg If BaseGV is null...
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< Value * > Args, FastMathFlags FMF, unsigned VF=1)
Get intrinsic cost based on arguments.
Definition: BasicTTIImpl.h:820
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
LLVMContext & Context
unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr, bool VariableMask, unsigned Alignment)
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases, uint64_t Range) const
Return true if lowering to a jump table is suitable for a set of case clusters which may contain NumC...
unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract)
Estimate the overhead of scalarizing an instruction.
Definition: BasicTTIImpl.h:368
The main scalar evolution driver.
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold, but used for partial/runtime unrolling (set to UINT_MAX to disable).
unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< Type * > ParamTys)
Definition: BasicTTIImpl.h:175
static uint64_t round(uint64_t Acc, uint64_t Input)
Definition: xxhash.cpp:57
unsigned PartialThreshold
The cost threshold for the unrolled loop, like Threshold, but used for partial/runtime unrolling (set...
CaseIt case_begin()
Returns a read/write iterator that points to the first case in the SwitchInst.
unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy)
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
virtual bool isLegalICmpImmediate(int64_t) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:301
BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
Definition: BasicTTIImpl.h:77
int getExtCost(const Instruction *I, const Value *Src)
Definition: BasicTTIImpl.h:158
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
unsigned getOperandsScalarizationOverhead(ArrayRef< const Value * > Args, unsigned VF)
Estimate the overhead of scalarizing an instructions unique non-constant operands.
Definition: BasicTTIImpl.h:387
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, unsigned Align=1, bool *=nullptr) const
Determine if the target supports unaligned memory accesses.
An instruction for reading from memory.
Definition: Instructions.h:164
int getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands)
Definition: BasicTTIImpl.h:153
bool isProfitableToHoist(Instruction *I)
Definition: BasicTTIImpl.h:144
unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys)
Compute a cost of the given call instruction.
Base class which can be used to help build a TTI implementation.
Definition: BasicTTIImpl.h:40
unsigned getMaxInterleaveFactor(unsigned VF)
Definition: BasicTTIImpl.h:427
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
This file provides helpers for the implementation of a TargetTransformInfo-conforming class...
CRTP base class for use as a mix-in that aids implementing a TargetTransformInfo-compatible class...
unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *, const SCEV *)
virtual bool isLegalAddImmediate(int64_t) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index)
Definition: BasicTTIImpl.h:612
int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace)
Definition: BasicTTIImpl.h:126
int getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands)
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
unsigned getRegisterBitWidth(bool Vector) const
Definition: BasicTTIImpl.h:364
unsigned getJumpBufSize() const
Returns the target's jmp_buf size in bytes (if never set, the default is 200)
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
unsigned getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Type * getVectorElementType() const
Definition: Type.h:368
BasicTTIImpl(const TargetMachine *ST, const Function &F)
int InstructionOpcodeToISD(unsigned Opcode) const
Get the ISD node that corresponds to the Instruction class opcode.
unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, unsigned Alignment, unsigned AddressSpace)
Definition: BasicTTIImpl.h:703
unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, const Instruction *I)
Definition: BasicTTIImpl.h:625
Choose alternate elements from vector.
unsigned getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwise)
Try to calculate arithmetic and shuffle op costs for reduction operations.
#define F(x, y, z)
Definition: MD5.cpp:55
unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, const Instruction *I=nullptr)
Definition: BasicTTIImpl.h:485
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition: ISDOpcodes.h:397
bool sgt(const APInt &RHS) const
Signed greather than comparison.
Definition: APInt.h:1253
LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const
Return how this store with truncation should be treated: either it is legal, needs to be promoted to ...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
bool isOperationLegalOrPromote(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal using promotion...
Type * getElementType() const
Definition: DerivedTypes.h:360
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return how this load with extension should be treated: either it is legal, needs to be promoted to a ...
unsigned getFPOpCost(Type *Ty)
Definition: BasicTTIImpl.h:265
bool isTruncateFree(Type *Ty1, Type *Ty2)
Definition: BasicTTIImpl.h:140
ExtractSubvector Index indicates start offset.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP)
Definition: BasicTTIImpl.h:292
size_type count() const
count - Returns the number of bits which are set.
Definition: BitVector.h:173
Machine Value Type.
Concrete BasicTTIImpl that can be used if no further customization is needed.
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
size_type size() const
Definition: SmallPtrSet.h:93
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:227
bool isOperationLegalOrCustom(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool areJTsAllowed(const Function *Fn) const
Return true if lowering to a jump table is allowed.
#define A
Definition: LargeTest.cpp:12
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:372
Expected to fold away in lowering.
uint64_t getNumElements() const
Definition: DerivedTypes.h:359
Merge elements from two source vectors into one with any shuffle mask.
bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace)
Definition: BasicTTIImpl.h:111
unsigned getNumberOfParts(Type *Tp)
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS=0) const
Return the cost of the scaling factor used in the addressing mode represented by AM for this target...
Extended Value Type.
Definition: ValueTypes.h:34
static wasm::ValType getType(const TargetRegisterClass *RC)
bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset)
Definition: BasicTTIImpl.h:136
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:185
bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return true if the specified load with extension is legal on this target.
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE maxNum semantics.
Definition: APFloat.h:1223
bool isLegalAddImmediate(int64_t imm)
Definition: BasicTTIImpl.h:103
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
OperandValueProperties
Additional properties of an operand's values.
unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< Type * > Tys, FastMathFlags FMF, unsigned ScalarizationCostPassed=UINT_MAX)
Get intrinsic cost based on argument types.
Definition: BasicTTIImpl.h:880
unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< const Value * > Arguments)
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
unsigned getCFInstrCost(unsigned Opcode)
Definition: BasicTTIImpl.h:620
unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index, Type *SubTp)
Definition: BasicTTIImpl.h:476
unsigned getNumberOfRegisters(bool Vector)
Definition: BasicTTIImpl.h:362
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
#define E
Definition: LargeTest.cpp:27
#define B
Definition: LargeTest.cpp:24
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty, 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 * >())
Definition: BasicTTIImpl.h:429
iterator end()
Definition: BasicBlock.h:254
unsigned getVectorSplitCost()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
AddressSpace
Definition: NVPTXBaseInfo.h:22
cl::opt< unsigned > PartialUnrollingThreshold
const size_t N
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
virtual bool isProfitableToHoist(Instruction *I) const
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:531
unsigned getScalarizationOverhead(Type *VecTy, ArrayRef< const Value * > Args)
Definition: BasicTTIImpl.h:410
Class to represent vector types.
Definition: DerivedTypes.h:393
Class for arbitrary precision integers.
Definition: APInt.h:69
Select(COND, TRUEVAL, FALSEVAL).
Definition: ISDOpcodes.h:388
std::pair< int, MVT > getTypeLegalizationCost(const DataLayout &DL, Type *Ty) const
Estimate the cost of type-legalization and the legalized type.
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:462
std::vector< BlockT * >::const_iterator block_iterator
Definition: LoopInfo.h:141
unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment, unsigned AddressSpace, const Instruction *I=nullptr)
Definition: BasicTTIImpl.h:672
unsigned LoopMicroOpBufferSize
Definition: MCSchedule.h:164
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition: ISDOpcodes.h:286
bool isAlwaysUniform(const Value *V)
Definition: BasicTTIImpl.h:96
FMINNAN/FMAXNAN - Behave identically to FMINNUM/FMAXNUM, except that when a single input is NaN...
Definition: ISDOpcodes.h:571
unsigned getFlatAddressSpace()
Definition: BasicTTIImpl.h:98
const DataLayout & getDataLayout() const
llvm_unreachable("Unknown RegBank!")
TargetSubtargetInfo - Generic base class for all target subtargets.
bool isLSRCostLess(TTI::LSRCost &C1, TTI::LSRCost &C2)
block_iterator block_end() const
Definition: LoopInfo.h:143
unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment, unsigned AddressSpace)
BR_JT - Jumptable branch.
Definition: ISDOpcodes.h:604
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< const Value * > Arguments)
Definition: BasicTTIImpl.h:170
unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy)
Definition: BasicTTIImpl.h:271
This class represents an analyzed expression in the program.
bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth, unsigned AddressSpace, unsigned Alignment, bool *Fast) const
Definition: BasicTTIImpl.h:85
unsigned getJumpBufAlignment() const
Returns the target's jmp_buf alignment in bytes (if never set, the default is 0)
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:360
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
Parameters that control the generic loop unrolling transformation.
unsigned getJumpBufAlignment()
Definition: BasicTTIImpl.h:248
unsigned OptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size (set to UINT_MAX to disable)...
Establish a view to a call site for examination.
Definition: CallSite.h:687
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:346
unsigned getInliningThresholdMultiplier()
Definition: BasicTTIImpl.h:290
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:43
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index)
Definition: BasicTTIImpl.h:665
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:388
virtual bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) const
static EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
Definition: ValueTypes.cpp:311
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2)
Definition: BasicTTIImpl.h:122
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JumpTableSize)
Definition: BasicTTIImpl.h:192
const unsigned Kind
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
Multiway switch.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
The cost of a typical 'add' instruction.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
Definition: CallSite.h:104
bool isSourceOfDivergence(const Value *V)
Definition: BasicTTIImpl.h:94
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
LLVM Value Representation.
Definition: Value.h:73
FMA - Perform a * b + c with no intermediate rounding step.
Definition: ISDOpcodes.h:276
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:593
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:81
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:56
bool isTypeLegal(Type *Ty)
Definition: BasicTTIImpl.h:148
block_iterator block_begin() const
Definition: LoopInfo.h:142
bool UpperBound
Allow using trip count upper bound to unroll loops.
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:160
OperandValueKind
Additional information about an operand's possible values.
bool haveFastSqrt(Type *Ty)
Definition: BasicTTIImpl.h:258
int * Ptr
bool isLegalICmpImmediate(int64_t imm)
Definition: BasicTTIImpl.h:107
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition: ValueTypes.h:64
The cost of a 'div' instruction on x86.
const BasicBlock * getParent() const
Definition: Instruction.h:66
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE minNum semantics.
Definition: APFloat.h:1212
bool noNaNs() const
Flag queries.
Definition: Operator.h:189
This file describes how to lower LLVM code to machine code.
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:141
ShuffleKind
The various kinds of shuffle patterns for vector queries.
Shuffle elements of single source vector with any shuffle mask.
BRIND - Indirect branch.
Definition: ISDOpcodes.h:600
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1183