1 //===- BasicTargetTransformInfo.cpp - Basic target-independent TTI impl ---===//
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 the implementation of a basic TargetTransformInfo pass
11 /// predicated on the target abstractions present in the target independent
12 /// code generator. It uses these (primarily TargetLowering) to model as much
13 /// of the TTI query interface as possible. It is included by most targets so
14 /// that they can specialize only a small subset of the query space.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "basictti"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Target/TargetLowering.h"
28 class BasicTTI final : public ImmutablePass, public TargetTransformInfo {
29 const TargetMachine *TM;
31 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
32 /// are set if the result needs to be inserted and/or extracted from vectors.
33 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
35 const TargetLoweringBase *getTLI() const { return TM->getTargetLowering(); }
38 BasicTTI() : ImmutablePass(ID), TM(0) {
39 llvm_unreachable("This pass cannot be directly constructed");
42 BasicTTI(const TargetMachine *TM) : ImmutablePass(ID), TM(TM) {
43 initializeBasicTTIPass(*PassRegistry::getPassRegistry());
46 virtual void initializePass() override {
50 virtual void finalizePass() {
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
55 TargetTransformInfo::getAnalysisUsage(AU);
58 /// Pass identification.
61 /// Provide necessary pointer adjustments for the two base classes.
62 virtual void *getAdjustedAnalysisPointer(const void *ID) override {
63 if (ID == &TargetTransformInfo::ID)
64 return (TargetTransformInfo*)this;
68 virtual bool hasBranchDivergence() const override;
70 /// \name Scalar TTI Implementations
73 virtual bool isLegalAddImmediate(int64_t imm) const override;
74 virtual bool isLegalICmpImmediate(int64_t imm) const override;
75 virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
76 int64_t BaseOffset, bool HasBaseReg,
77 int64_t Scale) const override;
78 virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
79 int64_t BaseOffset, bool HasBaseReg,
80 int64_t Scale) const override;
81 virtual bool isTruncateFree(Type *Ty1, Type *Ty2) const override;
82 virtual bool isTypeLegal(Type *Ty) const override;
83 virtual unsigned getJumpBufAlignment() const override;
84 virtual unsigned getJumpBufSize() const override;
85 virtual bool shouldBuildLookupTables() const override;
86 virtual bool haveFastSqrt(Type *Ty) const override;
87 virtual void getUnrollingPreferences(
88 Loop *L, UnrollingPreferences &UP) const override;
92 /// \name Vector TTI Implementations
95 virtual unsigned getNumberOfRegisters(bool Vector) const override;
96 virtual unsigned getMaximumUnrollFactor() const override;
97 virtual unsigned getRegisterBitWidth(bool Vector) const override;
98 virtual unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
100 OperandValueKind) const override;
101 virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp,
102 int Index, Type *SubTp) const override;
103 virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst,
104 Type *Src) const override;
105 virtual unsigned getCFInstrCost(unsigned Opcode) const override;
106 virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
107 Type *CondTy) const override;
108 virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
109 unsigned Index) const override;
110 virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
112 unsigned AddressSpace) const override;
113 virtual unsigned getIntrinsicInstrCost(
114 Intrinsic::ID, Type *RetTy, ArrayRef<Type*> Tys) const override;
115 virtual unsigned getNumberOfParts(Type *Tp) const override;
116 virtual unsigned getAddressComputationCost(
117 Type *Ty, bool IsComplex) const override;
118 virtual unsigned getReductionCost(unsigned Opcode, Type *Ty,
119 bool IsPairwise) const override;
126 INITIALIZE_AG_PASS(BasicTTI, TargetTransformInfo, "basictti",
127 "Target independent code generator's TTI", true, true, false)
128 char BasicTTI::ID = 0;
131 llvm::createBasicTargetTransformInfoPass(const TargetMachine *TM) {
132 return new BasicTTI(TM);
135 bool BasicTTI::hasBranchDivergence() const { return false; }
137 bool BasicTTI::isLegalAddImmediate(int64_t imm) const {
138 return getTLI()->isLegalAddImmediate(imm);
141 bool BasicTTI::isLegalICmpImmediate(int64_t imm) const {
142 return getTLI()->isLegalICmpImmediate(imm);
145 bool BasicTTI::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
146 int64_t BaseOffset, bool HasBaseReg,
147 int64_t Scale) const {
148 TargetLoweringBase::AddrMode AM;
150 AM.BaseOffs = BaseOffset;
151 AM.HasBaseReg = HasBaseReg;
153 return getTLI()->isLegalAddressingMode(AM, Ty);
156 int BasicTTI::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
157 int64_t BaseOffset, bool HasBaseReg,
158 int64_t Scale) const {
159 TargetLoweringBase::AddrMode AM;
161 AM.BaseOffs = BaseOffset;
162 AM.HasBaseReg = HasBaseReg;
164 return getTLI()->getScalingFactorCost(AM, Ty);
167 bool BasicTTI::isTruncateFree(Type *Ty1, Type *Ty2) const {
168 return getTLI()->isTruncateFree(Ty1, Ty2);
171 bool BasicTTI::isTypeLegal(Type *Ty) const {
172 EVT T = getTLI()->getValueType(Ty);
173 return getTLI()->isTypeLegal(T);
176 unsigned BasicTTI::getJumpBufAlignment() const {
177 return getTLI()->getJumpBufAlignment();
180 unsigned BasicTTI::getJumpBufSize() const {
181 return getTLI()->getJumpBufSize();
184 bool BasicTTI::shouldBuildLookupTables() const {
185 const TargetLoweringBase *TLI = getTLI();
186 return TLI->supportJumpTables() &&
187 (TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
188 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
191 bool BasicTTI::haveFastSqrt(Type *Ty) const {
192 const TargetLoweringBase *TLI = getTLI();
193 EVT VT = TLI->getValueType(Ty);
194 return TLI->isTypeLegal(VT) && TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
197 void BasicTTI::getUnrollingPreferences(Loop *, UnrollingPreferences &) const { }
199 //===----------------------------------------------------------------------===//
201 // Calls used by the vectorizers.
203 //===----------------------------------------------------------------------===//
205 unsigned BasicTTI::getScalarizationOverhead(Type *Ty, bool Insert,
206 bool Extract) const {
207 assert (Ty->isVectorTy() && "Can only scalarize vectors");
210 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
212 Cost += TopTTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
214 Cost += TopTTI->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
220 unsigned BasicTTI::getNumberOfRegisters(bool Vector) const {
224 unsigned BasicTTI::getRegisterBitWidth(bool Vector) const {
228 unsigned BasicTTI::getMaximumUnrollFactor() const {
232 unsigned BasicTTI::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
234 OperandValueKind) const {
235 // Check if any of the operands are vector operands.
236 const TargetLoweringBase *TLI = getTLI();
237 int ISD = TLI->InstructionOpcodeToISD(Opcode);
238 assert(ISD && "Invalid opcode");
240 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Ty);
242 bool IsFloat = Ty->getScalarType()->isFloatingPointTy();
243 // Assume that floating point arithmetic operations cost twice as much as
244 // integer operations.
245 unsigned OpCost = (IsFloat ? 2 : 1);
247 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
248 // The operation is legal. Assume it costs 1.
249 // If the type is split to multiple registers, assume that there is some
251 // TODO: Once we have extract/insert subvector cost we need to use them.
253 return LT.first * 2 * OpCost;
254 return LT.first * 1 * OpCost;
257 if (!TLI->isOperationExpand(ISD, LT.second)) {
258 // If the operation is custom lowered then assume
259 // thare the code is twice as expensive.
260 return LT.first * 2 * OpCost;
263 // Else, assume that we need to scalarize this op.
264 if (Ty->isVectorTy()) {
265 unsigned Num = Ty->getVectorNumElements();
266 unsigned Cost = TopTTI->getArithmeticInstrCost(Opcode, Ty->getScalarType());
267 // return the cost of multiple scalar invocation plus the cost of inserting
268 // and extracting the values.
269 return getScalarizationOverhead(Ty, true, true) + Num * Cost;
272 // We don't know anything about this scalar instruction.
276 unsigned BasicTTI::getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
281 unsigned BasicTTI::getCastInstrCost(unsigned Opcode, Type *Dst,
283 const TargetLoweringBase *TLI = getTLI();
284 int ISD = TLI->InstructionOpcodeToISD(Opcode);
285 assert(ISD && "Invalid opcode");
287 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(Src);
288 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(Dst);
290 // Check for NOOP conversions.
291 if (SrcLT.first == DstLT.first &&
292 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
294 // Bitcast between types that are legalized to the same type are free.
295 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
299 if (Opcode == Instruction::Trunc &&
300 TLI->isTruncateFree(SrcLT.second, DstLT.second))
303 if (Opcode == Instruction::ZExt &&
304 TLI->isZExtFree(SrcLT.second, DstLT.second))
307 // If the cast is marked as legal (or promote) then assume low cost.
308 if (TLI->isOperationLegalOrPromote(ISD, DstLT.second))
311 // Handle scalar conversions.
312 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
314 // Scalar bitcasts are usually free.
315 if (Opcode == Instruction::BitCast)
318 // Just check the op cost. If the operation is legal then assume it costs 1.
319 if (!TLI->isOperationExpand(ISD, DstLT.second))
322 // Assume that illegal scalar instruction are expensive.
326 // Check vector-to-vector casts.
327 if (Dst->isVectorTy() && Src->isVectorTy()) {
329 // If the cast is between same-sized registers, then the check is simple.
330 if (SrcLT.first == DstLT.first &&
331 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
333 // Assume that Zext is done using AND.
334 if (Opcode == Instruction::ZExt)
337 // Assume that sext is done using SHL and SRA.
338 if (Opcode == Instruction::SExt)
341 // Just check the op cost. If the operation is legal then assume it costs
342 // 1 and multiply by the type-legalization overhead.
343 if (!TLI->isOperationExpand(ISD, DstLT.second))
344 return SrcLT.first * 1;
347 // If we are converting vectors and the operation is illegal, or
348 // if the vectors are legalized to different types, estimate the
349 // scalarization costs.
350 unsigned Num = Dst->getVectorNumElements();
351 unsigned Cost = TopTTI->getCastInstrCost(Opcode, Dst->getScalarType(),
352 Src->getScalarType());
354 // Return the cost of multiple scalar invocation plus the cost of
355 // inserting and extracting the values.
356 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
359 // We already handled vector-to-vector and scalar-to-scalar conversions. This
360 // is where we handle bitcast between vectors and scalars. We need to assume
361 // that the conversion is scalarized in one way or another.
362 if (Opcode == Instruction::BitCast)
363 // Illegal bitcasts are done by storing and loading from a stack slot.
364 return (Src->isVectorTy()? getScalarizationOverhead(Src, false, true):0) +
365 (Dst->isVectorTy()? getScalarizationOverhead(Dst, true, false):0);
367 llvm_unreachable("Unhandled cast");
370 unsigned BasicTTI::getCFInstrCost(unsigned Opcode) const {
371 // Branches are assumed to be predicted.
375 unsigned BasicTTI::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
376 Type *CondTy) const {
377 const TargetLoweringBase *TLI = getTLI();
378 int ISD = TLI->InstructionOpcodeToISD(Opcode);
379 assert(ISD && "Invalid opcode");
381 // Selects on vectors are actually vector selects.
382 if (ISD == ISD::SELECT) {
383 assert(CondTy && "CondTy must exist");
384 if (CondTy->isVectorTy())
388 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(ValTy);
390 if (!TLI->isOperationExpand(ISD, LT.second)) {
391 // The operation is legal. Assume it costs 1. Multiply
392 // by the type-legalization overhead.
396 // Otherwise, assume that the cast is scalarized.
397 if (ValTy->isVectorTy()) {
398 unsigned Num = ValTy->getVectorNumElements();
400 CondTy = CondTy->getScalarType();
401 unsigned Cost = TopTTI->getCmpSelInstrCost(Opcode, ValTy->getScalarType(),
404 // Return the cost of multiple scalar invocation plus the cost of inserting
405 // and extracting the values.
406 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
409 // Unknown scalar opcode.
413 unsigned BasicTTI::getVectorInstrCost(unsigned Opcode, Type *Val,
414 unsigned Index) const {
418 unsigned BasicTTI::getMemoryOpCost(unsigned Opcode, Type *Src,
420 unsigned AddressSpace) const {
421 assert(!Src->isVoidTy() && "Invalid type");
422 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Src);
424 // Assume that all loads of legal types cost 1.
428 unsigned BasicTTI::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
429 ArrayRef<Type *> Tys) const {
433 // Assume that we need to scalarize this intrinsic.
434 unsigned ScalarizationCost = 0;
435 unsigned ScalarCalls = 1;
436 if (RetTy->isVectorTy()) {
437 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
438 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
440 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
441 if (Tys[i]->isVectorTy()) {
442 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
443 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
447 return ScalarCalls + ScalarizationCost;
449 // Look for intrinsics that can be lowered directly or turned into a scalar
451 case Intrinsic::sqrt: ISD = ISD::FSQRT; break;
452 case Intrinsic::sin: ISD = ISD::FSIN; break;
453 case Intrinsic::cos: ISD = ISD::FCOS; break;
454 case Intrinsic::exp: ISD = ISD::FEXP; break;
455 case Intrinsic::exp2: ISD = ISD::FEXP2; break;
456 case Intrinsic::log: ISD = ISD::FLOG; break;
457 case Intrinsic::log10: ISD = ISD::FLOG10; break;
458 case Intrinsic::log2: ISD = ISD::FLOG2; break;
459 case Intrinsic::fabs: ISD = ISD::FABS; break;
460 case Intrinsic::copysign: ISD = ISD::FCOPYSIGN; break;
461 case Intrinsic::floor: ISD = ISD::FFLOOR; break;
462 case Intrinsic::ceil: ISD = ISD::FCEIL; break;
463 case Intrinsic::trunc: ISD = ISD::FTRUNC; break;
464 case Intrinsic::nearbyint:
465 ISD = ISD::FNEARBYINT; break;
466 case Intrinsic::rint: ISD = ISD::FRINT; break;
467 case Intrinsic::round: ISD = ISD::FROUND; break;
468 case Intrinsic::pow: ISD = ISD::FPOW; break;
469 case Intrinsic::fma: ISD = ISD::FMA; break;
470 case Intrinsic::fmuladd: ISD = ISD::FMA; break; // FIXME: mul + add?
471 case Intrinsic::lifetime_start:
472 case Intrinsic::lifetime_end:
476 const TargetLoweringBase *TLI = getTLI();
477 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(RetTy);
479 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
480 // The operation is legal. Assume it costs 1.
481 // If the type is split to multiple registers, assume that thre is some
483 // TODO: Once we have extract/insert subvector cost we need to use them.
489 if (!TLI->isOperationExpand(ISD, LT.second)) {
490 // If the operation is custom lowered then assume
491 // thare the code is twice as expensive.
495 // Else, assume that we need to scalarize this intrinsic. For math builtins
496 // this will emit a costly libcall, adding call overhead and spills. Make it
498 if (RetTy->isVectorTy()) {
499 unsigned Num = RetTy->getVectorNumElements();
500 unsigned Cost = TopTTI->getIntrinsicInstrCost(IID, RetTy->getScalarType(),
502 return 10 * Cost * Num;
505 // This is going to be turned into a library call, make it expensive.
509 unsigned BasicTTI::getNumberOfParts(Type *Tp) const {
510 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Tp);
514 unsigned BasicTTI::getAddressComputationCost(Type *Ty, bool IsComplex) const {
518 unsigned BasicTTI::getReductionCost(unsigned Opcode, Type *Ty,
519 bool IsPairwise) const {
520 assert(Ty->isVectorTy() && "Expect a vector type");
521 unsigned NumVecElts = Ty->getVectorNumElements();
522 unsigned NumReduxLevels = Log2_32(NumVecElts);
523 unsigned ArithCost = NumReduxLevels *
524 TopTTI->getArithmeticInstrCost(Opcode, Ty);
525 // Assume the pairwise shuffles add a cost.
526 unsigned ShuffleCost =
527 NumReduxLevels * (IsPairwise + 1) *
528 TopTTI->getShuffleCost(SK_ExtractSubvector, Ty, NumVecElts / 2, Ty);
529 return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);