1 //===- TargetTransformInfoImpl.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 helpers for the implementation of
11 /// a TargetTransformInfo-conforming class.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
16 #define LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
18 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/Type.h"
26 #include "llvm/Analysis/VectorUtils.h"
30 /// \brief Base class for use as a mix-in that aids implementing
31 /// a TargetTransformInfo-compatible class.
32 class TargetTransformInfoImplBase {
34 typedef TargetTransformInfo TTI;
38 explicit TargetTransformInfoImplBase(const DataLayout &DL) : DL(DL) {}
41 // Provide value semantics. MSVC requires that we spell all of these out.
42 TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg)
44 TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg) : DL(Arg.DL) {}
46 const DataLayout &getDataLayout() const { return DL; }
48 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
51 // By default, just classify everything as 'basic'.
52 return TTI::TCC_Basic;
54 case Instruction::GetElementPtr:
55 llvm_unreachable("Use getGEPCost for GEP operations!");
57 case Instruction::BitCast:
58 assert(OpTy && "Cast instructions must provide the operand type");
59 if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy()))
60 // Identity and pointer-to-pointer casts are free.
63 // Otherwise, the default basic cost is used.
64 return TTI::TCC_Basic;
66 case Instruction::FDiv:
67 case Instruction::FRem:
68 case Instruction::SDiv:
69 case Instruction::SRem:
70 case Instruction::UDiv:
71 case Instruction::URem:
72 return TTI::TCC_Expensive;
74 case Instruction::IntToPtr: {
75 // An inttoptr cast is free so long as the input is a legal integer type
76 // which doesn't contain values outside the range of a pointer.
77 unsigned OpSize = OpTy->getScalarSizeInBits();
78 if (DL.isLegalInteger(OpSize) &&
79 OpSize <= DL.getPointerTypeSizeInBits(Ty))
82 // Otherwise it's not a no-op.
83 return TTI::TCC_Basic;
85 case Instruction::PtrToInt: {
86 // A ptrtoint cast is free so long as the result is large enough to store
87 // the pointer, and a legal integer type.
88 unsigned DestSize = Ty->getScalarSizeInBits();
89 if (DL.isLegalInteger(DestSize) &&
90 DestSize >= DL.getPointerTypeSizeInBits(OpTy))
93 // Otherwise it's not a no-op.
94 return TTI::TCC_Basic;
96 case Instruction::Trunc:
97 // trunc to a native type is free (assuming the target has compare and
98 // shift-right of the same width).
99 if (DL.isLegalInteger(DL.getTypeSizeInBits(Ty)))
100 return TTI::TCC_Free;
102 return TTI::TCC_Basic;
106 int getGEPCost(Type *PointeeType, const Value *Ptr,
107 ArrayRef<const Value *> Operands) {
108 // In the basic model, we just assume that all-constant GEPs will be folded
109 // into their uses via addressing modes.
110 for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx)
111 if (!isa<Constant>(Operands[Idx]))
112 return TTI::TCC_Basic;
114 return TTI::TCC_Free;
117 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
120 return SI.getNumCases();
123 unsigned getCallCost(FunctionType *FTy, int NumArgs) {
124 assert(FTy && "FunctionType must be provided to this routine.");
126 // The target-independent implementation just measures the size of the
127 // function by approximating that each argument will take on average one
128 // instruction to prepare.
131 // Set the argument number to the number of explicit arguments in the
133 NumArgs = FTy->getNumParams();
135 return TTI::TCC_Basic * (NumArgs + 1);
138 unsigned getInliningThresholdMultiplier() { return 1; }
140 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
141 ArrayRef<Type *> ParamTys) {
144 // Intrinsics rarely (if ever) have normal argument setup constraints.
145 // Model them as having a basic instruction cost.
146 // FIXME: This is wrong for libc intrinsics.
147 return TTI::TCC_Basic;
149 case Intrinsic::annotation:
150 case Intrinsic::assume:
151 case Intrinsic::dbg_declare:
152 case Intrinsic::dbg_value:
153 case Intrinsic::invariant_start:
154 case Intrinsic::invariant_end:
155 case Intrinsic::lifetime_start:
156 case Intrinsic::lifetime_end:
157 case Intrinsic::objectsize:
158 case Intrinsic::ptr_annotation:
159 case Intrinsic::var_annotation:
160 case Intrinsic::experimental_gc_result:
161 case Intrinsic::experimental_gc_relocate:
162 case Intrinsic::coro_alloc:
163 case Intrinsic::coro_begin:
164 case Intrinsic::coro_free:
165 case Intrinsic::coro_end:
166 case Intrinsic::coro_frame:
167 case Intrinsic::coro_size:
168 case Intrinsic::coro_suspend:
169 case Intrinsic::coro_param:
170 case Intrinsic::coro_subfn_addr:
171 // These intrinsics don't actually represent code after lowering.
172 return TTI::TCC_Free;
176 bool hasBranchDivergence() { return false; }
178 bool isSourceOfDivergence(const Value *V) { return false; }
180 unsigned getFlatAddressSpace () {
184 bool isLoweredToCall(const Function *F) {
185 // FIXME: These should almost certainly not be handled here, and instead
186 // handled with the help of TLI or the target itself. This was largely
187 // ported from existing analysis heuristics here so that such refactorings
188 // can take place in the future.
190 if (F->isIntrinsic())
193 if (F->hasLocalLinkage() || !F->hasName())
196 StringRef Name = F->getName();
198 // These will all likely lower to a single selection DAG node.
199 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
200 Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
201 Name == "fmin" || Name == "fminf" || Name == "fminl" ||
202 Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
203 Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
204 Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
207 // These are all likely to be optimized into something smaller.
208 if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
209 Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
210 Name == "floorf" || Name == "ceil" || Name == "round" ||
211 Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
218 void getUnrollingPreferences(Loop *, TTI::UnrollingPreferences &) {}
220 bool isLegalAddImmediate(int64_t Imm) { return false; }
222 bool isLegalICmpImmediate(int64_t Imm) { return false; }
224 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
225 bool HasBaseReg, int64_t Scale,
226 unsigned AddrSpace) {
227 // Guess that only reg and reg+reg addressing is allowed. This heuristic is
228 // taken from the implementation of LSR.
229 return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
232 bool isLegalMaskedStore(Type *DataType) { return false; }
234 bool isLegalMaskedLoad(Type *DataType) { return false; }
236 bool isLegalMaskedScatter(Type *DataType) { return false; }
238 bool isLegalMaskedGather(Type *DataType) { return false; }
240 bool prefersVectorizedAddressing() { return true; }
242 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
243 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
244 // Guess that all legal addressing mode are free.
245 if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
251 bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) { return true; }
253 bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
255 bool isProfitableToHoist(Instruction *I) { return true; }
257 bool isTypeLegal(Type *Ty) { return false; }
259 unsigned getJumpBufAlignment() { return 0; }
261 unsigned getJumpBufSize() { return 0; }
263 bool shouldBuildLookupTables() { return true; }
264 bool shouldBuildLookupTablesForConstant(Constant *C) { return true; }
266 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
270 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
271 unsigned VF) { return 0; }
273 bool supportsEfficientVectorElementLoadStore() { return false; }
275 bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
277 bool enableInterleavedAccessVectorization() { return false; }
279 bool isFPVectorizationPotentiallyUnsafe() { return false; }
281 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
283 unsigned AddressSpace,
285 bool *Fast) { return false; }
287 TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
288 return TTI::PSK_Software;
291 bool haveFastSqrt(Type *Ty) { return false; }
293 unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
295 int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
300 unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
302 unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
304 return TTI::TCC_Free;
307 unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
309 return TTI::TCC_Free;
312 unsigned getNumberOfRegisters(bool Vector) { return 8; }
314 unsigned getRegisterBitWidth(bool Vector) { return 32; }
316 unsigned getMinVectorRegisterBitWidth() { return 128; }
319 shouldConsiderAddressTypePromotion(const Instruction &I,
320 bool &AllowPromotionWithoutCommonHeader) {
321 AllowPromotionWithoutCommonHeader = false;
325 unsigned getCacheLineSize() { return 0; }
327 unsigned getPrefetchDistance() { return 0; }
329 unsigned getMinPrefetchStride() { return 1; }
331 unsigned getMaxPrefetchIterationsAhead() { return UINT_MAX; }
333 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
335 unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
336 TTI::OperandValueKind Opd1Info,
337 TTI::OperandValueKind Opd2Info,
338 TTI::OperandValueProperties Opd1PropInfo,
339 TTI::OperandValueProperties Opd2PropInfo,
340 ArrayRef<const Value *> Args) {
344 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
349 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
350 const Instruction *I) { return 1; }
352 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
353 VectorType *VecTy, unsigned Index) {
357 unsigned getCFInstrCost(unsigned Opcode) { return 1; }
359 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
360 const Instruction *I) {
364 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
368 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
369 unsigned AddressSpace, const Instruction *I) {
373 unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
374 unsigned AddressSpace) {
378 unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
380 unsigned Alignment) {
384 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
386 ArrayRef<unsigned> Indices,
388 unsigned AddressSpace) {
392 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
393 ArrayRef<Type *> Tys, FastMathFlags FMF,
394 unsigned ScalarizationCostPassed) {
397 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
398 ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) {
402 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
406 unsigned getNumberOfParts(Type *Tp) { return 0; }
408 unsigned getAddressComputationCost(Type *Tp, ScalarEvolution *,
413 unsigned getReductionCost(unsigned, Type *, bool) { return 1; }
415 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
417 bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
421 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
422 Type *ExpectedType) {
426 bool areInlineCompatible(const Function *Caller,
427 const Function *Callee) const {
428 return (Caller->getFnAttribute("target-cpu") ==
429 Callee->getFnAttribute("target-cpu")) &&
430 (Caller->getFnAttribute("target-features") ==
431 Callee->getFnAttribute("target-features"));
434 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { return 128; }
436 bool isLegalToVectorizeLoad(LoadInst *LI) const { return true; }
438 bool isLegalToVectorizeStore(StoreInst *SI) const { return true; }
440 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
442 unsigned AddrSpace) const {
446 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
448 unsigned AddrSpace) const {
452 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
453 unsigned ChainSizeInBytes,
454 VectorType *VecTy) const {
458 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
459 unsigned ChainSizeInBytes,
460 VectorType *VecTy) const {
464 bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
465 TTI::ReductionFlags Flags) const {
469 bool shouldExpandReduction(const IntrinsicInst *II) const {
474 // Obtain the minimum required size to hold the value (without the sign)
475 // In case of a vector it returns the min required size for one element.
476 unsigned minRequiredElementSize(const Value* Val, bool &isSigned) {
477 if (isa<ConstantDataVector>(Val) || isa<ConstantVector>(Val)) {
478 const auto* VectorValue = cast<Constant>(Val);
480 // In case of a vector need to pick the max between the min
481 // required size for each element
482 auto *VT = cast<VectorType>(Val->getType());
484 // Assume unsigned elements
487 // The max required size is the total vector width divided by num
488 // of elements in the vector
489 unsigned MaxRequiredSize = VT->getBitWidth() / VT->getNumElements();
491 unsigned MinRequiredSize = 0;
492 for(unsigned i = 0, e = VT->getNumElements(); i < e; ++i) {
493 if (auto* IntElement =
494 dyn_cast<ConstantInt>(VectorValue->getAggregateElement(i))) {
495 bool signedElement = IntElement->getValue().isNegative();
496 // Get the element min required size.
497 unsigned ElementMinRequiredSize =
498 IntElement->getValue().getMinSignedBits() - 1;
499 // In case one element is signed then all the vector is signed.
500 isSigned |= signedElement;
501 // Save the max required bit size between all the elements.
502 MinRequiredSize = std::max(MinRequiredSize, ElementMinRequiredSize);
505 // not an int constant element
506 return MaxRequiredSize;
509 return MinRequiredSize;
512 if (const auto* CI = dyn_cast<ConstantInt>(Val)) {
513 isSigned = CI->getValue().isNegative();
514 return CI->getValue().getMinSignedBits() - 1;
517 if (const auto* Cast = dyn_cast<SExtInst>(Val)) {
519 return Cast->getSrcTy()->getScalarSizeInBits() - 1;
522 if (const auto* Cast = dyn_cast<ZExtInst>(Val)) {
524 return Cast->getSrcTy()->getScalarSizeInBits();
528 return Val->getType()->getScalarSizeInBits();
531 bool isStridedAccess(const SCEV *Ptr) {
532 return Ptr && isa<SCEVAddRecExpr>(Ptr);
535 const SCEVConstant *getConstantStrideStep(ScalarEvolution *SE,
537 if (!isStridedAccess(Ptr))
539 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ptr);
540 return dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*SE));
543 bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr,
544 int64_t MergeDistance) {
545 const SCEVConstant *Step = getConstantStrideStep(SE, Ptr);
548 APInt StrideVal = Step->getAPInt();
549 if (StrideVal.getBitWidth() > 64)
551 // FIXME: need to take absolute value for negtive stride case
552 return StrideVal.getSExtValue() < MergeDistance;
556 /// \brief CRTP base class for use as a mix-in that aids implementing
557 /// a TargetTransformInfo-compatible class.
558 template <typename T>
559 class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
561 typedef TargetTransformInfoImplBase BaseT;
564 explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
567 using BaseT::getCallCost;
569 unsigned getCallCost(const Function *F, int NumArgs) {
570 assert(F && "A concrete function must be provided to this routine.");
573 // Set the argument number to the number of explicit arguments in the
575 NumArgs = F->arg_size();
577 if (Intrinsic::ID IID = F->getIntrinsicID()) {
578 FunctionType *FTy = F->getFunctionType();
579 SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
580 return static_cast<T *>(this)
581 ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
584 if (!static_cast<T *>(this)->isLoweredToCall(F))
585 return TTI::TCC_Basic; // Give a basic cost if it will be lowered
588 return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
591 unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
592 // Simply delegate to generic handling of the call.
593 // FIXME: We should use instsimplify or something else to catch calls which
594 // will constant fold with these arguments.
595 return static_cast<T *>(this)->getCallCost(F, Arguments.size());
598 using BaseT::getGEPCost;
600 int getGEPCost(Type *PointeeType, const Value *Ptr,
601 ArrayRef<const Value *> Operands) {
602 const GlobalValue *BaseGV = nullptr;
603 if (Ptr != nullptr) {
604 // TODO: will remove this when pointers have an opaque type.
605 assert(Ptr->getType()->getScalarType()->getPointerElementType() ==
607 "explicit pointee type doesn't match operand's pointee type");
608 BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
610 bool HasBaseReg = (BaseGV == nullptr);
611 int64_t BaseOffset = 0;
614 auto GTI = gep_type_begin(PointeeType, Operands);
616 for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
617 TargetType = GTI.getIndexedType();
618 // We assume that the cost of Scalar GEP with constant index and the
619 // cost of Vector GEP with splat constant index are the same.
620 const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
622 if (auto Splat = getSplatValue(*I))
623 ConstIdx = dyn_cast<ConstantInt>(Splat);
624 if (StructType *STy = GTI.getStructTypeOrNull()) {
625 // For structures the index is always splat or scalar constant
626 assert(ConstIdx && "Unexpected GEP index");
627 uint64_t Field = ConstIdx->getZExtValue();
628 BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
630 int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
632 BaseOffset += ConstIdx->getSExtValue() * ElementSize;
634 // Needs scale register.
636 // No addressing mode takes two scale registers.
637 return TTI::TCC_Basic;
643 // Assumes the address space is 0 when Ptr is nullptr.
645 (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
646 if (static_cast<T *>(this)->isLegalAddressingMode(
647 TargetType, const_cast<GlobalValue *>(BaseGV), BaseOffset,
648 HasBaseReg, Scale, AS))
649 return TTI::TCC_Free;
650 return TTI::TCC_Basic;
653 using BaseT::getIntrinsicCost;
655 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
656 ArrayRef<const Value *> Arguments) {
657 // Delegate to the generic intrinsic handling code. This mostly provides an
658 // opportunity for targets to (for example) special case the cost of
659 // certain intrinsics based on constants used as arguments.
660 SmallVector<Type *, 8> ParamTys;
661 ParamTys.reserve(Arguments.size());
662 for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
663 ParamTys.push_back(Arguments[Idx]->getType());
664 return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
667 unsigned getUserCost(const User *U) {
669 return TTI::TCC_Free; // Model all PHI nodes as free.
671 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
672 SmallVector<Value *, 4> Indices(GEP->idx_begin(), GEP->idx_end());
673 return static_cast<T *>(this)->getGEPCost(
674 GEP->getSourceElementType(), GEP->getPointerOperand(), Indices);
677 if (auto CS = ImmutableCallSite(U)) {
678 const Function *F = CS.getCalledFunction();
680 // Just use the called value type.
681 Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
682 return static_cast<T *>(this)
683 ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
686 SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
687 return static_cast<T *>(this)->getCallCost(F, Arguments);
690 if (const CastInst *CI = dyn_cast<CastInst>(U)) {
691 // Result of a cmp instruction is often extended (to be used by other
692 // cmp instructions, logical or return instructions). These are usually
693 // nop on most sane targets.
694 if (isa<CmpInst>(CI->getOperand(0)))
695 return TTI::TCC_Free;
698 return static_cast<T *>(this)->getOperationCost(
699 Operator::getOpcode(U), U->getType(),
700 U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);