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/Analysis/VectorUtils.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/Type.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 int getExtCost(const Instruction *I, const Value *Src) {
124 return TTI::TCC_Basic;
127 unsigned getCallCost(FunctionType *FTy, int NumArgs) {
128 assert(FTy && "FunctionType must be provided to this routine.");
130 // The target-independent implementation just measures the size of the
131 // function by approximating that each argument will take on average one
132 // instruction to prepare.
135 // Set the argument number to the number of explicit arguments in the
137 NumArgs = FTy->getNumParams();
139 return TTI::TCC_Basic * (NumArgs + 1);
142 unsigned getInliningThresholdMultiplier() { return 1; }
144 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
145 ArrayRef<Type *> ParamTys) {
148 // Intrinsics rarely (if ever) have normal argument setup constraints.
149 // Model them as having a basic instruction cost.
150 // FIXME: This is wrong for libc intrinsics.
151 return TTI::TCC_Basic;
153 case Intrinsic::annotation:
154 case Intrinsic::assume:
155 case Intrinsic::sideeffect:
156 case Intrinsic::dbg_declare:
157 case Intrinsic::dbg_value:
158 case Intrinsic::invariant_start:
159 case Intrinsic::invariant_end:
160 case Intrinsic::lifetime_start:
161 case Intrinsic::lifetime_end:
162 case Intrinsic::objectsize:
163 case Intrinsic::ptr_annotation:
164 case Intrinsic::var_annotation:
165 case Intrinsic::experimental_gc_result:
166 case Intrinsic::experimental_gc_relocate:
167 case Intrinsic::coro_alloc:
168 case Intrinsic::coro_begin:
169 case Intrinsic::coro_free:
170 case Intrinsic::coro_end:
171 case Intrinsic::coro_frame:
172 case Intrinsic::coro_size:
173 case Intrinsic::coro_suspend:
174 case Intrinsic::coro_param:
175 case Intrinsic::coro_subfn_addr:
176 // These intrinsics don't actually represent code after lowering.
177 return TTI::TCC_Free;
181 bool hasBranchDivergence() { return false; }
183 bool isSourceOfDivergence(const Value *V) { return false; }
185 bool isAlwaysUniform(const Value *V) { return false; }
187 unsigned getFlatAddressSpace () {
191 bool isLoweredToCall(const Function *F) {
192 assert(F && "A concrete function must be provided to this routine.");
194 // FIXME: These should almost certainly not be handled here, and instead
195 // handled with the help of TLI or the target itself. This was largely
196 // ported from existing analysis heuristics here so that such refactorings
197 // can take place in the future.
199 if (F->isIntrinsic())
202 if (F->hasLocalLinkage() || !F->hasName())
205 StringRef Name = F->getName();
207 // These will all likely lower to a single selection DAG node.
208 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
209 Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
210 Name == "fmin" || Name == "fminf" || Name == "fminl" ||
211 Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
212 Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
213 Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
216 // These are all likely to be optimized into something smaller.
217 if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
218 Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
219 Name == "floorf" || Name == "ceil" || Name == "round" ||
220 Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
227 void getUnrollingPreferences(Loop *, ScalarEvolution &,
228 TTI::UnrollingPreferences &) {}
230 bool isLegalAddImmediate(int64_t Imm) { return false; }
232 bool isLegalICmpImmediate(int64_t Imm) { return false; }
234 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
235 bool HasBaseReg, int64_t Scale,
236 unsigned AddrSpace, Instruction *I = nullptr) {
237 // Guess that only reg and reg+reg addressing is allowed. This heuristic is
238 // taken from the implementation of LSR.
239 return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
242 bool isLSRCostLess(TTI::LSRCost &C1, TTI::LSRCost &C2) {
243 return std::tie(C1.NumRegs, C1.AddRecCost, C1.NumIVMuls, C1.NumBaseAdds,
244 C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
245 std::tie(C2.NumRegs, C2.AddRecCost, C2.NumIVMuls, C2.NumBaseAdds,
246 C2.ScaleCost, C2.ImmCost, C2.SetupCost);
249 bool isLegalMaskedStore(Type *DataType) { return false; }
251 bool isLegalMaskedLoad(Type *DataType) { return false; }
253 bool isLegalMaskedScatter(Type *DataType) { return false; }
255 bool isLegalMaskedGather(Type *DataType) { return false; }
257 bool hasDivRemOp(Type *DataType, bool IsSigned) { return false; }
259 bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) { return false; }
261 bool prefersVectorizedAddressing() { return true; }
263 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
264 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
265 // Guess that all legal addressing mode are free.
266 if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
272 bool LSRWithInstrQueries() { return false; }
274 bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
276 bool isProfitableToHoist(Instruction *I) { return true; }
278 bool isTypeLegal(Type *Ty) { return false; }
280 unsigned getJumpBufAlignment() { return 0; }
282 unsigned getJumpBufSize() { return 0; }
284 bool shouldBuildLookupTables() { return true; }
285 bool shouldBuildLookupTablesForConstant(Constant *C) { return true; }
287 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
291 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
292 unsigned VF) { return 0; }
294 bool supportsEfficientVectorElementLoadStore() { return false; }
296 bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
298 const TTI::MemCmpExpansionOptions *enableMemCmpExpansion(
299 bool IsZeroCmp) const {
303 bool enableInterleavedAccessVectorization() { return false; }
305 bool isFPVectorizationPotentiallyUnsafe() { return false; }
307 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
309 unsigned AddressSpace,
311 bool *Fast) { return false; }
313 TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
314 return TTI::PSK_Software;
317 bool haveFastSqrt(Type *Ty) { return false; }
319 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) { return true; }
321 unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
323 int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
328 unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
330 unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
332 return TTI::TCC_Free;
335 unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
337 return TTI::TCC_Free;
340 unsigned getNumberOfRegisters(bool Vector) { return 8; }
342 unsigned getRegisterBitWidth(bool Vector) const { return 32; }
344 unsigned getMinVectorRegisterBitWidth() { return 128; }
347 shouldConsiderAddressTypePromotion(const Instruction &I,
348 bool &AllowPromotionWithoutCommonHeader) {
349 AllowPromotionWithoutCommonHeader = false;
353 unsigned getCacheLineSize() { return 0; }
355 llvm::Optional<unsigned> getCacheSize(TargetTransformInfo::CacheLevel Level) {
357 case TargetTransformInfo::CacheLevel::L1D:
359 case TargetTransformInfo::CacheLevel::L2D:
360 return llvm::Optional<unsigned>();
363 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
366 llvm::Optional<unsigned> getCacheAssociativity(
367 TargetTransformInfo::CacheLevel Level) {
369 case TargetTransformInfo::CacheLevel::L1D:
371 case TargetTransformInfo::CacheLevel::L2D:
372 return llvm::Optional<unsigned>();
375 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
378 unsigned getPrefetchDistance() { return 0; }
380 unsigned getMinPrefetchStride() { return 1; }
382 unsigned getMaxPrefetchIterationsAhead() { return UINT_MAX; }
384 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
386 unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
387 TTI::OperandValueKind Opd1Info,
388 TTI::OperandValueKind Opd2Info,
389 TTI::OperandValueProperties Opd1PropInfo,
390 TTI::OperandValueProperties Opd2PropInfo,
391 ArrayRef<const Value *> Args) {
395 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
400 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
401 const Instruction *I) { return 1; }
403 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
404 VectorType *VecTy, unsigned Index) {
408 unsigned getCFInstrCost(unsigned Opcode) { return 1; }
410 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
411 const Instruction *I) {
415 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
419 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
420 unsigned AddressSpace, const Instruction *I) {
424 unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
425 unsigned AddressSpace) {
429 unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
431 unsigned Alignment) {
435 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
437 ArrayRef<unsigned> Indices,
439 unsigned AddressSpace) {
443 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
444 ArrayRef<Type *> Tys, FastMathFlags FMF,
445 unsigned ScalarizationCostPassed) {
448 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
449 ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) {
453 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
457 unsigned getNumberOfParts(Type *Tp) { return 0; }
459 unsigned getAddressComputationCost(Type *Tp, ScalarEvolution *,
464 unsigned getArithmeticReductionCost(unsigned, Type *, bool) { return 1; }
466 unsigned getMinMaxReductionCost(Type *, Type *, bool, bool) { return 1; }
468 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
470 bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
474 unsigned getAtomicMemIntrinsicMaxElementSize() const {
475 // Note for overrides: You must ensure for all element unordered-atomic
476 // memory intrinsics that all power-of-2 element sizes up to, and
477 // including, the return value of this method have a corresponding
478 // runtime lib call. These runtime lib call definitions can be found
479 // in RuntimeLibcalls.h
483 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
484 Type *ExpectedType) {
488 Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
489 unsigned SrcAlign, unsigned DestAlign) const {
490 return Type::getInt8Ty(Context);
493 void getMemcpyLoopResidualLoweringType(SmallVectorImpl<Type *> &OpsOut,
494 LLVMContext &Context,
495 unsigned RemainingBytes,
497 unsigned DestAlign) const {
498 for (unsigned i = 0; i != RemainingBytes; ++i)
499 OpsOut.push_back(Type::getInt8Ty(Context));
502 bool areInlineCompatible(const Function *Caller,
503 const Function *Callee) const {
504 return (Caller->getFnAttribute("target-cpu") ==
505 Callee->getFnAttribute("target-cpu")) &&
506 (Caller->getFnAttribute("target-features") ==
507 Callee->getFnAttribute("target-features"));
510 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { return 128; }
512 bool isLegalToVectorizeLoad(LoadInst *LI) const { return true; }
514 bool isLegalToVectorizeStore(StoreInst *SI) const { return true; }
516 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
518 unsigned AddrSpace) const {
522 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
524 unsigned AddrSpace) const {
528 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
529 unsigned ChainSizeInBytes,
530 VectorType *VecTy) const {
534 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
535 unsigned ChainSizeInBytes,
536 VectorType *VecTy) const {
540 bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
541 TTI::ReductionFlags Flags) const {
545 bool shouldExpandReduction(const IntrinsicInst *II) const {
550 // Obtain the minimum required size to hold the value (without the sign)
551 // In case of a vector it returns the min required size for one element.
552 unsigned minRequiredElementSize(const Value* Val, bool &isSigned) {
553 if (isa<ConstantDataVector>(Val) || isa<ConstantVector>(Val)) {
554 const auto* VectorValue = cast<Constant>(Val);
556 // In case of a vector need to pick the max between the min
557 // required size for each element
558 auto *VT = cast<VectorType>(Val->getType());
560 // Assume unsigned elements
563 // The max required size is the total vector width divided by num
564 // of elements in the vector
565 unsigned MaxRequiredSize = VT->getBitWidth() / VT->getNumElements();
567 unsigned MinRequiredSize = 0;
568 for(unsigned i = 0, e = VT->getNumElements(); i < e; ++i) {
569 if (auto* IntElement =
570 dyn_cast<ConstantInt>(VectorValue->getAggregateElement(i))) {
571 bool signedElement = IntElement->getValue().isNegative();
572 // Get the element min required size.
573 unsigned ElementMinRequiredSize =
574 IntElement->getValue().getMinSignedBits() - 1;
575 // In case one element is signed then all the vector is signed.
576 isSigned |= signedElement;
577 // Save the max required bit size between all the elements.
578 MinRequiredSize = std::max(MinRequiredSize, ElementMinRequiredSize);
581 // not an int constant element
582 return MaxRequiredSize;
585 return MinRequiredSize;
588 if (const auto* CI = dyn_cast<ConstantInt>(Val)) {
589 isSigned = CI->getValue().isNegative();
590 return CI->getValue().getMinSignedBits() - 1;
593 if (const auto* Cast = dyn_cast<SExtInst>(Val)) {
595 return Cast->getSrcTy()->getScalarSizeInBits() - 1;
598 if (const auto* Cast = dyn_cast<ZExtInst>(Val)) {
600 return Cast->getSrcTy()->getScalarSizeInBits();
604 return Val->getType()->getScalarSizeInBits();
607 bool isStridedAccess(const SCEV *Ptr) {
608 return Ptr && isa<SCEVAddRecExpr>(Ptr);
611 const SCEVConstant *getConstantStrideStep(ScalarEvolution *SE,
613 if (!isStridedAccess(Ptr))
615 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ptr);
616 return dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*SE));
619 bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr,
620 int64_t MergeDistance) {
621 const SCEVConstant *Step = getConstantStrideStep(SE, Ptr);
624 APInt StrideVal = Step->getAPInt();
625 if (StrideVal.getBitWidth() > 64)
627 // FIXME: Need to take absolute value for negative stride case.
628 return StrideVal.getSExtValue() < MergeDistance;
632 /// \brief CRTP base class for use as a mix-in that aids implementing
633 /// a TargetTransformInfo-compatible class.
634 template <typename T>
635 class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
637 typedef TargetTransformInfoImplBase BaseT;
640 explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
643 using BaseT::getCallCost;
645 unsigned getCallCost(const Function *F, int NumArgs) {
646 assert(F && "A concrete function must be provided to this routine.");
649 // Set the argument number to the number of explicit arguments in the
651 NumArgs = F->arg_size();
653 if (Intrinsic::ID IID = F->getIntrinsicID()) {
654 FunctionType *FTy = F->getFunctionType();
655 SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
656 return static_cast<T *>(this)
657 ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
660 if (!static_cast<T *>(this)->isLoweredToCall(F))
661 return TTI::TCC_Basic; // Give a basic cost if it will be lowered
664 return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
667 unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
668 // Simply delegate to generic handling of the call.
669 // FIXME: We should use instsimplify or something else to catch calls which
670 // will constant fold with these arguments.
671 return static_cast<T *>(this)->getCallCost(F, Arguments.size());
674 using BaseT::getGEPCost;
676 int getGEPCost(Type *PointeeType, const Value *Ptr,
677 ArrayRef<const Value *> Operands) {
678 const GlobalValue *BaseGV = nullptr;
679 if (Ptr != nullptr) {
680 // TODO: will remove this when pointers have an opaque type.
681 assert(Ptr->getType()->getScalarType()->getPointerElementType() ==
683 "explicit pointee type doesn't match operand's pointee type");
684 BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
686 bool HasBaseReg = (BaseGV == nullptr);
688 auto PtrSizeBits = DL.getPointerTypeSizeInBits(Ptr->getType());
689 APInt BaseOffset(PtrSizeBits, 0);
692 auto GTI = gep_type_begin(PointeeType, Operands);
693 Type *TargetType = nullptr;
695 // Handle the case where the GEP instruction has a single operand,
696 // the basis, therefore TargetType is a nullptr.
697 if (Operands.empty())
698 return !BaseGV ? TTI::TCC_Free : TTI::TCC_Basic;
700 for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
701 TargetType = GTI.getIndexedType();
702 // We assume that the cost of Scalar GEP with constant index and the
703 // cost of Vector GEP with splat constant index are the same.
704 const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
706 if (auto Splat = getSplatValue(*I))
707 ConstIdx = dyn_cast<ConstantInt>(Splat);
708 if (StructType *STy = GTI.getStructTypeOrNull()) {
709 // For structures the index is always splat or scalar constant
710 assert(ConstIdx && "Unexpected GEP index");
711 uint64_t Field = ConstIdx->getZExtValue();
712 BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
714 int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
717 ConstIdx->getValue().sextOrTrunc(PtrSizeBits) * ElementSize;
719 // Needs scale register.
721 // No addressing mode takes two scale registers.
722 return TTI::TCC_Basic;
728 // Assumes the address space is 0 when Ptr is nullptr.
730 (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
732 if (static_cast<T *>(this)->isLegalAddressingMode(
733 TargetType, const_cast<GlobalValue *>(BaseGV),
734 BaseOffset.sextOrTrunc(64).getSExtValue(), HasBaseReg, Scale, AS))
735 return TTI::TCC_Free;
736 return TTI::TCC_Basic;
739 using BaseT::getIntrinsicCost;
741 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
742 ArrayRef<const Value *> Arguments) {
743 // Delegate to the generic intrinsic handling code. This mostly provides an
744 // opportunity for targets to (for example) special case the cost of
745 // certain intrinsics based on constants used as arguments.
746 SmallVector<Type *, 8> ParamTys;
747 ParamTys.reserve(Arguments.size());
748 for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
749 ParamTys.push_back(Arguments[Idx]->getType());
750 return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
753 unsigned getUserCost(const User *U, ArrayRef<const Value *> Operands) {
755 return TTI::TCC_Free; // Model all PHI nodes as free.
757 // Static alloca doesn't generate target instructions.
758 if (auto *A = dyn_cast<AllocaInst>(U))
759 if (A->isStaticAlloca())
760 return TTI::TCC_Free;
762 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
763 return static_cast<T *>(this)->getGEPCost(GEP->getSourceElementType(),
764 GEP->getPointerOperand(),
765 Operands.drop_front());
768 if (auto CS = ImmutableCallSite(U)) {
769 const Function *F = CS.getCalledFunction();
771 // Just use the called value type.
772 Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
773 return static_cast<T *>(this)
774 ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
777 SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
778 return static_cast<T *>(this)->getCallCost(F, Arguments);
781 if (const CastInst *CI = dyn_cast<CastInst>(U)) {
782 // Result of a cmp instruction is often extended (to be used by other
783 // cmp instructions, logical or return instructions). These are usually
784 // nop on most sane targets.
785 if (isa<CmpInst>(CI->getOperand(0)))
786 return TTI::TCC_Free;
787 if (isa<SExtInst>(CI) || isa<ZExtInst>(CI) || isa<FPExtInst>(CI))
788 return static_cast<T *>(this)->getExtCost(CI, Operands.back());
791 return static_cast<T *>(this)->getOperationCost(
792 Operator::getOpcode(U), U->getType(),
793 U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);
796 int getInstructionLatency(const Instruction *I) {
797 SmallVector<const Value *, 4> Operands(I->value_op_begin(),
799 if (getUserCost(I, Operands) == TTI::TCC_Free)
802 if (isa<LoadInst>(I))
805 Type *DstTy = I->getType();
807 // Usually an intrinsic is a simple instruction.
808 // A real function call is much slower.
809 if (auto *CI = dyn_cast<CallInst>(I)) {
810 const Function *F = CI->getCalledFunction();
811 if (!F || static_cast<T *>(this)->isLoweredToCall(F))
813 // Some intrinsics return a value and a flag, we use the value type
814 // to decide its latency.
815 if (StructType* StructTy = dyn_cast<StructType>(DstTy))
816 DstTy = StructTy->getElementType(0);
817 // Fall through to simple instructions.
820 if (VectorType *VectorTy = dyn_cast<VectorType>(DstTy))
821 DstTy = VectorTy->getElementType();
822 if (DstTy->isFloatingPointTy())