1 //===- BasicTTIImpl.h -------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file provides a helper that implements much of the TTI interface in
11 /// terms of the target-independent code generator and TargetLowering
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_BASICTTIIMPL_H
17 #define LLVM_CODEGEN_BASICTTIIMPL_H
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/TargetTransformInfoImpl.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetSubtargetInfo.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
28 extern cl::opt<unsigned> PartialUnrollingThreshold;
30 /// \brief Base class which can be used to help build a TTI implementation.
32 /// This class provides as much implementation of the TTI interface as is
33 /// possible using the target independent parts of the code generator.
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.
40 class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
42 typedef TargetTransformInfoImplCRTPBase<T> BaseT;
43 typedef TargetTransformInfo TTI;
45 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
46 /// are set if the result needs to be inserted and/or extracted from vectors.
47 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
48 assert(Ty->isVectorTy() && "Can only scalarize vectors");
51 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
53 Cost += static_cast<T *>(this)
54 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
56 Cost += static_cast<T *>(this)
57 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
63 /// Estimate a cost of shuffle as a sequence of extract and insert
65 unsigned getPermuteShuffleOverhead(Type *Ty) {
66 assert(Ty->isVectorTy() && "Can only shuffle vectors");
68 // Shuffle cost is equal to the cost of extracting element from its argument
69 // plus the cost of inserting them onto the result vector.
71 // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
72 // index 0 of first vector, index 1 of second vector,index 2 of first
73 // vector and finally index 3 of second vector and insert them at index
74 // <0,1,2,3> of result vector.
75 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
76 Cost += static_cast<T *>(this)
77 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
78 Cost += static_cast<T *>(this)
79 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
84 /// \brief Local query method delegates up to T which *must* implement this!
85 const TargetSubtargetInfo *getST() const {
86 return static_cast<const T *>(this)->getST();
89 /// \brief Local query method delegates up to T which *must* implement this!
90 const TargetLoweringBase *getTLI() const {
91 return static_cast<const T *>(this)->getTLI();
95 explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
98 using TargetTransformInfoImplBase::DL;
101 /// \name Scalar TTI Implementations
103 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
104 unsigned BitWidth, unsigned AddressSpace,
105 unsigned Alignment, bool *Fast) const {
106 EVT E = EVT::getIntegerVT(Context, BitWidth);
107 return getTLI()->allowsMisalignedMemoryAccesses(E, AddressSpace, Alignment, Fast);
110 bool hasBranchDivergence() { return false; }
112 bool isSourceOfDivergence(const Value *V) { return false; }
114 bool isLegalAddImmediate(int64_t imm) {
115 return getTLI()->isLegalAddImmediate(imm);
118 bool isLegalICmpImmediate(int64_t imm) {
119 return getTLI()->isLegalICmpImmediate(imm);
122 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
123 bool HasBaseReg, int64_t Scale,
124 unsigned AddrSpace) {
125 TargetLoweringBase::AddrMode AM;
127 AM.BaseOffs = BaseOffset;
128 AM.HasBaseReg = HasBaseReg;
130 return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace);
133 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
134 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
135 TargetLoweringBase::AddrMode AM;
137 AM.BaseOffs = BaseOffset;
138 AM.HasBaseReg = HasBaseReg;
140 return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
143 bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) {
144 return getTLI()->isFoldableMemAccessOffset(I, Offset);
147 bool isTruncateFree(Type *Ty1, Type *Ty2) {
148 return getTLI()->isTruncateFree(Ty1, Ty2);
151 bool isProfitableToHoist(Instruction *I) {
152 return getTLI()->isProfitableToHoist(I);
155 bool isTypeLegal(Type *Ty) {
156 EVT VT = getTLI()->getValueType(DL, Ty);
157 return getTLI()->isTypeLegal(VT);
160 int getGEPCost(Type *PointeeType, const Value *Ptr,
161 ArrayRef<const Value *> Operands) {
162 return BaseT::getGEPCost(PointeeType, Ptr, Operands);
165 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
166 ArrayRef<const Value *> Arguments) {
167 return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
170 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
171 ArrayRef<Type *> ParamTys) {
172 if (IID == Intrinsic::cttz) {
173 if (getTLI()->isCheapToSpeculateCttz())
174 return TargetTransformInfo::TCC_Basic;
175 return TargetTransformInfo::TCC_Expensive;
178 if (IID == Intrinsic::ctlz) {
179 if (getTLI()->isCheapToSpeculateCtlz())
180 return TargetTransformInfo::TCC_Basic;
181 return TargetTransformInfo::TCC_Expensive;
184 return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
187 unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
189 unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
191 bool shouldBuildLookupTables() {
192 const TargetLoweringBase *TLI = getTLI();
193 return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
194 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
197 bool haveFastSqrt(Type *Ty) {
198 const TargetLoweringBase *TLI = getTLI();
199 EVT VT = TLI->getValueType(DL, Ty);
200 return TLI->isTypeLegal(VT) &&
201 TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
204 unsigned getFPOpCost(Type *Ty) {
205 // By default, FP instructions are no more expensive since they are
206 // implemented in HW. Target specific TTI can override this.
207 return TargetTransformInfo::TCC_Basic;
210 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
211 const TargetLoweringBase *TLI = getTLI();
214 case Instruction::Trunc: {
215 if (TLI->isTruncateFree(OpTy, Ty))
216 return TargetTransformInfo::TCC_Free;
217 return TargetTransformInfo::TCC_Basic;
219 case Instruction::ZExt: {
220 if (TLI->isZExtFree(OpTy, Ty))
221 return TargetTransformInfo::TCC_Free;
222 return TargetTransformInfo::TCC_Basic;
226 return BaseT::getOperationCost(Opcode, Ty, OpTy);
229 unsigned getInliningThresholdMultiplier() { return 1; }
231 void getUnrollingPreferences(Loop *L, TTI::UnrollingPreferences &UP) {
232 // This unrolling functionality is target independent, but to provide some
233 // motivation for its intended use, for x86:
235 // According to the Intel 64 and IA-32 Architectures Optimization Reference
236 // Manual, Intel Core models and later have a loop stream detector (and
237 // associated uop queue) that can benefit from partial unrolling.
238 // The relevant requirements are:
239 // - The loop must have no more than 4 (8 for Nehalem and later) branches
240 // taken, and none of them may be calls.
241 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
243 // According to the Software Optimization Guide for AMD Family 15h
244 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
245 // and loop buffer which can benefit from partial unrolling.
246 // The relevant requirements are:
247 // - The loop must have fewer than 16 branches
248 // - The loop must have less than 40 uops in all executed loop branches
250 // The number of taken branches in a loop is hard to estimate here, and
251 // benchmarking has revealed that it is better not to be conservative when
252 // estimating the branch count. As a result, we'll ignore the branch limits
253 // until someone finds a case where it matters in practice.
256 const TargetSubtargetInfo *ST = getST();
257 if (PartialUnrollingThreshold.getNumOccurrences() > 0)
258 MaxOps = PartialUnrollingThreshold;
259 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
260 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
264 // Scan the loop: don't unroll loops with calls.
265 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
269 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
270 if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
271 ImmutableCallSite CS(&*J);
272 if (const Function *F = CS.getCalledFunction()) {
273 if (!static_cast<T *>(this)->isLoweredToCall(F))
281 // Enable runtime and partial unrolling up to the specified size.
282 // Enable using trip count upper bound to unroll loops.
283 UP.Partial = UP.Runtime = UP.UpperBound = true;
284 UP.PartialThreshold = MaxOps;
286 // Avoid unrolling when optimizing for size.
287 UP.OptSizeThreshold = 0;
288 UP.PartialOptSizeThreshold = 0;
290 // Set number of instructions optimized when "back edge"
291 // becomes "fall through" to default value of 2.
297 /// \name Vector TTI Implementations
300 unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
302 unsigned getRegisterBitWidth(bool Vector) { return 32; }
304 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
306 unsigned getArithmeticInstrCost(
307 unsigned Opcode, Type *Ty,
308 TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
309 TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
310 TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
311 TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None) {
312 // Check if any of the operands are vector operands.
313 const TargetLoweringBase *TLI = getTLI();
314 int ISD = TLI->InstructionOpcodeToISD(Opcode);
315 assert(ISD && "Invalid opcode");
317 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
319 bool IsFloat = Ty->getScalarType()->isFloatingPointTy();
320 // Assume that floating point arithmetic operations cost twice as much as
321 // integer operations.
322 unsigned OpCost = (IsFloat ? 2 : 1);
324 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
325 // The operation is legal. Assume it costs 1.
326 // TODO: Once we have extract/insert subvector cost we need to use them.
327 return LT.first * OpCost;
330 if (!TLI->isOperationExpand(ISD, LT.second)) {
331 // If the operation is custom lowered, then assume that the code is twice
333 return LT.first * 2 * OpCost;
336 // Else, assume that we need to scalarize this op.
337 // TODO: If one of the types get legalized by splitting, handle this
338 // similarly to what getCastInstrCost() does.
339 if (Ty->isVectorTy()) {
340 unsigned Num = Ty->getVectorNumElements();
341 unsigned Cost = static_cast<T *>(this)
342 ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
343 // return the cost of multiple scalar invocation plus the cost of
345 // and extracting the values.
346 return getScalarizationOverhead(Ty, true, true) + Num * Cost;
349 // We don't know anything about this scalar instruction.
353 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
355 if (Kind == TTI::SK_Alternate || Kind == TTI::SK_PermuteTwoSrc ||
356 Kind == TTI::SK_PermuteSingleSrc) {
357 return getPermuteShuffleOverhead(Tp);
362 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) {
363 const TargetLoweringBase *TLI = getTLI();
364 int ISD = TLI->InstructionOpcodeToISD(Opcode);
365 assert(ISD && "Invalid opcode");
366 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
367 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
369 // Check for NOOP conversions.
370 if (SrcLT.first == DstLT.first &&
371 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
373 // Bitcast between types that are legalized to the same type are free.
374 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
378 if (Opcode == Instruction::Trunc &&
379 TLI->isTruncateFree(SrcLT.second, DstLT.second))
382 if (Opcode == Instruction::ZExt &&
383 TLI->isZExtFree(SrcLT.second, DstLT.second))
386 if (Opcode == Instruction::AddrSpaceCast &&
387 TLI->isNoopAddrSpaceCast(Src->getPointerAddressSpace(),
388 Dst->getPointerAddressSpace()))
391 // If the cast is marked as legal (or promote) then assume low cost.
392 if (SrcLT.first == DstLT.first &&
393 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
396 // Handle scalar conversions.
397 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
399 // Scalar bitcasts are usually free.
400 if (Opcode == Instruction::BitCast)
403 // Just check the op cost. If the operation is legal then assume it costs
405 if (!TLI->isOperationExpand(ISD, DstLT.second))
408 // Assume that illegal scalar instruction are expensive.
412 // Check vector-to-vector casts.
413 if (Dst->isVectorTy() && Src->isVectorTy()) {
415 // If the cast is between same-sized registers, then the check is simple.
416 if (SrcLT.first == DstLT.first &&
417 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
419 // Assume that Zext is done using AND.
420 if (Opcode == Instruction::ZExt)
423 // Assume that sext is done using SHL and SRA.
424 if (Opcode == Instruction::SExt)
427 // Just check the op cost. If the operation is legal then assume it
429 // 1 and multiply by the type-legalization overhead.
430 if (!TLI->isOperationExpand(ISD, DstLT.second))
431 return SrcLT.first * 1;
434 // If we are legalizing by splitting, query the concrete TTI for the cost
435 // of casting the original vector twice. We also need to factor int the
436 // cost of the split itself. Count that as 1, to be consistent with
437 // TLI->getTypeLegalizationCost().
438 if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
439 TargetLowering::TypeSplitVector) ||
440 (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
441 TargetLowering::TypeSplitVector)) {
442 Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
443 Dst->getVectorNumElements() / 2);
444 Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
445 Src->getVectorNumElements() / 2);
446 T *TTI = static_cast<T *>(this);
447 return TTI->getVectorSplitCost() +
448 (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc));
451 // In other cases where the source or destination are illegal, assume
452 // the operation will get scalarized.
453 unsigned Num = Dst->getVectorNumElements();
454 unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
455 Opcode, Dst->getScalarType(), Src->getScalarType());
457 // Return the cost of multiple scalar invocation plus the cost of
458 // inserting and extracting the values.
459 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
462 // We already handled vector-to-vector and scalar-to-scalar conversions.
464 // is where we handle bitcast between vectors and scalars. We need to assume
465 // that the conversion is scalarized in one way or another.
466 if (Opcode == Instruction::BitCast)
467 // Illegal bitcasts are done by storing and loading from a stack slot.
468 return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
470 (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
473 llvm_unreachable("Unhandled cast");
476 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
477 VectorType *VecTy, unsigned Index) {
478 return static_cast<T *>(this)->getVectorInstrCost(
479 Instruction::ExtractElement, VecTy, Index) +
480 static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
481 VecTy->getElementType());
484 unsigned getCFInstrCost(unsigned Opcode) {
485 // Branches are assumed to be predicted.
489 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
490 const TargetLoweringBase *TLI = getTLI();
491 int ISD = TLI->InstructionOpcodeToISD(Opcode);
492 assert(ISD && "Invalid opcode");
494 // Selects on vectors are actually vector selects.
495 if (ISD == ISD::SELECT) {
496 assert(CondTy && "CondTy must exist");
497 if (CondTy->isVectorTy())
500 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
502 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
503 !TLI->isOperationExpand(ISD, LT.second)) {
504 // The operation is legal. Assume it costs 1. Multiply
505 // by the type-legalization overhead.
509 // Otherwise, assume that the cast is scalarized.
510 // TODO: If one of the types get legalized by splitting, handle this
511 // similarly to what getCastInstrCost() does.
512 if (ValTy->isVectorTy()) {
513 unsigned Num = ValTy->getVectorNumElements();
515 CondTy = CondTy->getScalarType();
516 unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
517 Opcode, ValTy->getScalarType(), CondTy);
519 // Return the cost of multiple scalar invocation plus the cost of
520 // inserting and extracting the values.
521 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
524 // Unknown scalar opcode.
528 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
529 std::pair<unsigned, MVT> LT =
530 getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
535 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
536 unsigned AddressSpace) {
537 assert(!Src->isVoidTy() && "Invalid type");
538 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
540 // Assuming that all loads of legal types cost 1.
541 unsigned Cost = LT.first;
543 if (Src->isVectorTy() &&
544 Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
545 // This is a vector load that legalizes to a larger type than the vector
546 // itself. Unless the corresponding extending load or truncating store is
547 // legal, then this will scalarize.
548 TargetLowering::LegalizeAction LA = TargetLowering::Expand;
549 EVT MemVT = getTLI()->getValueType(DL, Src);
550 if (Opcode == Instruction::Store)
551 LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
553 LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
555 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
556 // This is a vector load/store for some illegal type that is scalarized.
557 // We must account for the cost of building or decomposing the vector.
558 Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
559 Opcode == Instruction::Store);
566 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
568 ArrayRef<unsigned> Indices,
570 unsigned AddressSpace) {
571 VectorType *VT = dyn_cast<VectorType>(VecTy);
572 assert(VT && "Expect a vector type for interleaved memory op");
574 unsigned NumElts = VT->getNumElements();
575 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
577 unsigned NumSubElts = NumElts / Factor;
578 VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
580 // Firstly, the cost of load/store operation.
581 unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
582 Opcode, VecTy, Alignment, AddressSpace);
584 // Legalize the vector type, and get the legalized and unlegalized type
586 MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
588 static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
589 unsigned VecTyLTSize = VecTyLT.getStoreSize();
591 // Return the ceiling of dividing A by B.
592 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
594 // Scale the cost of the memory operation by the fraction of legalized
595 // instructions that will actually be used. We shouldn't account for the
596 // cost of dead instructions since they will be removed.
598 // E.g., An interleaved load of factor 8:
599 // %vec = load <16 x i64>, <16 x i64>* %ptr
600 // %v0 = shufflevector %vec, undef, <0, 8>
602 // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
603 // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
604 // type). The other loads are unused.
606 // We only scale the cost of loads since interleaved store groups aren't
607 // allowed to have gaps.
608 if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
610 // The number of loads of a legal type it will take to represent a load
611 // of the unlegalized vector type.
612 unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
614 // The number of elements of the unlegalized type that correspond to a
615 // single legal instruction.
616 unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
618 // Determine which legal instructions will be used.
619 BitVector UsedInsts(NumLegalInsts, false);
620 for (unsigned Index : Indices)
621 for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
622 UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
624 // Scale the cost of the load by the fraction of legal instructions that
626 Cost *= UsedInsts.count() / NumLegalInsts;
629 // Then plus the cost of interleave operation.
630 if (Opcode == Instruction::Load) {
631 // The interleave cost is similar to extract sub vectors' elements
632 // from the wide vector, and insert them into sub vectors.
634 // E.g. An interleaved load of factor 2 (with one member of index 0):
635 // %vec = load <8 x i32>, <8 x i32>* %ptr
636 // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
637 // The cost is estimated as extract elements at 0, 2, 4, 6 from the
638 // <8 x i32> vector and insert them into a <4 x i32> vector.
640 assert(Indices.size() <= Factor &&
641 "Interleaved memory op has too many members");
643 for (unsigned Index : Indices) {
644 assert(Index < Factor && "Invalid index for interleaved memory op");
646 // Extract elements from loaded vector for each sub vector.
647 for (unsigned i = 0; i < NumSubElts; i++)
648 Cost += static_cast<T *>(this)->getVectorInstrCost(
649 Instruction::ExtractElement, VT, Index + i * Factor);
652 unsigned InsSubCost = 0;
653 for (unsigned i = 0; i < NumSubElts; i++)
654 InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
655 Instruction::InsertElement, SubVT, i);
657 Cost += Indices.size() * InsSubCost;
659 // The interleave cost is extract all elements from sub vectors, and
660 // insert them into the wide vector.
662 // E.g. An interleaved store of factor 2:
663 // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
664 // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
665 // The cost is estimated as extract all elements from both <4 x i32>
666 // vectors and insert into the <8 x i32> vector.
668 unsigned ExtSubCost = 0;
669 for (unsigned i = 0; i < NumSubElts; i++)
670 ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
671 Instruction::ExtractElement, SubVT, i);
672 Cost += ExtSubCost * Factor;
674 for (unsigned i = 0; i < NumElts; i++)
675 Cost += static_cast<T *>(this)
676 ->getVectorInstrCost(Instruction::InsertElement, VT, i);
682 /// Get intrinsic cost based on arguments
683 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
684 ArrayRef<Value *> Args, FastMathFlags FMF) {
687 SmallVector<Type *, 4> Types;
688 for (Value *Op : Args)
689 Types.push_back(Op->getType());
690 return static_cast<T *>(this)->getIntrinsicInstrCost(IID, RetTy, Types,
693 case Intrinsic::masked_scatter: {
694 Value *Mask = Args[3];
695 bool VarMask = !isa<Constant>(Mask);
696 unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
698 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Store,
703 case Intrinsic::masked_gather: {
704 Value *Mask = Args[2];
705 bool VarMask = !isa<Constant>(Mask);
706 unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
708 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Load,
709 RetTy, Args[0], VarMask,
715 /// Get intrinsic cost based on argument types
716 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
717 ArrayRef<Type *> Tys, FastMathFlags FMF) {
718 SmallVector<unsigned, 2> ISDs;
719 unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
722 // Assume that we need to scalarize this intrinsic.
723 unsigned ScalarizationCost = 0;
724 unsigned ScalarCalls = 1;
725 Type *ScalarRetTy = RetTy;
726 if (RetTy->isVectorTy()) {
727 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
728 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
729 ScalarRetTy = RetTy->getScalarType();
731 SmallVector<Type *, 4> ScalarTys;
732 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
734 if (Ty->isVectorTy()) {
735 ScalarizationCost += getScalarizationOverhead(Ty, false, true);
736 ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
737 Ty = Ty->getScalarType();
739 ScalarTys.push_back(Ty);
741 if (ScalarCalls == 1)
742 return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
744 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
745 IID, ScalarRetTy, ScalarTys, FMF);
747 return ScalarCalls * ScalarCost + ScalarizationCost;
749 // Look for intrinsics that can be lowered directly or turned into a scalar
751 case Intrinsic::sqrt:
752 ISDs.push_back(ISD::FSQRT);
755 ISDs.push_back(ISD::FSIN);
758 ISDs.push_back(ISD::FCOS);
761 ISDs.push_back(ISD::FEXP);
763 case Intrinsic::exp2:
764 ISDs.push_back(ISD::FEXP2);
767 ISDs.push_back(ISD::FLOG);
769 case Intrinsic::log10:
770 ISDs.push_back(ISD::FLOG10);
772 case Intrinsic::log2:
773 ISDs.push_back(ISD::FLOG2);
775 case Intrinsic::fabs:
776 ISDs.push_back(ISD::FABS);
778 case Intrinsic::minnum:
779 ISDs.push_back(ISD::FMINNUM);
781 ISDs.push_back(ISD::FMINNAN);
783 case Intrinsic::maxnum:
784 ISDs.push_back(ISD::FMAXNUM);
786 ISDs.push_back(ISD::FMAXNAN);
788 case Intrinsic::copysign:
789 ISDs.push_back(ISD::FCOPYSIGN);
791 case Intrinsic::floor:
792 ISDs.push_back(ISD::FFLOOR);
794 case Intrinsic::ceil:
795 ISDs.push_back(ISD::FCEIL);
797 case Intrinsic::trunc:
798 ISDs.push_back(ISD::FTRUNC);
800 case Intrinsic::nearbyint:
801 ISDs.push_back(ISD::FNEARBYINT);
803 case Intrinsic::rint:
804 ISDs.push_back(ISD::FRINT);
806 case Intrinsic::round:
807 ISDs.push_back(ISD::FROUND);
810 ISDs.push_back(ISD::FPOW);
813 ISDs.push_back(ISD::FMA);
815 case Intrinsic::fmuladd:
816 ISDs.push_back(ISD::FMA);
818 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
819 case Intrinsic::lifetime_start:
820 case Intrinsic::lifetime_end:
822 case Intrinsic::masked_store:
823 return static_cast<T *>(this)
824 ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
825 case Intrinsic::masked_load:
826 return static_cast<T *>(this)
827 ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
828 case Intrinsic::ctpop:
829 ISDs.push_back(ISD::CTPOP);
830 // In case of legalization use TCC_Expensive. This is cheaper than a
831 // library call but still not a cheap instruction.
832 SingleCallCost = TargetTransformInfo::TCC_Expensive;
834 // FIXME: ctlz, cttz, ...
837 const TargetLoweringBase *TLI = getTLI();
838 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
840 SmallVector<unsigned, 2> LegalCost;
841 SmallVector<unsigned, 2> CustomCost;
842 for (unsigned ISD : ISDs) {
843 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
844 if (IID == Intrinsic::fabs && TLI->isFAbsFree(LT.second)) {
848 // The operation is legal. Assume it costs 1.
849 // If the type is split to multiple registers, assume that there is some
851 // TODO: Once we have extract/insert subvector cost we need to use them.
853 LegalCost.push_back(LT.first * 2);
855 LegalCost.push_back(LT.first * 1);
856 } else if (!TLI->isOperationExpand(ISD, LT.second)) {
857 // If the operation is custom lowered then assume
858 // that the code is twice as expensive.
859 CustomCost.push_back(LT.first * 2);
863 auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
864 if (MinLegalCostI != LegalCost.end())
865 return *MinLegalCostI;
867 auto MinCustomCostI = std::min_element(CustomCost.begin(), CustomCost.end());
868 if (MinCustomCostI != CustomCost.end())
869 return *MinCustomCostI;
871 // If we can't lower fmuladd into an FMA estimate the cost as a floating
872 // point mul followed by an add.
873 if (IID == Intrinsic::fmuladd)
874 return static_cast<T *>(this)
875 ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
876 static_cast<T *>(this)
877 ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
879 // Else, assume that we need to scalarize this intrinsic. For math builtins
880 // this will emit a costly libcall, adding call overhead and spills. Make it
882 if (RetTy->isVectorTy()) {
883 unsigned ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
884 unsigned ScalarCalls = RetTy->getVectorNumElements();
885 SmallVector<Type *, 4> ScalarTys;
886 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
888 if (Ty->isVectorTy())
889 Ty = Ty->getScalarType();
890 ScalarTys.push_back(Ty);
892 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
893 IID, RetTy->getScalarType(), ScalarTys, FMF);
894 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
895 if (Tys[i]->isVectorTy()) {
896 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
897 ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
901 return ScalarCalls * ScalarCost + ScalarizationCost;
904 // This is going to be turned into a library call, make it expensive.
905 return SingleCallCost;
908 /// \brief Compute a cost of the given call instruction.
910 /// Compute the cost of calling function F with return type RetTy and
911 /// argument types Tys. F might be nullptr, in this case the cost of an
912 /// arbitrary call with the specified signature will be returned.
913 /// This is used, for instance, when we estimate call of a vector
914 /// counterpart of the given function.
915 /// \param F Called function, might be nullptr.
916 /// \param RetTy Return value types.
917 /// \param Tys Argument types.
918 /// \returns The cost of Call instruction.
919 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
923 unsigned getNumberOfParts(Type *Tp) {
924 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
928 unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
933 unsigned getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwise) {
934 assert(Ty->isVectorTy() && "Expect a vector type");
935 Type *ScalarTy = Ty->getVectorElementType();
936 unsigned NumVecElts = Ty->getVectorNumElements();
937 unsigned NumReduxLevels = Log2_32(NumVecElts);
938 // Try to calculate arithmetic and shuffle op costs for reduction operations.
939 // We're assuming that reduction operation are performing the following way:
940 // 1. Non-pairwise reduction
941 // %val1 = shufflevector<n x t> %val, <n x t> %undef,
942 // <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
943 // \----------------v-------------/ \----------v------------/
944 // n/2 elements n/2 elements
945 // %red1 = op <n x t> %val, <n x t> val1
946 // After this operation we have a vector %red1 with only maningfull the
947 // first n/2 elements, the second n/2 elements are undefined and can be
948 // dropped. All other operations are actually working with the vector of
949 // length n/2, not n. though the real vector length is still n.
950 // %val2 = shufflevector<n x t> %red1, <n x t> %undef,
951 // <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
952 // \----------------v-------------/ \----------v------------/
953 // n/4 elements 3*n/4 elements
954 // %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
955 // length n/2, the resulting vector has length n/4 etc.
956 // 2. Pairwise reduction:
957 // Everything is the same except for an additional shuffle operation which
958 // is used to produce operands for pairwise kind of reductions.
959 // %val1 = shufflevector<n x t> %val, <n x t> %undef,
960 // <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
961 // \-------------v----------/ \----------v------------/
962 // n/2 elements n/2 elements
963 // %val2 = shufflevector<n x t> %val, <n x t> %undef,
964 // <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
965 // \-------------v----------/ \----------v------------/
966 // n/2 elements n/2 elements
967 // %red1 = op <n x t> %val1, <n x t> val2
968 // Again, the operation is performed on <n x t> vector, but the resulting
969 // vector %red1 is <n/2 x t> vector.
971 // The cost model should take into account that the actual length of the
972 // vector is reduced on each iteration.
973 unsigned ArithCost = 0;
974 unsigned ShuffleCost = 0;
975 auto *ConcreteTTI = static_cast<T *>(this);
976 std::pair<unsigned, MVT> LT =
977 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
978 unsigned LongVectorCount = 0;
980 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
981 while (NumVecElts > MVTLen) {
983 // Assume the pairwise shuffles add a cost.
984 ShuffleCost += (IsPairwise + 1) *
985 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
987 ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
988 Ty = VectorType::get(ScalarTy, NumVecElts);
991 // The minimal length of the vector is limited by the real length of vector
992 // operations performed on the current platform. That's why several final
993 // reduction opertions are perfomed on the vectors with the same
994 // architecture-dependent length.
995 ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
996 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
998 ArithCost += (NumReduxLevels - LongVectorCount) *
999 ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1000 return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
1003 unsigned getVectorSplitCost() { return 1; }
1008 /// \brief Concrete BasicTTIImpl that can be used if no further customization
1010 class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
1011 typedef BasicTTIImplBase<BasicTTIImpl> BaseT;
1012 friend class BasicTTIImplBase<BasicTTIImpl>;
1014 const TargetSubtargetInfo *ST;
1015 const TargetLoweringBase *TLI;
1017 const TargetSubtargetInfo *getST() const { return ST; }
1018 const TargetLoweringBase *getTLI() const { return TLI; }
1021 explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);