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 //===----------------------------------------------------------------------===//
11 /// This file provides a helper that implements much of the TTI interface in
12 /// terms of the target-independent code generator and TargetLowering
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_CODEGEN_BASICTTIIMPL_H
18 #define LLVM_CODEGEN_BASICTTIIMPL_H
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/TargetTransformInfoImpl.h"
28 #include "llvm/CodeGen/ISDOpcodes.h"
29 #include "llvm/CodeGen/MachineValueType.h"
30 #include "llvm/CodeGen/TargetLowering.h"
31 #include "llvm/CodeGen/TargetSubtargetInfo.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/Constant.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/InstrTypes.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Operator.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/IR/Value.h"
46 #include "llvm/MC/MCSchedule.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
62 class ScalarEvolution;
66 extern cl::opt<unsigned> PartialUnrollingThreshold;
68 /// \brief Base class which can be used to help build a TTI implementation.
70 /// This class provides as much implementation of the TTI interface as is
71 /// possible using the target independent parts of the code generator.
73 /// In order to subclass it, your class must implement a getST() method to
74 /// return the subtarget, and a getTLI() method to return the target lowering.
75 /// We need these methods implemented in the derived class so that this class
76 /// doesn't have to duplicate storage for them.
78 class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
80 using BaseT = TargetTransformInfoImplCRTPBase<T>;
81 using TTI = TargetTransformInfo;
83 /// Estimate a cost of shuffle as a sequence of extract and insert
85 unsigned getPermuteShuffleOverhead(Type *Ty) {
86 assert(Ty->isVectorTy() && "Can only shuffle vectors");
88 // Shuffle cost is equal to the cost of extracting element from its argument
89 // plus the cost of inserting them onto the result vector.
91 // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
92 // index 0 of first vector, index 1 of second vector,index 2 of first
93 // vector and finally index 3 of second vector and insert them at index
94 // <0,1,2,3> of result vector.
95 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
96 Cost += static_cast<T *>(this)
97 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
98 Cost += static_cast<T *>(this)
99 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
104 /// \brief Local query method delegates up to T which *must* implement this!
105 const TargetSubtargetInfo *getST() const {
106 return static_cast<const T *>(this)->getST();
109 /// \brief Local query method delegates up to T which *must* implement this!
110 const TargetLoweringBase *getTLI() const {
111 return static_cast<const T *>(this)->getTLI();
115 explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
118 using TargetTransformInfoImplBase::DL;
121 /// \name Scalar TTI Implementations
123 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
124 unsigned BitWidth, unsigned AddressSpace,
125 unsigned Alignment, bool *Fast) const {
126 EVT E = EVT::getIntegerVT(Context, BitWidth);
127 return getTLI()->allowsMisalignedMemoryAccesses(E, AddressSpace, Alignment, Fast);
130 bool hasBranchDivergence() { return false; }
132 bool isSourceOfDivergence(const Value *V) { return false; }
134 bool isAlwaysUniform(const Value *V) { return false; }
136 unsigned getFlatAddressSpace() {
137 // Return an invalid address space.
141 bool isLegalAddImmediate(int64_t imm) {
142 return getTLI()->isLegalAddImmediate(imm);
145 bool isLegalICmpImmediate(int64_t imm) {
146 return getTLI()->isLegalICmpImmediate(imm);
149 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
150 bool HasBaseReg, int64_t Scale,
151 unsigned AddrSpace, Instruction *I = nullptr) {
152 TargetLoweringBase::AddrMode AM;
154 AM.BaseOffs = BaseOffset;
155 AM.HasBaseReg = HasBaseReg;
157 return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
160 bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2) {
161 return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
164 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
165 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
166 TargetLoweringBase::AddrMode AM;
168 AM.BaseOffs = BaseOffset;
169 AM.HasBaseReg = HasBaseReg;
171 return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
174 bool isTruncateFree(Type *Ty1, Type *Ty2) {
175 return getTLI()->isTruncateFree(Ty1, Ty2);
178 bool isProfitableToHoist(Instruction *I) {
179 return getTLI()->isProfitableToHoist(I);
182 bool isTypeLegal(Type *Ty) {
183 EVT VT = getTLI()->getValueType(DL, Ty);
184 return getTLI()->isTypeLegal(VT);
187 int getGEPCost(Type *PointeeType, const Value *Ptr,
188 ArrayRef<const Value *> Operands) {
189 return BaseT::getGEPCost(PointeeType, Ptr, Operands);
192 int getExtCost(const Instruction *I, const Value *Src) {
193 if (getTLI()->isExtFree(I))
194 return TargetTransformInfo::TCC_Free;
196 if (isa<ZExtInst>(I) || isa<SExtInst>(I))
197 if (const LoadInst *LI = dyn_cast<LoadInst>(Src))
198 if (getTLI()->isExtLoad(LI, I, DL))
199 return TargetTransformInfo::TCC_Free;
201 return TargetTransformInfo::TCC_Basic;
204 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
205 ArrayRef<const Value *> Arguments) {
206 return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
209 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
210 ArrayRef<Type *> ParamTys) {
211 if (IID == Intrinsic::cttz) {
212 if (getTLI()->isCheapToSpeculateCttz())
213 return TargetTransformInfo::TCC_Basic;
214 return TargetTransformInfo::TCC_Expensive;
217 if (IID == Intrinsic::ctlz) {
218 if (getTLI()->isCheapToSpeculateCtlz())
219 return TargetTransformInfo::TCC_Basic;
220 return TargetTransformInfo::TCC_Expensive;
223 return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
226 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
227 unsigned &JumpTableSize) {
228 /// Try to find the estimated number of clusters. Note that the number of
229 /// clusters identified in this function could be different from the actural
230 /// numbers found in lowering. This function ignore switches that are
231 /// lowered with a mix of jump table / bit test / BTree. This function was
232 /// initially intended to be used when estimating the cost of switch in
233 /// inline cost heuristic, but it's a generic cost model to be used in other
234 /// places (e.g., in loop unrolling).
235 unsigned N = SI.getNumCases();
236 const TargetLoweringBase *TLI = getTLI();
237 const DataLayout &DL = this->getDataLayout();
240 bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
242 // Early exit if both a jump table and bit test are not allowed.
243 if (N < 1 || (!IsJTAllowed && DL.getPointerSizeInBits() < N))
246 APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
247 APInt MinCaseVal = MaxCaseVal;
248 for (auto CI : SI.cases()) {
249 const APInt &CaseVal = CI.getCaseValue()->getValue();
250 if (CaseVal.sgt(MaxCaseVal))
251 MaxCaseVal = CaseVal;
252 if (CaseVal.slt(MinCaseVal))
253 MinCaseVal = CaseVal;
256 // Check if suitable for a bit test
257 if (N <= DL.getPointerSizeInBits()) {
258 SmallPtrSet<const BasicBlock *, 4> Dests;
259 for (auto I : SI.cases())
260 Dests.insert(I.getCaseSuccessor());
262 if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
267 // Check if suitable for a jump table.
269 if (N < 2 || N < TLI->getMinimumJumpTableEntries())
272 (MaxCaseVal - MinCaseVal)
273 .getLimitedValue(std::numeric_limits<uint64_t>::max() - 1) + 1;
274 // Check whether a range of clusters is dense enough for a jump table
275 if (TLI->isSuitableForJumpTable(&SI, N, Range)) {
276 JumpTableSize = Range;
283 unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
285 unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
287 bool shouldBuildLookupTables() {
288 const TargetLoweringBase *TLI = getTLI();
289 return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
290 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
293 bool haveFastSqrt(Type *Ty) {
294 const TargetLoweringBase *TLI = getTLI();
295 EVT VT = TLI->getValueType(DL, Ty);
296 return TLI->isTypeLegal(VT) &&
297 TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
300 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
304 unsigned getFPOpCost(Type *Ty) {
305 // Check whether FADD is available, as a proxy for floating-point in
307 const TargetLoweringBase *TLI = getTLI();
308 EVT VT = TLI->getValueType(DL, Ty);
309 if (TLI->isOperationLegalOrCustomOrPromote(ISD::FADD, VT))
310 return TargetTransformInfo::TCC_Basic;
311 return TargetTransformInfo::TCC_Expensive;
314 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
315 const TargetLoweringBase *TLI = getTLI();
318 case Instruction::Trunc:
319 if (TLI->isTruncateFree(OpTy, Ty))
320 return TargetTransformInfo::TCC_Free;
321 return TargetTransformInfo::TCC_Basic;
322 case Instruction::ZExt:
323 if (TLI->isZExtFree(OpTy, Ty))
324 return TargetTransformInfo::TCC_Free;
325 return TargetTransformInfo::TCC_Basic;
328 return BaseT::getOperationCost(Opcode, Ty, OpTy);
331 unsigned getInliningThresholdMultiplier() { return 1; }
333 void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
334 TTI::UnrollingPreferences &UP) {
335 // This unrolling functionality is target independent, but to provide some
336 // motivation for its intended use, for x86:
338 // According to the Intel 64 and IA-32 Architectures Optimization Reference
339 // Manual, Intel Core models and later have a loop stream detector (and
340 // associated uop queue) that can benefit from partial unrolling.
341 // The relevant requirements are:
342 // - The loop must have no more than 4 (8 for Nehalem and later) branches
343 // taken, and none of them may be calls.
344 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
346 // According to the Software Optimization Guide for AMD Family 15h
347 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
348 // and loop buffer which can benefit from partial unrolling.
349 // The relevant requirements are:
350 // - The loop must have fewer than 16 branches
351 // - The loop must have less than 40 uops in all executed loop branches
353 // The number of taken branches in a loop is hard to estimate here, and
354 // benchmarking has revealed that it is better not to be conservative when
355 // estimating the branch count. As a result, we'll ignore the branch limits
356 // until someone finds a case where it matters in practice.
359 const TargetSubtargetInfo *ST = getST();
360 if (PartialUnrollingThreshold.getNumOccurrences() > 0)
361 MaxOps = PartialUnrollingThreshold;
362 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
363 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
367 // Scan the loop: don't unroll loops with calls.
368 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
372 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
373 if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
374 ImmutableCallSite CS(&*J);
375 if (const Function *F = CS.getCalledFunction()) {
376 if (!static_cast<T *>(this)->isLoweredToCall(F))
384 // Enable runtime and partial unrolling up to the specified size.
385 // Enable using trip count upper bound to unroll loops.
386 UP.Partial = UP.Runtime = UP.UpperBound = true;
387 UP.PartialThreshold = MaxOps;
389 // Avoid unrolling when optimizing for size.
390 UP.OptSizeThreshold = 0;
391 UP.PartialOptSizeThreshold = 0;
393 // Set number of instructions optimized when "back edge"
394 // becomes "fall through" to default value of 2.
398 int getInstructionLatency(const Instruction *I) {
399 if (isa<LoadInst>(I))
400 return getST()->getSchedModel().DefaultLoadLatency;
402 return BaseT::getInstructionLatency(I);
405 bool isOutOfOrder() const {
406 return getST()->getSchedModel().isOutOfOrder();
411 /// \name Vector TTI Implementations
414 unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
416 unsigned getRegisterBitWidth(bool Vector) const { return 32; }
418 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
419 /// are set if the result needs to be inserted and/or extracted from vectors.
420 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
421 assert(Ty->isVectorTy() && "Can only scalarize vectors");
424 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
426 Cost += static_cast<T *>(this)
427 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
429 Cost += static_cast<T *>(this)
430 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
436 /// Estimate the overhead of scalarizing an instructions unique
437 /// non-constant operands. The types of the arguments are ordinarily
438 /// scalar, in which case the costs are multiplied with VF.
439 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
442 SmallPtrSet<const Value*, 4> UniqueOperands;
443 for (const Value *A : Args) {
444 if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
445 Type *VecTy = nullptr;
446 if (A->getType()->isVectorTy()) {
447 VecTy = A->getType();
448 // If A is a vector operand, VF should be 1 or correspond to A.
449 assert((VF == 1 || VF == VecTy->getVectorNumElements()) &&
450 "Vector argument does not match VF");
453 VecTy = VectorType::get(A->getType(), VF);
455 Cost += getScalarizationOverhead(VecTy, false, true);
462 unsigned getScalarizationOverhead(Type *VecTy, ArrayRef<const Value *> Args) {
463 assert(VecTy->isVectorTy());
467 Cost += getScalarizationOverhead(VecTy, true, false);
469 Cost += getOperandsScalarizationOverhead(Args,
470 VecTy->getVectorNumElements());
472 // When no information on arguments is provided, we add the cost
473 // associated with one argument as a heuristic.
474 Cost += getScalarizationOverhead(VecTy, false, true);
479 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
481 unsigned getArithmeticInstrCost(
482 unsigned Opcode, Type *Ty,
483 TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
484 TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
485 TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
486 TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
487 ArrayRef<const Value *> Args = ArrayRef<const Value *>()) {
488 // Check if any of the operands are vector operands.
489 const TargetLoweringBase *TLI = getTLI();
490 int ISD = TLI->InstructionOpcodeToISD(Opcode);
491 assert(ISD && "Invalid opcode");
493 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
495 bool IsFloat = Ty->isFPOrFPVectorTy();
496 // Assume that floating point arithmetic operations cost twice as much as
497 // integer operations.
498 unsigned OpCost = (IsFloat ? 2 : 1);
500 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
501 // The operation is legal. Assume it costs 1.
502 // TODO: Once we have extract/insert subvector cost we need to use them.
503 return LT.first * OpCost;
506 if (!TLI->isOperationExpand(ISD, LT.second)) {
507 // If the operation is custom lowered, then assume that the code is twice
509 return LT.first * 2 * OpCost;
512 // Else, assume that we need to scalarize this op.
513 // TODO: If one of the types get legalized by splitting, handle this
514 // similarly to what getCastInstrCost() does.
515 if (Ty->isVectorTy()) {
516 unsigned Num = Ty->getVectorNumElements();
517 unsigned Cost = static_cast<T *>(this)
518 ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
519 // Return the cost of multiple scalar invocation plus the cost of
520 // inserting and extracting the values.
521 return getScalarizationOverhead(Ty, Args) + Num * Cost;
524 // We don't know anything about this scalar instruction.
528 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
530 if (Kind == TTI::SK_Alternate || Kind == TTI::SK_PermuteTwoSrc ||
531 Kind == TTI::SK_PermuteSingleSrc) {
532 return getPermuteShuffleOverhead(Tp);
537 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
538 const Instruction *I = nullptr) {
539 const TargetLoweringBase *TLI = getTLI();
540 int ISD = TLI->InstructionOpcodeToISD(Opcode);
541 assert(ISD && "Invalid opcode");
542 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
543 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
545 // Check for NOOP conversions.
546 if (SrcLT.first == DstLT.first &&
547 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
549 // Bitcast between types that are legalized to the same type are free.
550 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
554 if (Opcode == Instruction::Trunc &&
555 TLI->isTruncateFree(SrcLT.second, DstLT.second))
558 if (Opcode == Instruction::ZExt &&
559 TLI->isZExtFree(SrcLT.second, DstLT.second))
562 if (Opcode == Instruction::AddrSpaceCast &&
563 TLI->isNoopAddrSpaceCast(Src->getPointerAddressSpace(),
564 Dst->getPointerAddressSpace()))
567 // If this is a zext/sext of a load, return 0 if the corresponding
568 // extending load exists on target.
569 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
570 I && isa<LoadInst>(I->getOperand(0))) {
571 EVT ExtVT = EVT::getEVT(Dst);
572 EVT LoadVT = EVT::getEVT(Src);
574 ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
575 if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
579 // If the cast is marked as legal (or promote) then assume low cost.
580 if (SrcLT.first == DstLT.first &&
581 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
584 // Handle scalar conversions.
585 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
586 // Scalar bitcasts are usually free.
587 if (Opcode == Instruction::BitCast)
590 // Just check the op cost. If the operation is legal then assume it costs
592 if (!TLI->isOperationExpand(ISD, DstLT.second))
595 // Assume that illegal scalar instruction are expensive.
599 // Check vector-to-vector casts.
600 if (Dst->isVectorTy() && Src->isVectorTy()) {
601 // If the cast is between same-sized registers, then the check is simple.
602 if (SrcLT.first == DstLT.first &&
603 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
605 // Assume that Zext is done using AND.
606 if (Opcode == Instruction::ZExt)
609 // Assume that sext is done using SHL and SRA.
610 if (Opcode == Instruction::SExt)
613 // Just check the op cost. If the operation is legal then assume it
615 // 1 and multiply by the type-legalization overhead.
616 if (!TLI->isOperationExpand(ISD, DstLT.second))
617 return SrcLT.first * 1;
620 // If we are legalizing by splitting, query the concrete TTI for the cost
621 // of casting the original vector twice. We also need to factor int the
622 // cost of the split itself. Count that as 1, to be consistent with
623 // TLI->getTypeLegalizationCost().
624 if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
625 TargetLowering::TypeSplitVector) ||
626 (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
627 TargetLowering::TypeSplitVector)) {
628 Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
629 Dst->getVectorNumElements() / 2);
630 Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
631 Src->getVectorNumElements() / 2);
632 T *TTI = static_cast<T *>(this);
633 return TTI->getVectorSplitCost() +
634 (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
637 // In other cases where the source or destination are illegal, assume
638 // the operation will get scalarized.
639 unsigned Num = Dst->getVectorNumElements();
640 unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
641 Opcode, Dst->getScalarType(), Src->getScalarType(), I);
643 // Return the cost of multiple scalar invocation plus the cost of
644 // inserting and extracting the values.
645 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
648 // We already handled vector-to-vector and scalar-to-scalar conversions.
650 // is where we handle bitcast between vectors and scalars. We need to assume
651 // that the conversion is scalarized in one way or another.
652 if (Opcode == Instruction::BitCast)
653 // Illegal bitcasts are done by storing and loading from a stack slot.
654 return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
656 (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
659 llvm_unreachable("Unhandled cast");
662 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
663 VectorType *VecTy, unsigned Index) {
664 return static_cast<T *>(this)->getVectorInstrCost(
665 Instruction::ExtractElement, VecTy, Index) +
666 static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
667 VecTy->getElementType());
670 unsigned getCFInstrCost(unsigned Opcode) {
671 // Branches are assumed to be predicted.
675 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
676 const Instruction *I) {
677 const TargetLoweringBase *TLI = getTLI();
678 int ISD = TLI->InstructionOpcodeToISD(Opcode);
679 assert(ISD && "Invalid opcode");
681 // Selects on vectors are actually vector selects.
682 if (ISD == ISD::SELECT) {
683 assert(CondTy && "CondTy must exist");
684 if (CondTy->isVectorTy())
687 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
689 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
690 !TLI->isOperationExpand(ISD, LT.second)) {
691 // The operation is legal. Assume it costs 1. Multiply
692 // by the type-legalization overhead.
696 // Otherwise, assume that the cast is scalarized.
697 // TODO: If one of the types get legalized by splitting, handle this
698 // similarly to what getCastInstrCost() does.
699 if (ValTy->isVectorTy()) {
700 unsigned Num = ValTy->getVectorNumElements();
702 CondTy = CondTy->getScalarType();
703 unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
704 Opcode, ValTy->getScalarType(), CondTy, I);
706 // Return the cost of multiple scalar invocation plus the cost of
707 // inserting and extracting the values.
708 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
711 // Unknown scalar opcode.
715 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
716 std::pair<unsigned, MVT> LT =
717 getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
722 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
723 unsigned AddressSpace, const Instruction *I = nullptr) {
724 assert(!Src->isVoidTy() && "Invalid type");
725 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
727 // Assuming that all loads of legal types cost 1.
728 unsigned Cost = LT.first;
730 if (Src->isVectorTy() &&
731 Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
732 // This is a vector load that legalizes to a larger type than the vector
733 // itself. Unless the corresponding extending load or truncating store is
734 // legal, then this will scalarize.
735 TargetLowering::LegalizeAction LA = TargetLowering::Expand;
736 EVT MemVT = getTLI()->getValueType(DL, Src);
737 if (Opcode == Instruction::Store)
738 LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
740 LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
742 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
743 // This is a vector load/store for some illegal type that is scalarized.
744 // We must account for the cost of building or decomposing the vector.
745 Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
746 Opcode == Instruction::Store);
753 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
755 ArrayRef<unsigned> Indices,
757 unsigned AddressSpace) {
758 VectorType *VT = dyn_cast<VectorType>(VecTy);
759 assert(VT && "Expect a vector type for interleaved memory op");
761 unsigned NumElts = VT->getNumElements();
762 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
764 unsigned NumSubElts = NumElts / Factor;
765 VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
767 // Firstly, the cost of load/store operation.
768 unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
769 Opcode, VecTy, Alignment, AddressSpace);
771 // Legalize the vector type, and get the legalized and unlegalized type
773 MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
775 static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
776 unsigned VecTyLTSize = VecTyLT.getStoreSize();
778 // Return the ceiling of dividing A by B.
779 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
781 // Scale the cost of the memory operation by the fraction of legalized
782 // instructions that will actually be used. We shouldn't account for the
783 // cost of dead instructions since they will be removed.
785 // E.g., An interleaved load of factor 8:
786 // %vec = load <16 x i64>, <16 x i64>* %ptr
787 // %v0 = shufflevector %vec, undef, <0, 8>
789 // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
790 // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
791 // type). The other loads are unused.
793 // We only scale the cost of loads since interleaved store groups aren't
794 // allowed to have gaps.
795 if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
796 // The number of loads of a legal type it will take to represent a load
797 // of the unlegalized vector type.
798 unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
800 // The number of elements of the unlegalized type that correspond to a
801 // single legal instruction.
802 unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
804 // Determine which legal instructions will be used.
805 BitVector UsedInsts(NumLegalInsts, false);
806 for (unsigned Index : Indices)
807 for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
808 UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
810 // Scale the cost of the load by the fraction of legal instructions that
812 Cost *= UsedInsts.count() / NumLegalInsts;
815 // Then plus the cost of interleave operation.
816 if (Opcode == Instruction::Load) {
817 // The interleave cost is similar to extract sub vectors' elements
818 // from the wide vector, and insert them into sub vectors.
820 // E.g. An interleaved load of factor 2 (with one member of index 0):
821 // %vec = load <8 x i32>, <8 x i32>* %ptr
822 // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
823 // The cost is estimated as extract elements at 0, 2, 4, 6 from the
824 // <8 x i32> vector and insert them into a <4 x i32> vector.
826 assert(Indices.size() <= Factor &&
827 "Interleaved memory op has too many members");
829 for (unsigned Index : Indices) {
830 assert(Index < Factor && "Invalid index for interleaved memory op");
832 // Extract elements from loaded vector for each sub vector.
833 for (unsigned i = 0; i < NumSubElts; i++)
834 Cost += static_cast<T *>(this)->getVectorInstrCost(
835 Instruction::ExtractElement, VT, Index + i * Factor);
838 unsigned InsSubCost = 0;
839 for (unsigned i = 0; i < NumSubElts; i++)
840 InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
841 Instruction::InsertElement, SubVT, i);
843 Cost += Indices.size() * InsSubCost;
845 // The interleave cost is extract all elements from sub vectors, and
846 // insert them into the wide vector.
848 // E.g. An interleaved store of factor 2:
849 // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
850 // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
851 // The cost is estimated as extract all elements from both <4 x i32>
852 // vectors and insert into the <8 x i32> vector.
854 unsigned ExtSubCost = 0;
855 for (unsigned i = 0; i < NumSubElts; i++)
856 ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
857 Instruction::ExtractElement, SubVT, i);
858 Cost += ExtSubCost * Factor;
860 for (unsigned i = 0; i < NumElts; i++)
861 Cost += static_cast<T *>(this)
862 ->getVectorInstrCost(Instruction::InsertElement, VT, i);
868 /// Get intrinsic cost based on arguments.
869 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
870 ArrayRef<Value *> Args, FastMathFlags FMF,
872 unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
873 assert((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type");
877 // Assume that we need to scalarize this intrinsic.
878 SmallVector<Type *, 4> Types;
879 for (Value *Op : Args) {
880 Type *OpTy = Op->getType();
881 assert(VF == 1 || !OpTy->isVectorTy());
882 Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
885 if (VF > 1 && !RetTy->isVoidTy())
886 RetTy = VectorType::get(RetTy, VF);
888 // Compute the scalarization overhead based on Args for a vector
889 // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
890 // CostModel will pass a vector RetTy and VF is 1.
891 unsigned ScalarizationCost = std::numeric_limits<unsigned>::max();
892 if (RetVF > 1 || VF > 1) {
893 ScalarizationCost = 0;
894 if (!RetTy->isVoidTy())
895 ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
896 ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
899 return static_cast<T *>(this)->
900 getIntrinsicInstrCost(IID, RetTy, Types, FMF, ScalarizationCost);
902 case Intrinsic::masked_scatter: {
903 assert(VF == 1 && "Can't vectorize types here.");
904 Value *Mask = Args[3];
905 bool VarMask = !isa<Constant>(Mask);
906 unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
908 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Store,
913 case Intrinsic::masked_gather: {
914 assert(VF == 1 && "Can't vectorize types here.");
915 Value *Mask = Args[2];
916 bool VarMask = !isa<Constant>(Mask);
917 unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
919 static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Load,
920 RetTy, Args[0], VarMask,
926 /// Get intrinsic cost based on argument types.
927 /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
928 /// cost of scalarizing the arguments and the return value will be computed
930 unsigned getIntrinsicInstrCost(
931 Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> Tys, FastMathFlags FMF,
932 unsigned ScalarizationCostPassed = std::numeric_limits<unsigned>::max()) {
933 SmallVector<unsigned, 2> ISDs;
934 unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
937 // Assume that we need to scalarize this intrinsic.
938 unsigned ScalarizationCost = ScalarizationCostPassed;
939 unsigned ScalarCalls = 1;
940 Type *ScalarRetTy = RetTy;
941 if (RetTy->isVectorTy()) {
942 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
943 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
944 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
945 ScalarRetTy = RetTy->getScalarType();
947 SmallVector<Type *, 4> ScalarTys;
948 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
950 if (Ty->isVectorTy()) {
951 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
952 ScalarizationCost += getScalarizationOverhead(Ty, false, true);
953 ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
954 Ty = Ty->getScalarType();
956 ScalarTys.push_back(Ty);
958 if (ScalarCalls == 1)
959 return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
961 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
962 IID, ScalarRetTy, ScalarTys, FMF);
964 return ScalarCalls * ScalarCost + ScalarizationCost;
966 // Look for intrinsics that can be lowered directly or turned into a scalar
968 case Intrinsic::sqrt:
969 ISDs.push_back(ISD::FSQRT);
972 ISDs.push_back(ISD::FSIN);
975 ISDs.push_back(ISD::FCOS);
978 ISDs.push_back(ISD::FEXP);
980 case Intrinsic::exp2:
981 ISDs.push_back(ISD::FEXP2);
984 ISDs.push_back(ISD::FLOG);
986 case Intrinsic::log10:
987 ISDs.push_back(ISD::FLOG10);
989 case Intrinsic::log2:
990 ISDs.push_back(ISD::FLOG2);
992 case Intrinsic::fabs:
993 ISDs.push_back(ISD::FABS);
995 case Intrinsic::minnum:
996 ISDs.push_back(ISD::FMINNUM);
998 ISDs.push_back(ISD::FMINNAN);
1000 case Intrinsic::maxnum:
1001 ISDs.push_back(ISD::FMAXNUM);
1003 ISDs.push_back(ISD::FMAXNAN);
1005 case Intrinsic::copysign:
1006 ISDs.push_back(ISD::FCOPYSIGN);
1008 case Intrinsic::floor:
1009 ISDs.push_back(ISD::FFLOOR);
1011 case Intrinsic::ceil:
1012 ISDs.push_back(ISD::FCEIL);
1014 case Intrinsic::trunc:
1015 ISDs.push_back(ISD::FTRUNC);
1017 case Intrinsic::nearbyint:
1018 ISDs.push_back(ISD::FNEARBYINT);
1020 case Intrinsic::rint:
1021 ISDs.push_back(ISD::FRINT);
1023 case Intrinsic::round:
1024 ISDs.push_back(ISD::FROUND);
1026 case Intrinsic::pow:
1027 ISDs.push_back(ISD::FPOW);
1029 case Intrinsic::fma:
1030 ISDs.push_back(ISD::FMA);
1032 case Intrinsic::fmuladd:
1033 ISDs.push_back(ISD::FMA);
1035 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
1036 case Intrinsic::lifetime_start:
1037 case Intrinsic::lifetime_end:
1038 case Intrinsic::sideeffect:
1040 case Intrinsic::masked_store:
1041 return static_cast<T *>(this)
1042 ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
1043 case Intrinsic::masked_load:
1044 return static_cast<T *>(this)
1045 ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
1046 case Intrinsic::ctpop:
1047 ISDs.push_back(ISD::CTPOP);
1048 // In case of legalization use TCC_Expensive. This is cheaper than a
1049 // library call but still not a cheap instruction.
1050 SingleCallCost = TargetTransformInfo::TCC_Expensive;
1052 // FIXME: ctlz, cttz, ...
1055 const TargetLoweringBase *TLI = getTLI();
1056 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
1058 SmallVector<unsigned, 2> LegalCost;
1059 SmallVector<unsigned, 2> CustomCost;
1060 for (unsigned ISD : ISDs) {
1061 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
1062 if (IID == Intrinsic::fabs && TLI->isFAbsFree(LT.second)) {
1066 // The operation is legal. Assume it costs 1.
1067 // If the type is split to multiple registers, assume that there is some
1068 // overhead to this.
1069 // TODO: Once we have extract/insert subvector cost we need to use them.
1071 LegalCost.push_back(LT.first * 2);
1073 LegalCost.push_back(LT.first * 1);
1074 } else if (!TLI->isOperationExpand(ISD, LT.second)) {
1075 // If the operation is custom lowered then assume
1076 // that the code is twice as expensive.
1077 CustomCost.push_back(LT.first * 2);
1081 auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
1082 if (MinLegalCostI != LegalCost.end())
1083 return *MinLegalCostI;
1085 auto MinCustomCostI = std::min_element(CustomCost.begin(), CustomCost.end());
1086 if (MinCustomCostI != CustomCost.end())
1087 return *MinCustomCostI;
1089 // If we can't lower fmuladd into an FMA estimate the cost as a floating
1090 // point mul followed by an add.
1091 if (IID == Intrinsic::fmuladd)
1092 return static_cast<T *>(this)
1093 ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
1094 static_cast<T *>(this)
1095 ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
1097 // Else, assume that we need to scalarize this intrinsic. For math builtins
1098 // this will emit a costly libcall, adding call overhead and spills. Make it
1100 if (RetTy->isVectorTy()) {
1101 unsigned ScalarizationCost =
1102 ((ScalarizationCostPassed != std::numeric_limits<unsigned>::max())
1103 ? ScalarizationCostPassed
1104 : getScalarizationOverhead(RetTy, true, false));
1105 unsigned ScalarCalls = RetTy->getVectorNumElements();
1106 SmallVector<Type *, 4> ScalarTys;
1107 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1109 if (Ty->isVectorTy())
1110 Ty = Ty->getScalarType();
1111 ScalarTys.push_back(Ty);
1113 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
1114 IID, RetTy->getScalarType(), ScalarTys, FMF);
1115 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1116 if (Tys[i]->isVectorTy()) {
1117 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1118 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
1119 ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
1123 return ScalarCalls * ScalarCost + ScalarizationCost;
1126 // This is going to be turned into a library call, make it expensive.
1127 return SingleCallCost;
1130 /// \brief Compute a cost of the given call instruction.
1132 /// Compute the cost of calling function F with return type RetTy and
1133 /// argument types Tys. F might be nullptr, in this case the cost of an
1134 /// arbitrary call with the specified signature will be returned.
1135 /// This is used, for instance, when we estimate call of a vector
1136 /// counterpart of the given function.
1137 /// \param F Called function, might be nullptr.
1138 /// \param RetTy Return value types.
1139 /// \param Tys Argument types.
1140 /// \returns The cost of Call instruction.
1141 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
1145 unsigned getNumberOfParts(Type *Tp) {
1146 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
1150 unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
1155 /// Try to calculate arithmetic and shuffle op costs for reduction operations.
1156 /// We're assuming that reduction operation are performing the following way:
1157 /// 1. Non-pairwise reduction
1158 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1159 /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
1160 /// \----------------v-------------/ \----------v------------/
1161 /// n/2 elements n/2 elements
1162 /// %red1 = op <n x t> %val, <n x t> val1
1163 /// After this operation we have a vector %red1 where only the first n/2
1164 /// elements are meaningful, the second n/2 elements are undefined and can be
1165 /// dropped. All other operations are actually working with the vector of
1166 /// length n/2, not n, though the real vector length is still n.
1167 /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
1168 /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
1169 /// \----------------v-------------/ \----------v------------/
1170 /// n/4 elements 3*n/4 elements
1171 /// %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
1172 /// length n/2, the resulting vector has length n/4 etc.
1173 /// 2. Pairwise reduction:
1174 /// Everything is the same except for an additional shuffle operation which
1175 /// is used to produce operands for pairwise kind of reductions.
1176 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1177 /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
1178 /// \-------------v----------/ \----------v------------/
1179 /// n/2 elements n/2 elements
1180 /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
1181 /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
1182 /// \-------------v----------/ \----------v------------/
1183 /// n/2 elements n/2 elements
1184 /// %red1 = op <n x t> %val1, <n x t> val2
1185 /// Again, the operation is performed on <n x t> vector, but the resulting
1186 /// vector %red1 is <n/2 x t> vector.
1188 /// The cost model should take into account that the actual length of the
1189 /// vector is reduced on each iteration.
1190 unsigned getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1192 assert(Ty->isVectorTy() && "Expect a vector type");
1193 Type *ScalarTy = Ty->getVectorElementType();
1194 unsigned NumVecElts = Ty->getVectorNumElements();
1195 unsigned NumReduxLevels = Log2_32(NumVecElts);
1196 unsigned ArithCost = 0;
1197 unsigned ShuffleCost = 0;
1198 auto *ConcreteTTI = static_cast<T *>(this);
1199 std::pair<unsigned, MVT> LT =
1200 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1201 unsigned LongVectorCount = 0;
1203 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1204 while (NumVecElts > MVTLen) {
1206 // Assume the pairwise shuffles add a cost.
1207 ShuffleCost += (IsPairwise + 1) *
1208 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1210 ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1211 Ty = VectorType::get(ScalarTy, NumVecElts);
1214 // The minimal length of the vector is limited by the real length of vector
1215 // operations performed on the current platform. That's why several final
1216 // reduction operations are performed on the vectors with the same
1217 // architecture-dependent length.
1218 ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1219 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1221 ArithCost += (NumReduxLevels - LongVectorCount) *
1222 ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1223 return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
1226 /// Try to calculate op costs for min/max reduction operations.
1227 /// \param CondTy Conditional type for the Select instruction.
1228 unsigned getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwise,
1230 assert(Ty->isVectorTy() && "Expect a vector type");
1231 Type *ScalarTy = Ty->getVectorElementType();
1232 Type *ScalarCondTy = CondTy->getVectorElementType();
1233 unsigned NumVecElts = Ty->getVectorNumElements();
1234 unsigned NumReduxLevels = Log2_32(NumVecElts);
1236 if (Ty->isFPOrFPVectorTy()) {
1237 CmpOpcode = Instruction::FCmp;
1239 assert(Ty->isIntOrIntVectorTy() &&
1240 "expecting floating point or integer type for min/max reduction");
1241 CmpOpcode = Instruction::ICmp;
1243 unsigned MinMaxCost = 0;
1244 unsigned ShuffleCost = 0;
1245 auto *ConcreteTTI = static_cast<T *>(this);
1246 std::pair<unsigned, MVT> LT =
1247 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1248 unsigned LongVectorCount = 0;
1250 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1251 while (NumVecElts > MVTLen) {
1253 // Assume the pairwise shuffles add a cost.
1254 ShuffleCost += (IsPairwise + 1) *
1255 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1258 ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1259 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1261 Ty = VectorType::get(ScalarTy, NumVecElts);
1262 CondTy = VectorType::get(ScalarCondTy, NumVecElts);
1265 // The minimal length of the vector is limited by the real length of vector
1266 // operations performed on the current platform. That's why several final
1267 // reduction opertions are perfomed on the vectors with the same
1268 // architecture-dependent length.
1269 ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
1270 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1273 (NumReduxLevels - LongVectorCount) *
1274 (ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1275 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1277 // Need 3 extractelement instructions for scalarization + an additional
1278 // scalar select instruction.
1279 return ShuffleCost + MinMaxCost +
1280 3 * getScalarizationOverhead(Ty, /*Insert=*/false,
1282 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
1283 ScalarCondTy, nullptr);
1286 unsigned getVectorSplitCost() { return 1; }
1291 /// \brief Concrete BasicTTIImpl that can be used if no further customization
1293 class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
1294 using BaseT = BasicTTIImplBase<BasicTTIImpl>;
1296 friend class BasicTTIImplBase<BasicTTIImpl>;
1298 const TargetSubtargetInfo *ST;
1299 const TargetLoweringBase *TLI;
1301 const TargetSubtargetInfo *getST() const { return ST; }
1302 const TargetLoweringBase *getTLI() const { return TLI; }
1305 explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);
1308 } // end namespace llvm
1310 #endif // LLVM_CODEGEN_BASICTTIIMPL_H