#ifndef LLVM_CODEGEN_BASICTTIIMPL_H
#define LLVM_CODEGEN_BASICTTIIMPL_H
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/TargetTransformInfoImpl.h"
#include "llvm/CodeGen/ISDOpcodes.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MachineValueType.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <limits>
#include <utility>
namespace llvm {
class Function;
class GlobalValue;
class LLVMContext;
class ScalarEvolution;
class SCEV;
class TargetMachine;
extern cl::opt<unsigned> PartialUnrollingThreshold;
template <typename T>
class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
private:
using BaseT = TargetTransformInfoImplCRTPBase<T>;
using TTI = TargetTransformInfo;
T *thisT() { return static_cast<T *>(this); }
InstructionCost getBroadcastShuffleOverhead(FixedVectorType *VTy) {
InstructionCost Cost = 0;
Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, VTy, 0);
for (int i = 0, e = VTy->getNumElements(); i < e; ++i) {
Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, VTy, i);
}
return Cost;
}
InstructionCost getPermuteShuffleOverhead(FixedVectorType *VTy) {
InstructionCost Cost = 0;
for (int i = 0, e = VTy->getNumElements(); i < e; ++i) {
Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, VTy, i);
Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, VTy, i);
}
return Cost;
}
InstructionCost getExtractSubvectorOverhead(VectorType *VTy, int Index,
FixedVectorType *SubVTy) {
assert(VTy && SubVTy &&
"Can only extract subvectors from vectors");
int NumSubElts = SubVTy->getNumElements();
assert((!isa<FixedVectorType>(VTy) ||
(Index + NumSubElts) <=
(int)cast<FixedVectorType>(VTy)->getNumElements()) &&
"SK_ExtractSubvector index out of range");
InstructionCost Cost = 0;
for (int i = 0; i != NumSubElts; ++i) {
Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, VTy,
i + Index);
Cost +=
thisT()->getVectorInstrCost(Instruction::InsertElement, SubVTy, i);
}
return Cost;
}
InstructionCost getInsertSubvectorOverhead(VectorType *VTy, int Index,
FixedVectorType *SubVTy) {
assert(VTy && SubVTy &&
"Can only insert subvectors into vectors");
int NumSubElts = SubVTy->getNumElements();
assert((!isa<FixedVectorType>(VTy) ||
(Index + NumSubElts) <=
(int)cast<FixedVectorType>(VTy)->getNumElements()) &&
"SK_InsertSubvector index out of range");
InstructionCost Cost = 0;
for (int i = 0; i != NumSubElts; ++i) {
Cost +=
thisT()->getVectorInstrCost(Instruction::ExtractElement, SubVTy, i);
Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, VTy,
i + Index);
}
return Cost;
}
const TargetSubtargetInfo *getST() const {
return static_cast<const T *>(this)->getST();
}
const TargetLoweringBase *getTLI() const {
return static_cast<const T *>(this)->getTLI();
}
static ISD::MemIndexedMode getISDIndexedMode(TTI::MemIndexedMode M) {
switch (M) {
case TTI::MIM_Unindexed:
return ISD::UNINDEXED;
case TTI::MIM_PreInc:
return ISD::PRE_INC;
case TTI::MIM_PreDec:
return ISD::PRE_DEC;
case TTI::MIM_PostInc:
return ISD::POST_INC;
case TTI::MIM_PostDec:
return ISD::POST_DEC;
}
llvm_unreachable("Unexpected MemIndexedMode");
}
InstructionCost getCommonMaskedMemoryOpCost(unsigned Opcode, Type *DataTy,
Align Alignment,
bool VariableMask,
bool IsGatherScatter,
TTI::TargetCostKind CostKind) {
if (isa<ScalableVectorType>(DataTy))
return InstructionCost::getInvalid();
auto *VT = cast<FixedVectorType>(DataTy);
InstructionCost AddrExtractCost =
IsGatherScatter
? getVectorInstrCost(Instruction::ExtractElement,
FixedVectorType::get(
PointerType::get(VT->getElementType(), 0),
VT->getNumElements()),
-1)
: 0;
InstructionCost LoadCost =
VT->getNumElements() *
(AddrExtractCost +
getMemoryOpCost(Opcode, VT->getElementType(), Alignment, 0, CostKind));
InstructionCost PackingCost = getScalarizationOverhead(
VT, Opcode != Instruction::Store, Opcode == Instruction::Store);
InstructionCost ConditionalCost = 0;
if (VariableMask) {
ConditionalCost =
VT->getNumElements() *
(getVectorInstrCost(
Instruction::ExtractElement,
FixedVectorType::get(Type::getInt1Ty(DataTy->getContext()),
VT->getNumElements()),
-1) +
getCFInstrCost(Instruction::Br, CostKind) +
getCFInstrCost(Instruction::PHI, CostKind));
}
return LoadCost + PackingCost + ConditionalCost;
}
protected:
explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
: BaseT(DL) {}
virtual ~BasicTTIImplBase() = default;
using TargetTransformInfoImplBase::DL;
public:
bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth,
unsigned AddressSpace, Align Alignment,
bool *Fast) const {
EVT E = EVT::getIntegerVT(Context, BitWidth);
return getTLI()->allowsMisalignedMemoryAccesses(
E, AddressSpace, Alignment, MachineMemOperand::MONone, Fast);
}
bool hasBranchDivergence() { return false; }
bool useGPUDivergenceAnalysis() { return false; }
bool isSourceOfDivergence(const Value *V) { return false; }
bool isAlwaysUniform(const Value *V) { return false; }
unsigned getFlatAddressSpace() {
return -1;
}
bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
Intrinsic::ID IID) const {
return false;
}
bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const {
return getTLI()->getTargetMachine().isNoopAddrSpaceCast(FromAS, ToAS);
}
unsigned getAssumedAddrSpace(const Value *V) const {
return getTLI()->getTargetMachine().getAssumedAddrSpace(V);
}
std::pair<const Value *, unsigned>
getPredicatedAddrSpace(const Value *V) const {
return getTLI()->getTargetMachine().getPredicatedAddrSpace(V);
}
Value *rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV,
Value *NewV) const {
return nullptr;
}
bool isLegalAddImmediate(int64_t imm) {
return getTLI()->isLegalAddImmediate(imm);
}
bool isLegalICmpImmediate(int64_t imm) {
return getTLI()->isLegalICmpImmediate(imm);
}
bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
bool HasBaseReg, int64_t Scale,
unsigned AddrSpace, Instruction *I = nullptr) {
TargetLoweringBase::AddrMode AM;
AM.BaseGV = BaseGV;
AM.BaseOffs = BaseOffset;
AM.HasBaseReg = HasBaseReg;
AM.Scale = Scale;
return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
}
unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
Type *ScalarValTy) const {
auto &&IsSupportedByTarget = [this, ScalarMemTy, ScalarValTy](unsigned VF) {
auto *SrcTy = FixedVectorType::get(ScalarMemTy, VF / 2);
EVT VT = getTLI()->getValueType(DL, SrcTy);
if (getTLI()->isOperationLegal(ISD::STORE, VT) ||
getTLI()->isOperationCustom(ISD::STORE, VT))
return true;
EVT ValVT =
getTLI()->getValueType(DL, FixedVectorType::get(ScalarValTy, VF / 2));
EVT LegalizedVT =
getTLI()->getTypeToTransformTo(ScalarMemTy->getContext(), VT);
return getTLI()->isTruncStoreLegal(LegalizedVT, ValVT);
};
while (VF > 2 && IsSupportedByTarget(VF))
VF /= 2;
return VF;
}
bool isIndexedLoadLegal(TTI::MemIndexedMode M, Type *Ty,
const DataLayout &DL) const {
EVT VT = getTLI()->getValueType(DL, Ty);
return getTLI()->isIndexedLoadLegal(getISDIndexedMode(M), VT);
}
bool isIndexedStoreLegal(TTI::MemIndexedMode M, Type *Ty,
const DataLayout &DL) const {
EVT VT = getTLI()->getValueType(DL, Ty);
return getTLI()->isIndexedStoreLegal(getISDIndexedMode(M), VT);
}
bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2) {
return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
}
bool isNumRegsMajorCostOfLSR() {
return TargetTransformInfoImplBase::isNumRegsMajorCostOfLSR();
}
bool isProfitableLSRChainElement(Instruction *I) {
return TargetTransformInfoImplBase::isProfitableLSRChainElement(I);
}
InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
int64_t BaseOffset, bool HasBaseReg,
int64_t Scale, unsigned AddrSpace) {
TargetLoweringBase::AddrMode AM;
AM.BaseGV = BaseGV;
AM.BaseOffs = BaseOffset;
AM.HasBaseReg = HasBaseReg;
AM.Scale = Scale;
return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
}
bool isTruncateFree(Type *Ty1, Type *Ty2) {
return getTLI()->isTruncateFree(Ty1, Ty2);
}
bool isProfitableToHoist(Instruction *I) {
return getTLI()->isProfitableToHoist(I);
}
bool useAA() const { return getST()->useAA(); }
bool isTypeLegal(Type *Ty) {
EVT VT = getTLI()->getValueType(DL, Ty);
return getTLI()->isTypeLegal(VT);
}
unsigned getRegUsageForType(Type *Ty) {
EVT ETy = getTLI()->getValueType(DL, Ty);
return getTLI()->getNumRegisters(Ty->getContext(), ETy);
}
InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr,
ArrayRef<const Value *> Operands,
TTI::TargetCostKind CostKind) {
return BaseT::getGEPCost(PointeeType, Ptr, Operands, CostKind);
}
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
unsigned &JumpTableSize,
ProfileSummaryInfo *PSI,
BlockFrequencyInfo *BFI) {
unsigned N = SI.getNumCases();
const TargetLoweringBase *TLI = getTLI();
const DataLayout &DL = this->getDataLayout();
JumpTableSize = 0;
bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
if (N < 1 || (!IsJTAllowed && DL.getIndexSizeInBits(0u) < N))
return N;
APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
APInt MinCaseVal = MaxCaseVal;
for (auto CI : SI.cases()) {
const APInt &CaseVal = CI.getCaseValue()->getValue();
if (CaseVal.sgt(MaxCaseVal))
MaxCaseVal = CaseVal;
if (CaseVal.slt(MinCaseVal))
MinCaseVal = CaseVal;
}
if (N <= DL.getIndexSizeInBits(0u)) {
SmallPtrSet<const BasicBlock *, 4> Dests;
for (auto I : SI.cases())
Dests.insert(I.getCaseSuccessor());
if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
DL))
return 1;
}
if (IsJTAllowed) {
if (N < 2 || N < TLI->getMinimumJumpTableEntries())
return N;
uint64_t Range =
(MaxCaseVal - MinCaseVal)
.getLimitedValue(std::numeric_limits<uint64_t>::max() - 1) + 1;
if (TLI->isSuitableForJumpTable(&SI, N, Range, PSI, BFI)) {
JumpTableSize = Range;
return 1;
}
}
return N;
}
bool shouldBuildLookupTables() {
const TargetLoweringBase *TLI = getTLI();
return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
}
bool shouldBuildRelLookupTables() const {
const TargetMachine &TM = getTLI()->getTargetMachine();
if (!TM.isPositionIndependent())
return false;
if (TM.getCodeModel() == CodeModel::Medium ||
TM.getCodeModel() == CodeModel::Large)
return false;
Triple TargetTriple = TM.getTargetTriple();
if (!TargetTriple.isArch64Bit())
return false;
if (TargetTriple.getArch() == Triple::aarch64 && TargetTriple.isOSDarwin())
return false;
return true;
}
bool haveFastSqrt(Type *Ty) {
const TargetLoweringBase *TLI = getTLI();
EVT VT = TLI->getValueType(DL, Ty);
return TLI->isTypeLegal(VT) &&
TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
}
bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
return true;
}
InstructionCost getFPOpCost(Type *Ty) {
const TargetLoweringBase *TLI = getTLI();
EVT VT = TLI->getValueType(DL, Ty);
if (TLI->isOperationLegalOrCustomOrPromote(ISD::FADD, VT))
return TargetTransformInfo::TCC_Basic;
return TargetTransformInfo::TCC_Expensive;
}
unsigned getInliningThresholdMultiplier() { return 1; }
unsigned adjustInliningThreshold(const CallBase *CB) { return 0; }
int getInlinerVectorBonusPercent() { return 150; }
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
TTI::UnrollingPreferences &UP,
OptimizationRemarkEmitter *ORE) {
unsigned MaxOps;
const TargetSubtargetInfo *ST = getST();
if (PartialUnrollingThreshold.getNumOccurrences() > 0)
MaxOps = PartialUnrollingThreshold;
else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
else
return;
for (BasicBlock *BB : L->blocks()) {
for (Instruction &I : *BB) {
if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
if (!thisT()->isLoweredToCall(F))
continue;
}
if (ORE) {
ORE->emit([&]() {
return OptimizationRemark("TTI", "DontUnroll", L->getStartLoc(),
L->getHeader())
<< "advising against unrolling the loop because it "
"contains a "
<< ore::NV("Call", &I);
});
}
return;
}
}
}
UP.Partial = UP.Runtime = UP.UpperBound = true;
UP.PartialThreshold = MaxOps;
UP.OptSizeThreshold = 0;
UP.PartialOptSizeThreshold = 0;
UP.BEInsns = 2;
}
void getPeelingPreferences(Loop *L, ScalarEvolution &SE,
TTI::PeelingPreferences &PP) {
PP.PeelCount = 0;
PP.AllowPeeling = true;
PP.AllowLoopNestsPeeling = false;
PP.PeelProfiledIterations = true;
}
bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
AssumptionCache &AC,
TargetLibraryInfo *LibInfo,
HardwareLoopInfo &HWLoopInfo) {
return BaseT::isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo);
}
bool preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
AssumptionCache &AC, TargetLibraryInfo *TLI,
DominatorTree *DT,
LoopVectorizationLegality *LVL) {
return BaseT::preferPredicateOverEpilogue(L, LI, SE, AC, TLI, DT, LVL);
}
PredicationStyle emitGetActiveLaneMask() {
return BaseT::emitGetActiveLaneMask();
}
Optional<Instruction *> instCombineIntrinsic(InstCombiner &IC,
IntrinsicInst &II) {
return BaseT::instCombineIntrinsic(IC, II);
}
Optional<Value *> simplifyDemandedUseBitsIntrinsic(InstCombiner &IC,
IntrinsicInst &II,
APInt DemandedMask,
KnownBits &Known,
bool &KnownBitsComputed) {
return BaseT::simplifyDemandedUseBitsIntrinsic(IC, II, DemandedMask, Known,
KnownBitsComputed);
}
Optional<Value *> simplifyDemandedVectorEltsIntrinsic(
InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
APInt &UndefElts2, APInt &UndefElts3,
std::function<void(Instruction *, unsigned, APInt, APInt &)>
SimplifyAndSetOp) {
return BaseT::simplifyDemandedVectorEltsIntrinsic(
IC, II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
SimplifyAndSetOp);
}
InstructionCost getInstructionLatency(const Instruction *I) {
if (isa<LoadInst>(I))
return getST()->getSchedModel().DefaultLoadLatency;
return BaseT::getInstructionLatency(I);
}
virtual Optional<unsigned>
getCacheSize(TargetTransformInfo::CacheLevel Level) const {
return Optional<unsigned>(
getST()->getCacheSize(static_cast<unsigned>(Level)));
}
virtual Optional<unsigned>
getCacheAssociativity(TargetTransformInfo::CacheLevel Level) const {
Optional<unsigned> TargetResult =
getST()->getCacheAssociativity(static_cast<unsigned>(Level));
if (TargetResult)
return TargetResult;
return BaseT::getCacheAssociativity(Level);
}
virtual unsigned getCacheLineSize() const {
return getST()->getCacheLineSize();
}
virtual unsigned getPrefetchDistance() const {
return getST()->getPrefetchDistance();
}
virtual unsigned getMinPrefetchStride(unsigned NumMemAccesses,
unsigned NumStridedMemAccesses,
unsigned NumPrefetches,
bool HasCall) const {
return getST()->getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
NumPrefetches, HasCall);
}
virtual unsigned getMaxPrefetchIterationsAhead() const {
return getST()->getMaxPrefetchIterationsAhead();
}
virtual bool enableWritePrefetching() const {
return getST()->enableWritePrefetching();
}
TypeSize getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
return TypeSize::getFixed(32);
}
Optional<unsigned> getMaxVScale() const { return None; }
Optional<unsigned> getVScaleForTuning() const { return None; }
InstructionCost getScalarizationOverhead(VectorType *InTy,
const APInt &DemandedElts,
bool Insert, bool Extract) {
if (isa<ScalableVectorType>(InTy))
return InstructionCost::getInvalid();
auto *Ty = cast<FixedVectorType>(InTy);
assert(DemandedElts.getBitWidth() == Ty->getNumElements() &&
"Vector size mismatch");
InstructionCost Cost = 0;
for (int i = 0, e = Ty->getNumElements(); i < e; ++i) {
if (!DemandedElts[i])
continue;
if (Insert)
Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, Ty, i);
if (Extract)
Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
}
return Cost;
}
InstructionCost getScalarizationOverhead(VectorType *InTy, bool Insert,
bool Extract) {
if (isa<ScalableVectorType>(InTy))
return InstructionCost::getInvalid();
auto *Ty = cast<FixedVectorType>(InTy);
APInt DemandedElts = APInt::getAllOnes(Ty->getNumElements());
return thisT()->getScalarizationOverhead(Ty, DemandedElts, Insert, Extract);
}
InstructionCost getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
ArrayRef<Type *> Tys) {
assert(Args.size() == Tys.size() && "Expected matching Args and Tys");
InstructionCost Cost = 0;
SmallPtrSet<const Value*, 4> UniqueOperands;
for (int I = 0, E = Args.size(); I != E; I++) {
const Value *A = Args[I];
Type *Ty = Tys[I];
if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy() &&
!Ty->isPtrOrPtrVectorTy())
continue;
if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
if (auto *VecTy = dyn_cast<VectorType>(Ty))
Cost += getScalarizationOverhead(VecTy, false, true);
}
}
return Cost;
}
InstructionCost getScalarizationOverhead(VectorType *RetTy,
ArrayRef<const Value *> Args,
ArrayRef<Type *> Tys) {
InstructionCost Cost = getScalarizationOverhead(RetTy, true, false);
if (!Args.empty())
Cost += getOperandsScalarizationOverhead(Args, Tys);
else
Cost += getScalarizationOverhead(RetTy, false, true);
return Cost;
}
unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
InstructionCost getArithmeticInstrCost(
unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
ArrayRef<const Value *> Args = ArrayRef<const Value *>(),
const Instruction *CxtI = nullptr) {
const TargetLoweringBase *TLI = getTLI();
int ISD = TLI->InstructionOpcodeToISD(Opcode);
assert(ISD && "Invalid opcode");
if (CostKind != TTI::TCK_RecipThroughput)
return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind,
Opd1Info, Opd2Info,
Opd1PropInfo, Opd2PropInfo,
Args, CxtI);
std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
bool IsFloat = Ty->isFPOrFPVectorTy();
InstructionCost OpCost = (IsFloat ? 2 : 1);
if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
return LT.first * OpCost;
}
if (!TLI->isOperationExpand(ISD, LT.second)) {
return LT.first * 2 * OpCost;
}
if (ISD == ISD::UREM || ISD == ISD::SREM) {
bool IsSigned = ISD == ISD::SREM;
if (TLI->isOperationLegalOrCustom(IsSigned ? ISD::SDIVREM : ISD::UDIVREM,
LT.second) ||
TLI->isOperationLegalOrCustom(IsSigned ? ISD::SDIV : ISD::UDIV,
LT.second)) {
unsigned DivOpc = IsSigned ? Instruction::SDiv : Instruction::UDiv;
InstructionCost DivCost = thisT()->getArithmeticInstrCost(
DivOpc, Ty, CostKind, Opd1Info, Opd2Info, Opd1PropInfo,
Opd2PropInfo);
InstructionCost MulCost =
thisT()->getArithmeticInstrCost(Instruction::Mul, Ty, CostKind);
InstructionCost SubCost =
thisT()->getArithmeticInstrCost(Instruction::Sub, Ty, CostKind);
return DivCost + MulCost + SubCost;
}
}
if (isa<ScalableVectorType>(Ty))
return InstructionCost::getInvalid();
if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
InstructionCost Cost = thisT()->getArithmeticInstrCost(
Opcode, VTy->getScalarType(), CostKind, Opd1Info, Opd2Info,
Opd1PropInfo, Opd2PropInfo, Args, CxtI);
SmallVector<Type *> Tys(Args.size(), Ty);
return getScalarizationOverhead(VTy, Args, Tys) +
VTy->getNumElements() * Cost;
}
return OpCost;
}
TTI::ShuffleKind improveShuffleKindFromMask(TTI::ShuffleKind Kind,
ArrayRef<int> Mask) const {
int Limit = Mask.size() * 2;
if (Mask.empty() ||
any_of(Mask, [Limit](int I) { return I >= Limit; }))
return Kind;
switch (Kind) {
case TTI::SK_PermuteSingleSrc:
if (ShuffleVectorInst::isReverseMask(Mask))
return TTI::SK_Reverse;
if (ShuffleVectorInst::isZeroEltSplatMask(Mask))
return TTI::SK_Broadcast;
break;
case TTI::SK_PermuteTwoSrc:
if (ShuffleVectorInst::isSelectMask(Mask))
return TTI::SK_Select;
if (ShuffleVectorInst::isTransposeMask(Mask))
return TTI::SK_Transpose;
break;
case TTI::SK_Select:
case TTI::SK_Reverse:
case TTI::SK_Broadcast:
case TTI::SK_Transpose:
case TTI::SK_InsertSubvector:
case TTI::SK_ExtractSubvector:
case TTI::SK_Splice:
break;
}
return Kind;
}
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
ArrayRef<int> Mask, int Index,
VectorType *SubTp,
ArrayRef<const Value *> Args = None) {
switch (improveShuffleKindFromMask(Kind, Mask)) {
case TTI::SK_Broadcast:
if (auto *FVT = dyn_cast<FixedVectorType>(Tp))
return getBroadcastShuffleOverhead(FVT);
return InstructionCost::getInvalid();
case TTI::SK_Select:
case TTI::SK_Splice:
case TTI::SK_Reverse:
case TTI::SK_Transpose:
case TTI::SK_PermuteSingleSrc:
case TTI::SK_PermuteTwoSrc:
if (auto *FVT = dyn_cast<FixedVectorType>(Tp))
return getPermuteShuffleOverhead(FVT);
return InstructionCost::getInvalid();
case TTI::SK_ExtractSubvector:
return getExtractSubvectorOverhead(Tp, Index,
cast<FixedVectorType>(SubTp));
case TTI::SK_InsertSubvector:
return getInsertSubvectorOverhead(Tp, Index,
cast<FixedVectorType>(SubTp));
}
llvm_unreachable("Unknown TTI::ShuffleKind");
}
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
TTI::CastContextHint CCH,
TTI::TargetCostKind CostKind,
const Instruction *I = nullptr) {
if (BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I) == 0)
return 0;
const TargetLoweringBase *TLI = getTLI();
int ISD = TLI->InstructionOpcodeToISD(Opcode);
assert(ISD && "Invalid opcode");
std::pair<InstructionCost, MVT> SrcLT =
TLI->getTypeLegalizationCost(DL, Src);
std::pair<InstructionCost, MVT> DstLT =
TLI->getTypeLegalizationCost(DL, Dst);
TypeSize SrcSize = SrcLT.second.getSizeInBits();
TypeSize DstSize = DstLT.second.getSizeInBits();
bool IntOrPtrSrc = Src->isIntegerTy() || Src->isPointerTy();
bool IntOrPtrDst = Dst->isIntegerTy() || Dst->isPointerTy();
switch (Opcode) {
default:
break;
case Instruction::Trunc:
if (TLI->isTruncateFree(SrcLT.second, DstLT.second))
return 0;
LLVM_FALLTHROUGH;
case Instruction::BitCast:
if (SrcLT.first == DstLT.first && IntOrPtrSrc == IntOrPtrDst &&
SrcSize == DstSize)
return 0;
break;
case Instruction::FPExt:
if (I && getTLI()->isExtFree(I))
return 0;
break;
case Instruction::ZExt:
if (TLI->isZExtFree(SrcLT.second, DstLT.second))
return 0;
LLVM_FALLTHROUGH;
case Instruction::SExt:
if (I && getTLI()->isExtFree(I))
return 0;
if (CCH == TTI::CastContextHint::Normal) {
EVT ExtVT = EVT::getEVT(Dst);
EVT LoadVT = EVT::getEVT(Src);
unsigned LType =
((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
if (DstLT.first == SrcLT.first &&
TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
return 0;
}
break;
case Instruction::AddrSpaceCast:
if (TLI->isFreeAddrSpaceCast(Src->getPointerAddressSpace(),
Dst->getPointerAddressSpace()))
return 0;
break;
}
auto *SrcVTy = dyn_cast<VectorType>(Src);
auto *DstVTy = dyn_cast<VectorType>(Dst);
if (SrcLT.first == DstLT.first &&
TLI->isOperationLegalOrPromote(ISD, DstLT.second))
return SrcLT.first;
if (!SrcVTy && !DstVTy) {
if (!TLI->isOperationExpand(ISD, DstLT.second))
return 1;
return 4;
}
if (DstVTy && SrcVTy) {
if (SrcLT.first == DstLT.first && SrcSize == DstSize) {
if (Opcode == Instruction::ZExt)
return SrcLT.first;
if (Opcode == Instruction::SExt)
return SrcLT.first * 2;
if (!TLI->isOperationExpand(ISD, DstLT.second))
return SrcLT.first * 1;
}
bool SplitSrc =
TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
TargetLowering::TypeSplitVector;
bool SplitDst =
TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
TargetLowering::TypeSplitVector;
if ((SplitSrc || SplitDst) && SrcVTy->getElementCount().isVector() &&
DstVTy->getElementCount().isVector()) {
Type *SplitDstTy = VectorType::getHalfElementsVectorType(DstVTy);
Type *SplitSrcTy = VectorType::getHalfElementsVectorType(SrcVTy);
T *TTI = static_cast<T *>(this);
InstructionCost SplitCost =
(!SplitSrc || !SplitDst) ? TTI->getVectorSplitCost() : 0;
return SplitCost +
(2 * TTI->getCastInstrCost(Opcode, SplitDstTy, SplitSrcTy, CCH,
CostKind, I));
}
if (isa<ScalableVectorType>(DstVTy))
return InstructionCost::getInvalid();
unsigned Num = cast<FixedVectorType>(DstVTy)->getNumElements();
InstructionCost Cost = thisT()->getCastInstrCost(
Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind, I);
return getScalarizationOverhead(DstVTy, true, true) + Num * Cost;
}
if (Opcode == Instruction::BitCast) {
return (SrcVTy ? getScalarizationOverhead(SrcVTy, false, true) : 0) +
(DstVTy ? getScalarizationOverhead(DstVTy, true, false) : 0);
}
llvm_unreachable("Unhandled cast");
}
InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
VectorType *VecTy, unsigned Index) {
return thisT()->getVectorInstrCost(Instruction::ExtractElement, VecTy,
Index) +
thisT()->getCastInstrCost(Opcode, Dst, VecTy->getElementType(),
TTI::CastContextHint::None,
TTI::TCK_RecipThroughput);
}
InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind,
const Instruction *I = nullptr) {
return BaseT::getCFInstrCost(Opcode, CostKind, I);
}
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
CmpInst::Predicate VecPred,
TTI::TargetCostKind CostKind,
const Instruction *I = nullptr) {
const TargetLoweringBase *TLI = getTLI();
int ISD = TLI->InstructionOpcodeToISD(Opcode);
assert(ISD && "Invalid opcode");
if (CostKind != TTI::TCK_RecipThroughput)
return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
I);
if (ISD == ISD::SELECT) {
assert(CondTy && "CondTy must exist");
if (CondTy->isVectorTy())
ISD = ISD::VSELECT;
}
std::pair<InstructionCost, MVT> LT =
TLI->getTypeLegalizationCost(DL, ValTy);
if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
!TLI->isOperationExpand(ISD, LT.second)) {
return LT.first * 1;
}
if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
if (isa<ScalableVectorType>(ValTy))
return InstructionCost::getInvalid();
unsigned Num = cast<FixedVectorType>(ValVTy)->getNumElements();
if (CondTy)
CondTy = CondTy->getScalarType();
InstructionCost Cost = thisT()->getCmpSelInstrCost(
Opcode, ValVTy->getScalarType(), CondTy, VecPred, CostKind, I);
return getScalarizationOverhead(ValVTy, true, false) + Num * Cost;
}
return 1;
}
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
unsigned Index) {
std::pair<InstructionCost, MVT> LT =
getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
return LT.first;
}
InstructionCost getReplicationShuffleCost(Type *EltTy, int ReplicationFactor,
int VF,
const APInt &DemandedDstElts,
TTI::TargetCostKind CostKind) {
assert(DemandedDstElts.getBitWidth() == (unsigned)VF * ReplicationFactor &&
"Unexpected size of DemandedDstElts.");
InstructionCost Cost;
auto *SrcVT = FixedVectorType::get(EltTy, VF);
auto *ReplicatedVT = FixedVectorType::get(EltTy, VF * ReplicationFactor);
APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedDstElts, VF);
Cost += thisT()->getScalarizationOverhead(SrcVT, DemandedSrcElts,
false,
true);
Cost +=
thisT()->getScalarizationOverhead(ReplicatedVT, DemandedDstElts,
true, false);
return Cost;
}
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src,
MaybeAlign Alignment, unsigned AddressSpace,
TTI::TargetCostKind CostKind,
const Instruction *I = nullptr) {
assert(!Src->isVoidTy() && "Invalid type");
if (getTLI()->getValueType(DL, Src, true) == MVT::Other)
return 4;
std::pair<InstructionCost, MVT> LT =
getTLI()->getTypeLegalizationCost(DL, Src);
InstructionCost Cost = LT.first;
if (CostKind != TTI::TCK_RecipThroughput)
return Cost;
const DataLayout &DL = this->getDataLayout();
if (Src->isVectorTy() &&
TypeSize::isKnownLT(DL.getTypeStoreSizeInBits(Src),
LT.second.getSizeInBits())) {
TargetLowering::LegalizeAction LA = TargetLowering::Expand;
EVT MemVT = getTLI()->getValueType(DL, Src);
if (Opcode == Instruction::Store)
LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
else
LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
Cost += getScalarizationOverhead(cast<VectorType>(Src),
Opcode != Instruction::Store,
Opcode == Instruction::Store);
}
}
return Cost;
}
InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *DataTy,
Align Alignment, unsigned AddressSpace,
TTI::TargetCostKind CostKind) {
return getCommonMaskedMemoryOpCost(Opcode, DataTy, Alignment, true, false,
CostKind);
}
InstructionCost getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
const Value *Ptr, bool VariableMask,
Align Alignment,
TTI::TargetCostKind CostKind,
const Instruction *I = nullptr) {
return getCommonMaskedMemoryOpCost(Opcode, DataTy, Alignment, VariableMask,
true, CostKind);
}
InstructionCost getInterleavedMemoryOpCost(
unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
bool UseMaskForCond = false, bool UseMaskForGaps = false) {
if (isa<ScalableVectorType>(VecTy))
return InstructionCost::getInvalid();
auto *VT = cast<FixedVectorType>(VecTy);
unsigned NumElts = VT->getNumElements();
assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
unsigned NumSubElts = NumElts / Factor;
auto *SubVT = FixedVectorType::get(VT->getElementType(), NumSubElts);
InstructionCost Cost;
if (UseMaskForCond || UseMaskForGaps)
Cost = thisT()->getMaskedMemoryOpCost(Opcode, VecTy, Alignment,
AddressSpace, CostKind);
else
Cost = thisT()->getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace,
CostKind);
MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
unsigned VecTySize = thisT()->getDataLayout().getTypeStoreSize(VecTy);
unsigned VecTyLTSize = VecTyLT.getStoreSize();
if (Cost.isValid() && VecTySize > VecTyLTSize) {
unsigned NumLegalInsts = divideCeil(VecTySize, VecTyLTSize);
unsigned NumEltsPerLegalInst = divideCeil(NumElts, NumLegalInsts);
BitVector UsedInsts(NumLegalInsts, false);
for (unsigned Index : Indices)
for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
Cost = divideCeil(UsedInsts.count() * *Cost.getValue(), NumLegalInsts);
}
assert(Indices.size() <= Factor &&
"Interleaved memory op has too many members");
const APInt DemandedAllSubElts = APInt::getAllOnes(NumSubElts);
const APInt DemandedAllResultElts = APInt::getAllOnes(NumElts);
APInt DemandedLoadStoreElts = APInt::getZero(NumElts);
for (unsigned Index : Indices) {
assert(Index < Factor && "Invalid index for interleaved memory op");
for (unsigned Elm = 0; Elm < NumSubElts; Elm++)
DemandedLoadStoreElts.setBit(Index + Elm * Factor);
}
if (Opcode == Instruction::Load) {
InstructionCost InsSubCost =
thisT()->getScalarizationOverhead(SubVT, DemandedAllSubElts,
true, false);
Cost += Indices.size() * InsSubCost;
Cost +=
thisT()->getScalarizationOverhead(VT, DemandedLoadStoreElts,
false, true);
} else {
InstructionCost ExtSubCost =
thisT()->getScalarizationOverhead(SubVT, DemandedAllSubElts,
false, true);
Cost += ExtSubCost * Indices.size();
Cost += thisT()->getScalarizationOverhead(VT, DemandedLoadStoreElts,
true,
false);
}
if (!UseMaskForCond)
return Cost;
Type *I8Type = Type::getInt8Ty(VT->getContext());
Cost += thisT()->getReplicationShuffleCost(
I8Type, Factor, NumSubElts,
UseMaskForGaps ? DemandedLoadStoreElts : DemandedAllResultElts,
CostKind);
if (UseMaskForGaps) {
auto *MaskVT = FixedVectorType::get(I8Type, NumElts);
Cost += thisT()->getArithmeticInstrCost(BinaryOperator::And, MaskVT,
CostKind);
}
return Cost;
}
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
TTI::TargetCostKind CostKind) {
if (BaseT::getIntrinsicInstrCost(ICA, CostKind) == 0)
return 0;
Intrinsic::ID IID = ICA.getID();
if (Function::isTargetIntrinsic(IID))
return TargetTransformInfo::TCC_Basic;
if (ICA.isTypeBasedOnly())
return getTypeBasedIntrinsicInstrCost(ICA, CostKind);
Type *RetTy = ICA.getReturnType();
ElementCount RetVF =
(RetTy->isVectorTy() ? cast<VectorType>(RetTy)->getElementCount()
: ElementCount::getFixed(1));
const IntrinsicInst *I = ICA.getInst();
const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
FastMathFlags FMF = ICA.getFlags();
switch (IID) {
default:
break;
case Intrinsic::powi:
if (auto *RHSC = dyn_cast<ConstantInt>(Args[1])) {
bool ShouldOptForSize = I->getParent()->getParent()->hasOptSize();
if (getTLI()->isBeneficialToExpandPowI(RHSC->getSExtValue(),
ShouldOptForSize)) {
APInt Exponent = RHSC->getValue().abs();
unsigned ActiveBits = Exponent.getActiveBits();
unsigned PopCount = Exponent.countPopulation();
InstructionCost Cost = (ActiveBits + PopCount - 2) *
thisT()->getArithmeticInstrCost(
Instruction::FMul, RetTy, CostKind);
if (RHSC->getSExtValue() < 0)
Cost += thisT()->getArithmeticInstrCost(Instruction::FDiv, RetTy,
CostKind);
return Cost;
}
}
break;
case Intrinsic::cttz:
if (RetVF.isScalar() && getTLI()->isCheapToSpeculateCttz())
return TargetTransformInfo::TCC_Basic;
break;
case Intrinsic::ctlz:
if (RetVF.isScalar() && getTLI()->isCheapToSpeculateCtlz())
return TargetTransformInfo::TCC_Basic;
break;
case Intrinsic::memcpy:
return thisT()->getMemcpyCost(ICA.getInst());
case Intrinsic::masked_scatter: {
const Value *Mask = Args[3];
bool VarMask = !isa<Constant>(Mask);
Align Alignment = cast<ConstantInt>(Args[2])->getAlignValue();
return thisT()->getGatherScatterOpCost(Instruction::Store,
ICA.getArgTypes()[0], Args[1],
VarMask, Alignment, CostKind, I);
}
case Intrinsic::masked_gather: {
const Value *Mask = Args[2];
bool VarMask = !isa<Constant>(Mask);
Align Alignment = cast<ConstantInt>(Args[1])->getAlignValue();
return thisT()->getGatherScatterOpCost(Instruction::Load, RetTy, Args[0],
VarMask, Alignment, CostKind, I);
}
case Intrinsic::experimental_stepvector: {
if (isa<ScalableVectorType>(RetTy))
return BaseT::getIntrinsicInstrCost(ICA, CostKind);
return TargetTransformInfo::TCC_Basic;
}
case Intrinsic::vector_extract: {
if (isa<ScalableVectorType>(RetTy))
return BaseT::getIntrinsicInstrCost(ICA, CostKind);
unsigned Index = cast<ConstantInt>(Args[1])->getZExtValue();
return thisT()->getShuffleCost(TTI::SK_ExtractSubvector,
cast<VectorType>(Args[0]->getType()), None,
Index, cast<VectorType>(RetTy));
}
case Intrinsic::vector_insert: {
if (isa<ScalableVectorType>(Args[1]->getType()))
return BaseT::getIntrinsicInstrCost(ICA, CostKind);
unsigned Index = cast<ConstantInt>(Args[2])->getZExtValue();
return thisT()->getShuffleCost(
TTI::SK_InsertSubvector, cast<VectorType>(Args[0]->getType()), None,
Index, cast<VectorType>(Args[1]->getType()));
}
case Intrinsic::experimental_vector_reverse: {
return thisT()->getShuffleCost(TTI::SK_Reverse,
cast<VectorType>(Args[0]->getType()), None,
0, cast<VectorType>(RetTy));
}
case Intrinsic::experimental_vector_splice: {
unsigned Index = cast<ConstantInt>(Args[2])->getZExtValue();
return thisT()->getShuffleCost(TTI::SK_Splice,
cast<VectorType>(Args[0]->getType()), None,
Index, cast<VectorType>(RetTy));
}
case Intrinsic::vector_reduce_add:
case Intrinsic::vector_reduce_mul:
case Intrinsic::vector_reduce_and:
case Intrinsic::vector_reduce_or:
case Intrinsic::vector_reduce_xor:
case Intrinsic::vector_reduce_smax:
case Intrinsic::vector_reduce_smin:
case Intrinsic::vector_reduce_fmax:
case Intrinsic::vector_reduce_fmin:
case Intrinsic::vector_reduce_umax:
case Intrinsic::vector_reduce_umin: {
IntrinsicCostAttributes Attrs(IID, RetTy, Args[0]->getType(), FMF, I, 1);
return getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
}
case Intrinsic::vector_reduce_fadd:
case Intrinsic::vector_reduce_fmul: {
IntrinsicCostAttributes Attrs(
IID, RetTy, {Args[0]->getType(), Args[1]->getType()}, FMF, I, 1);
return getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
}
case Intrinsic::fshl:
case Intrinsic::fshr: {
const Value *X = Args[0];
const Value *Y = Args[1];
const Value *Z = Args[2];
TTI::OperandValueProperties OpPropsX, OpPropsY, OpPropsZ, OpPropsBW;
TTI::OperandValueKind OpKindX = TTI::getOperandInfo(X, OpPropsX);
TTI::OperandValueKind OpKindY = TTI::getOperandInfo(Y, OpPropsY);
TTI::OperandValueKind OpKindZ = TTI::getOperandInfo(Z, OpPropsZ);
TTI::OperandValueKind OpKindBW = TTI::OK_UniformConstantValue;
OpPropsBW = isPowerOf2_32(RetTy->getScalarSizeInBits()) ? TTI::OP_PowerOf2
: TTI::OP_None;
InstructionCost Cost = 0;
Cost +=
thisT()->getArithmeticInstrCost(BinaryOperator::Or, RetTy, CostKind);
Cost +=
thisT()->getArithmeticInstrCost(BinaryOperator::Sub, RetTy, CostKind);
Cost += thisT()->getArithmeticInstrCost(
BinaryOperator::Shl, RetTy, CostKind, OpKindX, OpKindZ, OpPropsX);
Cost += thisT()->getArithmeticInstrCost(
BinaryOperator::LShr, RetTy, CostKind, OpKindY, OpKindZ, OpPropsY);
if (OpKindZ != TTI::OK_UniformConstantValue &&
OpKindZ != TTI::OK_NonUniformConstantValue)
Cost += thisT()->getArithmeticInstrCost(BinaryOperator::URem, RetTy,
CostKind, OpKindZ, OpKindBW,
OpPropsZ, OpPropsBW);
if (X != Y) {
Type *CondTy = RetTy->getWithNewBitWidth(1);
Cost +=
thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
CmpInst::ICMP_EQ, CostKind);
Cost +=
thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
CmpInst::ICMP_EQ, CostKind);
}
return Cost;
}
case Intrinsic::get_active_lane_mask: {
EVT ResVT = getTLI()->getValueType(DL, RetTy, true);
EVT ArgType = getTLI()->getValueType(DL, ICA.getArgTypes()[0], true);
if (!getTLI()->shouldExpandGetActiveLaneMask(ResVT, ArgType)) {
std::pair<InstructionCost, MVT> LT =
getTLI()->getTypeLegalizationCost(DL, RetTy);
return LT.first;
}
Type *ExpRetTy = VectorType::get(
ICA.getArgTypes()[0], cast<VectorType>(RetTy)->getElementCount());
IntrinsicCostAttributes Attrs(Intrinsic::uadd_sat, ExpRetTy, {}, FMF);
InstructionCost Cost =
thisT()->getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, ExpRetTy, RetTy,
CmpInst::ICMP_ULT, CostKind);
return Cost;
}
}
InstructionCost ScalarizationCost = InstructionCost::getInvalid();
if (RetVF.isVector() && !RetVF.isScalable()) {
ScalarizationCost = 0;
if (!RetTy->isVoidTy())
ScalarizationCost +=
getScalarizationOverhead(cast<VectorType>(RetTy), true, false);
ScalarizationCost +=
getOperandsScalarizationOverhead(Args, ICA.getArgTypes());
}
IntrinsicCostAttributes Attrs(IID, RetTy, ICA.getArgTypes(), FMF, I,
ScalarizationCost);
return thisT()->getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
}
InstructionCost
getTypeBasedIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
TTI::TargetCostKind CostKind) {
Intrinsic::ID IID = ICA.getID();
Type *RetTy = ICA.getReturnType();
const SmallVectorImpl<Type *> &Tys = ICA.getArgTypes();
FastMathFlags FMF = ICA.getFlags();
InstructionCost ScalarizationCostPassed = ICA.getScalarizationCost();
bool SkipScalarizationCost = ICA.skipScalarizationCost();
VectorType *VecOpTy = nullptr;
if (!Tys.empty()) {
unsigned VecTyIndex = 0;
if (IID == Intrinsic::vector_reduce_fadd ||
IID == Intrinsic::vector_reduce_fmul)
VecTyIndex = 1;
assert(Tys.size() > VecTyIndex && "Unexpected IntrinsicCostAttributes");
VecOpTy = dyn_cast<VectorType>(Tys[VecTyIndex]);
}
unsigned SingleCallCost = CostKind == TTI::TCK_CodeSize ? 1 : 10;
unsigned ISD = 0;
switch (IID) {
default: {
if (isa<ScalableVectorType>(RetTy) || any_of(Tys, [](const Type *Ty) {
return isa<ScalableVectorType>(Ty);
}))
return InstructionCost::getInvalid();
InstructionCost ScalarizationCost =
SkipScalarizationCost ? ScalarizationCostPassed : 0;
unsigned ScalarCalls = 1;
Type *ScalarRetTy = RetTy;
if (auto *RetVTy = dyn_cast<VectorType>(RetTy)) {
if (!SkipScalarizationCost)
ScalarizationCost = getScalarizationOverhead(RetVTy, true, false);
ScalarCalls = std::max(ScalarCalls,
cast<FixedVectorType>(RetVTy)->getNumElements());
ScalarRetTy = RetTy->getScalarType();
}
SmallVector<Type *, 4> ScalarTys;
for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
Type *Ty = Tys[i];
if (auto *VTy = dyn_cast<VectorType>(Ty)) {
if (!SkipScalarizationCost)
ScalarizationCost += getScalarizationOverhead(VTy, false, true);
ScalarCalls = std::max(ScalarCalls,
cast<FixedVectorType>(VTy)->getNumElements());
Ty = Ty->getScalarType();
}
ScalarTys.push_back(Ty);
}
if (ScalarCalls == 1)
return 1;
IntrinsicCostAttributes ScalarAttrs(IID, ScalarRetTy, ScalarTys, FMF);
InstructionCost ScalarCost =
thisT()->getIntrinsicInstrCost(ScalarAttrs, CostKind);
return ScalarCalls * ScalarCost + ScalarizationCost;
}
case Intrinsic::sqrt:
ISD = ISD::FSQRT;
break;
case Intrinsic::sin:
ISD = ISD::FSIN;
break;
case Intrinsic::cos:
ISD = ISD::FCOS;
break;
case Intrinsic::exp:
ISD = ISD::FEXP;
break;
case Intrinsic::exp2:
ISD = ISD::FEXP2;
break;
case Intrinsic::log:
ISD = ISD::FLOG;
break;
case Intrinsic::log10:
ISD = ISD::FLOG10;
break;
case Intrinsic::log2:
ISD = ISD::FLOG2;
break;
case Intrinsic::fabs:
ISD = ISD::FABS;
break;
case Intrinsic::canonicalize:
ISD = ISD::FCANONICALIZE;
break;
case Intrinsic::minnum:
ISD = ISD::FMINNUM;
break;
case Intrinsic::maxnum:
ISD = ISD::FMAXNUM;
break;
case Intrinsic::minimum:
ISD = ISD::FMINIMUM;
break;
case Intrinsic::maximum:
ISD = ISD::FMAXIMUM;
break;
case Intrinsic::copysign:
ISD = ISD::FCOPYSIGN;
break;
case Intrinsic::floor:
ISD = ISD::FFLOOR;
break;
case Intrinsic::ceil:
ISD = ISD::FCEIL;
break;
case Intrinsic::trunc:
ISD = ISD::FTRUNC;
break;
case Intrinsic::nearbyint:
ISD = ISD::FNEARBYINT;
break;
case Intrinsic::rint:
ISD = ISD::FRINT;
break;
case Intrinsic::round:
ISD = ISD::FROUND;
break;
case Intrinsic::roundeven:
ISD = ISD::FROUNDEVEN;
break;
case Intrinsic::pow:
ISD = ISD::FPOW;
break;
case Intrinsic::fma:
ISD = ISD::FMA;
break;
case Intrinsic::fmuladd:
ISD = ISD::FMA;
break;
case Intrinsic::experimental_constrained_fmuladd:
ISD = ISD::STRICT_FMA;
break;
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
case Intrinsic::sideeffect:
case Intrinsic::pseudoprobe:
case Intrinsic::arithmetic_fence:
return 0;
case Intrinsic::masked_store: {
Type *Ty = Tys[0];
Align TyAlign = thisT()->DL.getABITypeAlign(Ty);
return thisT()->getMaskedMemoryOpCost(Instruction::Store, Ty, TyAlign, 0,
CostKind);
}
case Intrinsic::masked_load: {
Type *Ty = RetTy;
Align TyAlign = thisT()->DL.getABITypeAlign(Ty);
return thisT()->getMaskedMemoryOpCost(Instruction::Load, Ty, TyAlign, 0,
CostKind);
}
case Intrinsic::vector_reduce_add:
return thisT()->getArithmeticReductionCost(Instruction::Add, VecOpTy,
None, CostKind);
case Intrinsic::vector_reduce_mul:
return thisT()->getArithmeticReductionCost(Instruction::Mul, VecOpTy,
None, CostKind);
case Intrinsic::vector_reduce_and:
return thisT()->getArithmeticReductionCost(Instruction::And, VecOpTy,
None, CostKind);
case Intrinsic::vector_reduce_or:
return thisT()->getArithmeticReductionCost(Instruction::Or, VecOpTy, None,
CostKind);
case Intrinsic::vector_reduce_xor:
return thisT()->getArithmeticReductionCost(Instruction::Xor, VecOpTy,
None, CostKind);
case Intrinsic::vector_reduce_fadd:
return thisT()->getArithmeticReductionCost(Instruction::FAdd, VecOpTy,
FMF, CostKind);
case Intrinsic::vector_reduce_fmul:
return thisT()->getArithmeticReductionCost(Instruction::FMul, VecOpTy,
FMF, CostKind);
case Intrinsic::vector_reduce_smax:
case Intrinsic::vector_reduce_smin:
case Intrinsic::vector_reduce_fmax:
case Intrinsic::vector_reduce_fmin:
return thisT()->getMinMaxReductionCost(
VecOpTy, cast<VectorType>(CmpInst::makeCmpResultType(VecOpTy)),
false, CostKind);
case Intrinsic::vector_reduce_umax:
case Intrinsic::vector_reduce_umin:
return thisT()->getMinMaxReductionCost(
VecOpTy, cast<VectorType>(CmpInst::makeCmpResultType(VecOpTy)),
true, CostKind);
case Intrinsic::abs: {
Type *CondTy = RetTy->getWithNewBitWidth(1);
CmpInst::Predicate Pred = CmpInst::ICMP_SGT;
InstructionCost Cost = 0;
Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
Pred, CostKind);
Cost += thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
Pred, CostKind);
Cost += thisT()->getArithmeticInstrCost(
BinaryOperator::Sub, RetTy, CostKind, TTI::OK_UniformConstantValue);
return Cost;
}
case Intrinsic::smax:
case Intrinsic::smin:
case Intrinsic::umax:
case Intrinsic::umin: {
Type *CondTy = RetTy->getWithNewBitWidth(1);
bool IsUnsigned = IID == Intrinsic::umax || IID == Intrinsic::umin;
CmpInst::Predicate Pred =
IsUnsigned ? CmpInst::ICMP_UGT : CmpInst::ICMP_SGT;
InstructionCost Cost = 0;
Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
Pred, CostKind);
Cost += thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
Pred, CostKind);
return Cost;
}
case Intrinsic::sadd_sat:
case Intrinsic::ssub_sat: {
Type *CondTy = RetTy->getWithNewBitWidth(1);
Type *OpTy = StructType::create({RetTy, CondTy});
Intrinsic::ID OverflowOp = IID == Intrinsic::sadd_sat
? Intrinsic::sadd_with_overflow
: Intrinsic::ssub_with_overflow;
CmpInst::Predicate Pred = CmpInst::ICMP_SGT;
InstructionCost Cost = 0;
IntrinsicCostAttributes Attrs(OverflowOp, OpTy, {RetTy, RetTy}, FMF,
nullptr, ScalarizationCostPassed);
Cost += thisT()->getIntrinsicInstrCost(Attrs, CostKind);
Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
Pred, CostKind);
Cost += 2 * thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy,
CondTy, Pred, CostKind);
return Cost;
}
case Intrinsic::uadd_sat:
case Intrinsic::usub_sat: {
Type *CondTy = RetTy->getWithNewBitWidth(1);
Type *OpTy = StructType::create({RetTy, CondTy});
Intrinsic::ID OverflowOp = IID == Intrinsic::uadd_sat
? Intrinsic::uadd_with_overflow
: Intrinsic::usub_with_overflow;
InstructionCost Cost = 0;
IntrinsicCostAttributes Attrs(OverflowOp, OpTy, {RetTy, RetTy}, FMF,
nullptr, ScalarizationCostPassed);
Cost += thisT()->getIntrinsicInstrCost(Attrs, CostKind);
Cost +=
thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
CmpInst::BAD_ICMP_PREDICATE, CostKind);
return Cost;
}
case Intrinsic::smul_fix:
case Intrinsic::umul_fix: {
unsigned ExtSize = RetTy->getScalarSizeInBits() * 2;
Type *ExtTy = RetTy->getWithNewBitWidth(ExtSize);
unsigned ExtOp =
IID == Intrinsic::smul_fix ? Instruction::SExt : Instruction::ZExt;
TTI::CastContextHint CCH = TTI::CastContextHint::None;
InstructionCost Cost = 0;
Cost += 2 * thisT()->getCastInstrCost(ExtOp, ExtTy, RetTy, CCH, CostKind);
Cost +=
thisT()->getArithmeticInstrCost(Instruction::Mul, ExtTy, CostKind);
Cost += 2 * thisT()->getCastInstrCost(Instruction::Trunc, RetTy, ExtTy,
CCH, CostKind);
Cost += thisT()->getArithmeticInstrCost(Instruction::LShr, RetTy,
CostKind, TTI::OK_AnyValue,
TTI::OK_UniformConstantValue);
Cost += thisT()->getArithmeticInstrCost(Instruction::Shl, RetTy, CostKind,
TTI::OK_AnyValue,
TTI::OK_UniformConstantValue);
Cost += thisT()->getArithmeticInstrCost(Instruction::Or, RetTy, CostKind);
return Cost;
}
case Intrinsic::sadd_with_overflow:
case Intrinsic::ssub_with_overflow: {
Type *SumTy = RetTy->getContainedType(0);
Type *OverflowTy = RetTy->getContainedType(1);
unsigned Opcode = IID == Intrinsic::sadd_with_overflow
? BinaryOperator::Add
: BinaryOperator::Sub;
InstructionCost Cost = 0;
Cost += thisT()->getArithmeticInstrCost(Opcode, SumTy, CostKind);
Cost += 2 * thisT()->getCmpSelInstrCost(
Instruction::ICmp, SumTy, OverflowTy,
CmpInst::ICMP_SGT, CostKind);
Cost += thisT()->getArithmeticInstrCost(BinaryOperator::Xor, OverflowTy,
CostKind);
return Cost;
}
case Intrinsic::uadd_with_overflow:
case Intrinsic::usub_with_overflow: {
Type *SumTy = RetTy->getContainedType(0);
Type *OverflowTy = RetTy->getContainedType(1);
unsigned Opcode = IID == Intrinsic::uadd_with_overflow
? BinaryOperator::Add
: BinaryOperator::Sub;
CmpInst::Predicate Pred = IID == Intrinsic::uadd_with_overflow
? CmpInst::ICMP_ULT
: CmpInst::ICMP_UGT;
InstructionCost Cost = 0;
Cost += thisT()->getArithmeticInstrCost(Opcode, SumTy, CostKind);
Cost +=
thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, SumTy, OverflowTy,
Pred, CostKind);
return Cost;
}
case Intrinsic::smul_with_overflow:
case Intrinsic::umul_with_overflow: {
Type *MulTy = RetTy->getContainedType(0);
Type *OverflowTy = RetTy->getContainedType(1);
unsigned ExtSize = MulTy->getScalarSizeInBits() * 2;
Type *ExtTy = MulTy->getWithNewBitWidth(ExtSize);
bool IsSigned = IID == Intrinsic::smul_with_overflow;
unsigned ExtOp = IsSigned ? Instruction::SExt : Instruction::ZExt;
TTI::CastContextHint CCH = TTI::CastContextHint::None;
InstructionCost Cost = 0;
Cost += 2 * thisT()->getCastInstrCost(ExtOp, ExtTy, MulTy, CCH, CostKind);
Cost +=
thisT()->getArithmeticInstrCost(Instruction::Mul, ExtTy, CostKind);
Cost += 2 * thisT()->getCastInstrCost(Instruction::Trunc, MulTy, ExtTy,
CCH, CostKind);
Cost += thisT()->getArithmeticInstrCost(Instruction::LShr, ExtTy,
CostKind, TTI::OK_AnyValue,
TTI::OK_UniformConstantValue);
if (IsSigned)
Cost += thisT()->getArithmeticInstrCost(Instruction::AShr, MulTy,
CostKind, TTI::OK_AnyValue,
TTI::OK_UniformConstantValue);
Cost += thisT()->getCmpSelInstrCost(
BinaryOperator::ICmp, MulTy, OverflowTy, CmpInst::ICMP_NE, CostKind);
return Cost;
}
case Intrinsic::fptosi_sat:
case Intrinsic::fptoui_sat: {
if (Tys.empty())
break;
Type *FromTy = Tys[0];
bool IsSigned = IID == Intrinsic::fptosi_sat;
InstructionCost Cost = 0;
IntrinsicCostAttributes Attrs1(Intrinsic::minnum, FromTy,
{FromTy, FromTy});
Cost += thisT()->getIntrinsicInstrCost(Attrs1, CostKind);
IntrinsicCostAttributes Attrs2(Intrinsic::maxnum, FromTy,
{FromTy, FromTy});
Cost += thisT()->getIntrinsicInstrCost(Attrs2, CostKind);
Cost += thisT()->getCastInstrCost(
IsSigned ? Instruction::FPToSI : Instruction::FPToUI, RetTy, FromTy,
TTI::CastContextHint::None, CostKind);
if (IsSigned) {
Type *CondTy = RetTy->getWithNewBitWidth(1);
Cost += thisT()->getCmpSelInstrCost(
BinaryOperator::FCmp, FromTy, CondTy, CmpInst::FCMP_UNO, CostKind);
Cost += thisT()->getCmpSelInstrCost(
BinaryOperator::Select, RetTy, CondTy, CmpInst::FCMP_UNO, CostKind);
}
return Cost;
}
case Intrinsic::ctpop:
ISD = ISD::CTPOP;
SingleCallCost = TargetTransformInfo::TCC_Expensive;
break;
case Intrinsic::ctlz:
ISD = ISD::CTLZ;
break;
case Intrinsic::cttz:
ISD = ISD::CTTZ;
break;
case Intrinsic::bswap:
ISD = ISD::BSWAP;
break;
case Intrinsic::bitreverse:
ISD = ISD::BITREVERSE;
break;
}
const TargetLoweringBase *TLI = getTLI();
std::pair<InstructionCost, MVT> LT =
TLI->getTypeLegalizationCost(DL, RetTy);
if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
if (IID == Intrinsic::fabs && LT.second.isFloatingPoint() &&
TLI->isFAbsFree(LT.second)) {
return 0;
}
if (LT.first > 1)
return (LT.first * 2);
else
return (LT.first * 1);
} else if (!TLI->isOperationExpand(ISD, LT.second)) {
return (LT.first * 2);
}
if (IID == Intrinsic::fmuladd)
return thisT()->getArithmeticInstrCost(BinaryOperator::FMul, RetTy,
CostKind) +
thisT()->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy,
CostKind);
if (IID == Intrinsic::experimental_constrained_fmuladd) {
IntrinsicCostAttributes FMulAttrs(
Intrinsic::experimental_constrained_fmul, RetTy, Tys);
IntrinsicCostAttributes FAddAttrs(
Intrinsic::experimental_constrained_fadd, RetTy, Tys);
return thisT()->getIntrinsicInstrCost(FMulAttrs, CostKind) +
thisT()->getIntrinsicInstrCost(FAddAttrs, CostKind);
}
if (auto *RetVTy = dyn_cast<VectorType>(RetTy)) {
if (isa<ScalableVectorType>(RetTy) || any_of(Tys, [](const Type *Ty) {
return isa<ScalableVectorType>(Ty);
}))
return InstructionCost::getInvalid();
InstructionCost ScalarizationCost =
SkipScalarizationCost ? ScalarizationCostPassed
: getScalarizationOverhead(RetVTy, true, false);
unsigned ScalarCalls = cast<FixedVectorType>(RetVTy)->getNumElements();
SmallVector<Type *, 4> ScalarTys;
for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
Type *Ty = Tys[i];
if (Ty->isVectorTy())
Ty = Ty->getScalarType();
ScalarTys.push_back(Ty);
}
IntrinsicCostAttributes Attrs(IID, RetTy->getScalarType(), ScalarTys, FMF);
InstructionCost ScalarCost =
thisT()->getIntrinsicInstrCost(Attrs, CostKind);
for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
if (auto *VTy = dyn_cast<VectorType>(Tys[i])) {
if (!ICA.skipScalarizationCost())
ScalarizationCost += getScalarizationOverhead(VTy, false, true);
ScalarCalls = std::max(ScalarCalls,
cast<FixedVectorType>(VTy)->getNumElements());
}
}
return ScalarCalls * ScalarCost + ScalarizationCost;
}
return SingleCallCost;
}
InstructionCost getCallInstrCost(Function *F, Type *RetTy,
ArrayRef<Type *> Tys,
TTI::TargetCostKind CostKind) {
return 10;
}
unsigned getNumberOfParts(Type *Tp) {
std::pair<InstructionCost, MVT> LT =
getTLI()->getTypeLegalizationCost(DL, Tp);
return LT.first.isValid() ? *LT.first.getValue() : 0;
}
InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *,
const SCEV *) {
return 0;
}
InstructionCost getTreeReductionCost(unsigned Opcode, VectorType *Ty,
TTI::TargetCostKind CostKind) {
if (isa<ScalableVectorType>(Ty))
return InstructionCost::getInvalid();
Type *ScalarTy = Ty->getElementType();
unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements();
if ((Opcode == Instruction::Or || Opcode == Instruction::And) &&
ScalarTy == IntegerType::getInt1Ty(Ty->getContext()) &&
NumVecElts >= 2) {
Type *ValTy = IntegerType::get(Ty->getContext(), NumVecElts);
return thisT()->getCastInstrCost(Instruction::BitCast, ValTy, Ty,
TTI::CastContextHint::None, CostKind) +
thisT()->getCmpSelInstrCost(Instruction::ICmp, ValTy,
CmpInst::makeCmpResultType(ValTy),
CmpInst::BAD_ICMP_PREDICATE, CostKind);
}
unsigned NumReduxLevels = Log2_32(NumVecElts);
InstructionCost ArithCost = 0;
InstructionCost ShuffleCost = 0;
std::pair<InstructionCost, MVT> LT =
thisT()->getTLI()->getTypeLegalizationCost(DL, Ty);
unsigned LongVectorCount = 0;
unsigned MVTLen =
LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
while (NumVecElts > MVTLen) {
NumVecElts /= 2;
VectorType *SubTy = FixedVectorType::get(ScalarTy, NumVecElts);
ShuffleCost += thisT()->getShuffleCost(TTI::SK_ExtractSubvector, Ty, None,
NumVecElts, SubTy);
ArithCost += thisT()->getArithmeticInstrCost(Opcode, SubTy, CostKind);
Ty = SubTy;
++LongVectorCount;
}
NumReduxLevels -= LongVectorCount;
ShuffleCost += NumReduxLevels * thisT()->getShuffleCost(
TTI::SK_PermuteSingleSrc, Ty, None, 0, Ty);
ArithCost +=
NumReduxLevels * thisT()->getArithmeticInstrCost(Opcode, Ty, CostKind);
return ShuffleCost + ArithCost +
thisT()->getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
}
InstructionCost getOrderedReductionCost(unsigned Opcode, VectorType *Ty,
TTI::TargetCostKind CostKind) {
if (isa<ScalableVectorType>(Ty))
return InstructionCost::getInvalid();
auto *VTy = cast<FixedVectorType>(Ty);
InstructionCost ExtractCost =
getScalarizationOverhead(VTy, false, true);
InstructionCost ArithCost = thisT()->getArithmeticInstrCost(
Opcode, VTy->getElementType(), CostKind);
ArithCost *= VTy->getNumElements();
return ExtractCost + ArithCost;
}
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
Optional<FastMathFlags> FMF,
TTI::TargetCostKind CostKind) {
if (TTI::requiresOrderedReduction(FMF))
return getOrderedReductionCost(Opcode, Ty, CostKind);
return getTreeReductionCost(Opcode, Ty, CostKind);
}
InstructionCost getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
bool IsUnsigned,
TTI::TargetCostKind CostKind) {
if (isa<ScalableVectorType>(Ty))
return InstructionCost::getInvalid();
Type *ScalarTy = Ty->getElementType();
Type *ScalarCondTy = CondTy->getElementType();
unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements();
unsigned NumReduxLevels = Log2_32(NumVecElts);
unsigned CmpOpcode;
if (Ty->isFPOrFPVectorTy()) {
CmpOpcode = Instruction::FCmp;
} else {
assert(Ty->isIntOrIntVectorTy() &&
"expecting floating point or integer type for min/max reduction");
CmpOpcode = Instruction::ICmp;
}
InstructionCost MinMaxCost = 0;
InstructionCost ShuffleCost = 0;
std::pair<InstructionCost, MVT> LT =
thisT()->getTLI()->getTypeLegalizationCost(DL, Ty);
unsigned LongVectorCount = 0;
unsigned MVTLen =
LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
while (NumVecElts > MVTLen) {
NumVecElts /= 2;
auto *SubTy = FixedVectorType::get(ScalarTy, NumVecElts);
CondTy = FixedVectorType::get(ScalarCondTy, NumVecElts);
ShuffleCost += thisT()->getShuffleCost(TTI::SK_ExtractSubvector, Ty, None,
NumVecElts, SubTy);
MinMaxCost +=
thisT()->getCmpSelInstrCost(CmpOpcode, SubTy, CondTy,
CmpInst::BAD_ICMP_PREDICATE, CostKind) +
thisT()->getCmpSelInstrCost(Instruction::Select, SubTy, CondTy,
CmpInst::BAD_ICMP_PREDICATE, CostKind);
Ty = SubTy;
++LongVectorCount;
}
NumReduxLevels -= LongVectorCount;
ShuffleCost += NumReduxLevels * thisT()->getShuffleCost(
TTI::SK_PermuteSingleSrc, Ty, None, 0, Ty);
MinMaxCost +=
NumReduxLevels *
(thisT()->getCmpSelInstrCost(CmpOpcode, Ty, CondTy,
CmpInst::BAD_ICMP_PREDICATE, CostKind) +
thisT()->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
CmpInst::BAD_ICMP_PREDICATE, CostKind));
return ShuffleCost + MinMaxCost +
thisT()->getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
}
InstructionCost getExtendedAddReductionCost(bool IsMLA, bool IsUnsigned,
Type *ResTy, VectorType *Ty,
TTI::TargetCostKind CostKind) {
VectorType *ExtTy = VectorType::get(ResTy, Ty);
InstructionCost RedCost = thisT()->getArithmeticReductionCost(
Instruction::Add, ExtTy, None, CostKind);
InstructionCost MulCost = 0;
InstructionCost ExtCost = thisT()->getCastInstrCost(
IsUnsigned ? Instruction::ZExt : Instruction::SExt, ExtTy, Ty,
TTI::CastContextHint::None, CostKind);
if (IsMLA) {
MulCost =
thisT()->getArithmeticInstrCost(Instruction::Mul, ExtTy, CostKind);
ExtCost *= 2;
}
return RedCost + MulCost + ExtCost;
}
InstructionCost getVectorSplitCost() { return 1; }
};
class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
using BaseT = BasicTTIImplBase<BasicTTIImpl>;
friend class BasicTTIImplBase<BasicTTIImpl>;
const TargetSubtargetInfo *ST;
const TargetLoweringBase *TLI;
const TargetSubtargetInfo *getST() const { return ST; }
const TargetLoweringBase *getTLI() const { return TLI; }
public:
explicit BasicTTIImpl(const TargetMachine *TM, const Function &F);
};
}
#endif